Fix comment in gcc/config/arm/predicates.md
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blobedb3886a03a13cb80d4f7e7618d71c5ffec103a3
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 @ifclear vms
183 * The Ada-to-XML converter gnat2xml::
184 @end ifclear
185 * The GNAT Metrics Tool gnatmetric::
186 * File Name Krunching with gnatkr::
187 * Preprocessing with gnatprep::
188 * The GNAT Library Browser gnatls::
189 * Cleaning Up with gnatclean::
190 @ifclear vms
191 * GNAT and Libraries::
192 * Using the GNU make Utility::
193 @end ifclear
194 * Memory Management Issues::
195 * Stack Related Facilities::
196 * Verifying Properties with gnatcheck::
197 * Creating Sample Bodies with gnatstub::
198 * Creating Unit Tests with gnattest::
199 * Performing Dimensionality Analysis in GNAT::
200 * Generating Ada Bindings for C and C++ headers::
201 * Other Utility Programs::
202 @ifclear vms
203 * Code Coverage and Profiling::
204 @end ifclear
205 * Running and Debugging Ada Programs::
206 @ifset vms
207 * Compatibility with HP Ada::
208 @end ifset
209 * Platform-Specific Information for the Run-Time Libraries::
210 * Example of Binder Output File::
211 * Elaboration Order Handling in GNAT::
212 * Overflow Check Handling in GNAT::
213 * Conditional Compilation::
214 * Inline Assembler::
215 * Compatibility and Porting Guide::
216 * Microsoft Windows Topics::
217 * Mac OS Topics::
218 * GNU Free Documentation License::
219 * Index::
220 @end menu
221 @end ifnottex
223 @node About This Guide
224 @unnumbered About This Guide
226 @noindent
227 @ifset vms
228 This guide describes the use of @value{EDITION},
229 a compiler and software development toolset for the full Ada
230 programming language, implemented on OpenVMS for HP's Alpha and
231 Integrity server (I64) platforms.
232 @end ifset
233 @ifclear vms
234 This guide describes the use of @value{EDITION},
235 a compiler and software development
236 toolset for the full Ada programming language.
237 @end ifclear
238 It documents the features of the compiler and tools, and explains
239 how to use them to build Ada applications.
241 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
242 invoked in Ada 83 compatibility mode.
243 By default, @value{EDITION} assumes Ada 2012, but you can override with a
244 compiler switch (@pxref{Compiling Different Versions of Ada})
245 to explicitly specify the language version.
246 Throughout this manual, references to ``Ada'' without a year suffix
247 apply to all Ada 95/2005/2012 versions of the language.
249 @ifclear FSFEDITION
250 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
251 ``GNAT'' in the remainder of this document.
252 @end ifclear
255 @menu
256 * What This Guide Contains::
257 * What You Should Know before Reading This Guide::
258 * Related Information::
259 * Conventions::
260 @end menu
262 @node What This Guide Contains
263 @unnumberedsec What This Guide Contains
265 @noindent
266 This guide contains the following chapters:
267 @itemize @bullet
269 @item
270 @ref{Getting Started with GNAT}, describes how to get started compiling
271 and running Ada programs with the GNAT Ada programming environment.
272 @item
273 @ref{The GNAT Compilation Model}, describes the compilation model used
274 by GNAT.
276 @item
277 @ref{Compiling with gcc}, describes how to compile
278 Ada programs with @command{gcc}, the Ada compiler.
280 @item
281 @ref{Binding with gnatbind}, describes how to
282 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
283 utility.
285 @item
286 @ref{Linking with gnatlink},
287 describes @command{gnatlink}, a
288 program that provides for linking using the GNAT run-time library to
289 construct a program. @command{gnatlink} can also incorporate foreign language
290 object units into the executable.
292 @item
293 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
294 utility that automatically determines the set of sources
295 needed by an Ada compilation unit, and executes the necessary compilations
296 binding and link.
298 @item
299 @ref{Improving Performance}, shows various techniques for making your
300 Ada program run faster or take less space.
301 It discusses the effect of the compiler's optimization switch and
302 also describes the @command{gnatelim} tool and unused subprogram/data
303 elimination.
305 @item
306 @ref{Renaming Files with gnatchop}, describes
307 @code{gnatchop}, a utility that allows you to preprocess a file that
308 contains Ada source code, and split it into one or more new files, one
309 for each compilation unit.
311 @item
312 @ref{Configuration Pragmas}, describes the configuration pragmas
313 handled by GNAT.
315 @item
316 @ref{Handling Arbitrary File Naming Conventions with gnatname},
317 shows how to override the default GNAT file naming conventions,
318 either for an individual unit or globally.
320 @item
321 @ref{GNAT Project Manager}, describes how to use project files
322 to organize large projects.
324 @item
325 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
326 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
327 way to navigate through sources.
329 @item
330 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
331 version of an Ada source file with control over casing, indentation,
332 comment placement, and other elements of program presentation style.
334 @ifclear vms
335 @item
336 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
337 source code into XML.
338 @end ifclear
340 @item
341 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
342 metrics for an Ada source file, such as the number of types and subprograms,
343 and assorted complexity measures.
345 @item
346 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
347 file name krunching utility, used to handle shortened
348 file names on operating systems with a limit on the length of names.
350 @item
351 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
352 preprocessor utility that allows a single source file to be used to
353 generate multiple or parameterized source files by means of macro
354 substitution.
356 @item
357 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
358 utility that displays information about compiled units, including dependences
359 on the corresponding sources files, and consistency of compilations.
361 @item
362 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
363 to delete files that are produced by the compiler, binder and linker.
365 @ifclear vms
366 @item
367 @ref{GNAT and Libraries}, describes the process of creating and using
368 Libraries with GNAT. It also describes how to recompile the GNAT run-time
369 library.
371 @item
372 @ref{Using the GNU make Utility}, describes some techniques for using
373 the GNAT toolset in Makefiles.
374 @end ifclear
376 @item
377 @ref{Memory Management Issues}, describes some useful predefined storage pools
378 and in particular the GNAT Debug Pool facility, which helps detect incorrect
379 memory references.
380 @ifclear vms
381 It also describes @command{gnatmem}, a utility that monitors dynamic
382 allocation and deallocation and helps detect ``memory leaks''.
383 @end ifclear
385 @item
386 @ref{Stack Related Facilities}, describes some useful tools associated with
387 stack checking and analysis.
389 @item
390 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
391 a utility that checks Ada code against a set of rules.
393 @item
394 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
395 a utility that generates empty but compilable bodies for library units.
397 @item
398 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
399 a utility that generates unit testing templates for library units.
401 @item
402 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
403 facilities used in GNAT to declare dimensioned objects, and to verify that
404 uses of these objects are consistent with their given physical dimensions
405 (so that meters cannot be assigned to kilograms, and so on).
407 @item
408 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
409 generate automatically Ada bindings from C and C++ headers.
411 @item
412 @ref{Other Utility Programs}, discusses several other GNAT utilities,
413 including @code{gnathtml}.
415 @ifclear vms
416 @item
417 @ref{Code Coverage and Profiling}, describes how to perform a structural
418 coverage and profile the execution of Ada programs.
419 @end ifclear
421 @item
422 @ref{Running and Debugging Ada Programs}, describes how to run and debug
423 Ada programs.
425 @ifset vms
426 @item
427 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
428 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
429 developed by Digital Equipment Corporation and currently supported by HP.}
430 for OpenVMS Alpha. This product was formerly known as DEC Ada,
431 @cindex DEC Ada
432 and for
433 historical compatibility reasons, the relevant libraries still use the
434 DEC prefix.
435 @end ifset
437 @item
438 @ref{Platform-Specific Information for the Run-Time Libraries},
439 describes the various run-time
440 libraries supported by GNAT on various platforms and explains how to
441 choose a particular library.
443 @item
444 @ref{Example of Binder Output File}, shows the source code for the binder
445 output file for a sample program.
447 @item
448 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
449 you deal with elaboration order issues.
451 @item
452 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
453 you deal with arithmetic overflow issues.
455 @item
456 @ref{Conditional Compilation}, describes how to model conditional compilation,
457 both with Ada in general and with GNAT facilities in particular.
459 @item
460 @ref{Inline Assembler}, shows how to use the inline assembly facility
461 in an Ada program.
463 @item
464 @ref{Compatibility and Porting Guide}, contains sections on compatibility
465 of GNAT with other Ada development environments (including Ada 83 systems),
466 to assist in porting code from those environments.
468 @ifset unw
469 @item
470 @ref{Microsoft Windows Topics}, presents information relevant to the
471 Microsoft Windows platform.
473 @item
474 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
475 platform.
476 @end ifset
477 @end itemize
479 @c *************************************************
480 @node What You Should Know before Reading This Guide
481 @c *************************************************
482 @unnumberedsec What You Should Know before Reading This Guide
484 @cindex Ada 95 Language Reference Manual
485 @cindex Ada 2005 Language Reference Manual
486 @noindent
487 This guide assumes a basic familiarity with the Ada 95 language, as
488 described in the International Standard ANSI/ISO/IEC-8652:1995, January
489 1995.
490 It does not require knowledge of the new features introduced by Ada 2005,
491 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
492 and Amendment 1).
493 Both reference manuals are included in the GNAT documentation
494 package.
496 @node Related Information
497 @unnumberedsec Related Information
499 @noindent
500 For further information about related tools, refer to the following
501 documents:
503 @itemize @bullet
504 @item
505 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
506 Reference Manual}, which contains all reference material for the GNAT
507 implementation of Ada.
509 @ifset unw
510 @item
511 @cite{Using the GNAT Programming Studio}, which describes the GPS
512 Integrated Development Environment.
514 @item
515 @cite{GNAT Programming Studio Tutorial}, which introduces the
516 main GPS features through examples.
517 @end ifset
519 @item
520 @cite{Ada 95 Reference Manual}, which contains reference
521 material for the Ada 95 programming language.
523 @item
524 @cite{Ada 2005 Reference Manual}, which contains reference
525 material for the Ada 2005 programming language.
527 @item
528 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
529 @ifset vms
530 in the GNU:[DOCS] directory,
531 @end ifset
532 for all details on the use of the GNU source-level debugger.
534 @item
535 @xref{Top,, The extensible self-documenting text editor, emacs,
536 GNU Emacs Manual},
537 @ifset vms
538 located in the GNU:[DOCS] directory if the EMACS kit is installed,
539 @end ifset
540 for full information on the extensible editor and programming
541 environment Emacs.
543 @end itemize
545 @c **************
546 @node Conventions
547 @unnumberedsec Conventions
548 @cindex Conventions
549 @cindex Typographical conventions
551 @noindent
552 Following are examples of the typographical and graphic conventions used
553 in this guide:
555 @itemize @bullet
556 @item
557 @code{Functions}, @command{utility program names}, @code{standard names},
558 and @code{classes}.
560 @item
561 @option{Option flags}
563 @item
564 @file{File names}, @samp{button names}, and @samp{field names}.
566 @item
567 @code{Variables}, @env{environment variables}, and @var{metasyntactic
568 variables}.
570 @item
571 @emph{Emphasis}.
573 @item
574 @r{[}optional information or parameters@r{]}
576 @item
577 Examples are described by text
578 @smallexample
579 and then shown this way.
580 @end smallexample
581 @end itemize
583 @noindent
584 Commands that are entered by the user are preceded in this manual by the
585 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
586 uses this sequence as a prompt, then the commands will appear exactly as
587 you see them in the manual. If your system uses some other prompt, then
588 the command will appear with the @code{$} replaced by whatever prompt
589 character you are using.
591 @ifset unw
592 Full file names are shown with the ``@code{/}'' character
593 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
594 If you are using GNAT on a Windows platform, please note that
595 the ``@code{\}'' character should be used instead.
596 @end ifset
598 @c ****************************
599 @node Getting Started with GNAT
600 @chapter Getting Started with GNAT
602 @noindent
603 This chapter describes some simple ways of using GNAT to build
604 executable Ada programs.
605 @ifset unw
606 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
607 show how to use the command line environment.
608 @ref{Introduction to GPS}, provides a brief
609 introduction to the GNAT Programming Studio, a visually-oriented
610 Integrated Development Environment for GNAT.
611 GPS offers a graphical ``look and feel'', support for development in
612 other programming languages, comprehensive browsing features, and
613 many other capabilities.
614 For information on GPS please refer to
615 @cite{Using the GNAT Programming Studio}.
616 @end ifset
618 @menu
619 * Running GNAT::
620 * Running a Simple Ada Program::
621 * Running a Program with Multiple Units::
622 * Using the gnatmake Utility::
623 @ifset vms
624 * Editing with Emacs::
625 @end ifset
626 @ifclear vms
627 * Introduction to GPS::
628 @end ifclear
629 @end menu
631 @node Running GNAT
632 @section Running GNAT
634 @noindent
635 Three steps are needed to create an executable file from an Ada source
636 file:
638 @enumerate
639 @item
640 The source file(s) must be compiled.
641 @item
642 The file(s) must be bound using the GNAT binder.
643 @item
644 All appropriate object files must be linked to produce an executable.
645 @end enumerate
647 @noindent
648 All three steps are most commonly handled by using the @command{gnatmake}
649 utility program that, given the name of the main program, automatically
650 performs the necessary compilation, binding and linking steps.
652 @node Running a Simple Ada Program
653 @section Running a Simple Ada Program
655 @noindent
656 Any text editor may be used to prepare an Ada program.
657 (If @code{Emacs} is
658 used, the optional Ada mode may be helpful in laying out the program.)
660 program text is a normal text file. We will assume in our initial
661 example that you have used your editor to prepare the following
662 standard format text file:
664 @smallexample @c ada
665 @cartouche
666 with Ada.Text_IO; use Ada.Text_IO;
667 procedure Hello is
668 begin
669    Put_Line ("Hello WORLD!");
670 end Hello;
671 @end cartouche
672 @end smallexample
674 @noindent
675 This file should be named @file{hello.adb}.
676 With the normal default file naming conventions, GNAT requires
677 that each file
678 contain a single compilation unit whose file name is the
679 unit name,
680 with periods replaced by hyphens; the
681 extension is @file{ads} for a
682 spec and @file{adb} for a body.
683 You can override this default file naming convention by use of the
684 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
685 Alternatively, if you want to rename your files according to this default
686 convention, which is probably more convenient if you will be using GNAT
687 for all your compilations, then the @code{gnatchop} utility
688 can be used to generate correctly-named source files
689 (@pxref{Renaming Files with gnatchop}).
691 You can compile the program using the following command (@code{$} is used
692 as the command prompt in the examples in this document):
694 @smallexample
695 $ gcc -c hello.adb
696 @end smallexample
698 @noindent
699 @command{gcc} is the command used to run the compiler. This compiler is
700 capable of compiling programs in several languages, including Ada and
701 C. It assumes that you have given it an Ada program if the file extension is
702 either @file{.ads} or @file{.adb}, and it will then call
703 the GNAT compiler to compile the specified file.
705 @ifclear vms
706 The @option{-c} switch is required. It tells @command{gcc} to only do a
707 compilation. (For C programs, @command{gcc} can also do linking, but this
708 capability is not used directly for Ada programs, so the @option{-c}
709 switch must always be present.)
710 @end ifclear
712 This compile command generates a file
713 @file{hello.o}, which is the object
714 file corresponding to your Ada program. It also generates
715 an ``Ada Library Information'' file @file{hello.ali},
716 which contains additional information used to check
717 that an Ada program is consistent.
718 To build an executable file,
719 use @code{gnatbind} to bind the program
720 and @command{gnatlink} to link it. The
721 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
722 @file{ALI} file, but the default extension of @file{.ali} can
723 be omitted. This means that in the most common case, the argument
724 is simply the name of the main program:
726 @smallexample
727 $ gnatbind hello
728 $ gnatlink hello
729 @end smallexample
731 @noindent
732 A simpler method of carrying out these steps is to use
733 @command{gnatmake},
734 a master program that invokes all the required
735 compilation, binding and linking tools in the correct order. In particular,
736 @command{gnatmake} automatically recompiles any sources that have been
737 modified since they were last compiled, or sources that depend
738 on such modified sources, so that ``version skew'' is avoided.
739 @cindex Version skew (avoided by @command{gnatmake})
741 @smallexample
742 $ gnatmake hello.adb
743 @end smallexample
745 @noindent
746 The result is an executable program called @file{hello}, which can be
747 run by entering:
749 @smallexample
750 $ ^hello^RUN HELLO^
751 @end smallexample
753 @noindent
754 assuming that the current directory is on the search path
755 for executable programs.
757 @noindent
758 and, if all has gone well, you will see
760 @smallexample
761 Hello WORLD!
762 @end smallexample
764 @noindent
765 appear in response to this command.
767 @c ****************************************
768 @node Running a Program with Multiple Units
769 @section Running a Program with Multiple Units
771 @noindent
772 Consider a slightly more complicated example that has three files: a
773 main program, and the spec and body of a package:
775 @smallexample @c ada
776 @cartouche
777 @group
778 package Greetings is
779    procedure Hello;
780    procedure Goodbye;
781 end Greetings;
783 with Ada.Text_IO; use Ada.Text_IO;
784 package body Greetings is
785    procedure Hello is
786    begin
787       Put_Line ("Hello WORLD!");
788    end Hello;
790    procedure Goodbye is
791    begin
792       Put_Line ("Goodbye WORLD!");
793    end Goodbye;
794 end Greetings;
795 @end group
797 @group
798 with Greetings;
799 procedure Gmain is
800 begin
801    Greetings.Hello;
802    Greetings.Goodbye;
803 end Gmain;
804 @end group
805 @end cartouche
806 @end smallexample
808 @noindent
809 Following the one-unit-per-file rule, place this program in the
810 following three separate files:
812 @table @file
813 @item greetings.ads
814 spec of package @code{Greetings}
816 @item greetings.adb
817 body of package @code{Greetings}
819 @item gmain.adb
820 body of main program
821 @end table
823 @noindent
824 To build an executable version of
825 this program, we could use four separate steps to compile, bind, and link
826 the program, as follows:
828 @smallexample
829 $ gcc -c gmain.adb
830 $ gcc -c greetings.adb
831 $ gnatbind gmain
832 $ gnatlink gmain
833 @end smallexample
835 @noindent
836 Note that there is no required order of compilation when using GNAT.
837 In particular it is perfectly fine to compile the main program first.
838 Also, it is not necessary to compile package specs in the case where
839 there is an accompanying body; you only need to compile the body. If you want
840 to submit these files to the compiler for semantic checking and not code
841 generation, then use the
842 @option{-gnatc} switch:
844 @smallexample
845 $ gcc -c greetings.ads -gnatc
846 @end smallexample
848 @noindent
849 Although the compilation can be done in separate steps as in the
850 above example, in practice it is almost always more convenient
851 to use the @command{gnatmake} tool. All you need to know in this case
852 is the name of the main program's source file. The effect of the above four
853 commands can be achieved with a single one:
855 @smallexample
856 $ gnatmake gmain.adb
857 @end smallexample
859 @noindent
860 In the next section we discuss the advantages of using @command{gnatmake} in
861 more detail.
863 @c *****************************
864 @node Using the gnatmake Utility
865 @section Using the @command{gnatmake} Utility
867 @noindent
868 If you work on a program by compiling single components at a time using
869 @command{gcc}, you typically keep track of the units you modify. In order to
870 build a consistent system, you compile not only these units, but also any
871 units that depend on the units you have modified.
872 For example, in the preceding case,
873 if you edit @file{gmain.adb}, you only need to recompile that file. But if
874 you edit @file{greetings.ads}, you must recompile both
875 @file{greetings.adb} and @file{gmain.adb}, because both files contain
876 units that depend on @file{greetings.ads}.
878 @code{gnatbind} will warn you if you forget one of these compilation
879 steps, so that it is impossible to generate an inconsistent program as a
880 result of forgetting to do a compilation. Nevertheless it is tedious and
881 error-prone to keep track of dependencies among units.
882 One approach to handle the dependency-bookkeeping is to use a
883 makefile. However, makefiles present maintenance problems of their own:
884 if the dependencies change as you change the program, you must make
885 sure that the makefile is kept up-to-date manually, which is also an
886 error-prone process.
888 The @command{gnatmake} utility takes care of these details automatically.
889 Invoke it using either one of the following forms:
891 @smallexample
892 $ gnatmake gmain.adb
893 $ gnatmake ^gmain^GMAIN^
894 @end smallexample
896 @noindent
897 The argument is the name of the file containing the main program;
898 you may omit the extension. @command{gnatmake}
899 examines the environment, automatically recompiles any files that need
900 recompiling, and binds and links the resulting set of object files,
901 generating the executable file, @file{^gmain^GMAIN.EXE^}.
902 In a large program, it
903 can be extremely helpful to use @command{gnatmake}, because working out by hand
904 what needs to be recompiled can be difficult.
906 Note that @command{gnatmake}
907 takes into account all the Ada rules that
908 establish dependencies among units. These include dependencies that result
909 from inlining subprogram bodies, and from
910 generic instantiation. Unlike some other
911 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
912 found by the compiler on a previous compilation, which may possibly
913 be wrong when sources change. @command{gnatmake} determines the exact set of
914 dependencies from scratch each time it is run.
916 @ifset vms
917 @node Editing with Emacs
918 @section Editing with Emacs
919 @cindex Emacs
921 @noindent
922 Emacs is an extensible self-documenting text editor that is available in a
923 separate VMSINSTAL kit.
925 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
926 click on the Emacs Help menu and run the Emacs Tutorial.
927 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
928 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
930 Documentation on Emacs and other tools is available in Emacs under the
931 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
932 use the middle mouse button to select a topic (e.g.@: Emacs).
934 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
935 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
936 get to the Emacs manual.
937 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
938 prompt.
940 The tutorial is highly recommended in order to learn the intricacies of Emacs,
941 which is sufficiently extensible to provide for a complete programming
942 environment and shell for the sophisticated user.
943 @end ifset
945 @ifclear vms
946 @node Introduction to GPS
947 @section Introduction to GPS
948 @cindex GPS (GNAT Programming Studio)
949 @cindex GNAT Programming Studio (GPS)
950 @noindent
951 Although the command line interface (@command{gnatmake}, etc.) alone
952 is sufficient, a graphical Interactive Development
953 Environment can make it easier for you to compose, navigate, and debug
954 programs.  This section describes the main features of GPS
955 (``GNAT Programming Studio''), the GNAT graphical IDE.
956 You will see how to use GPS to build and debug an executable, and
957 you will also learn some of the basics of the GNAT ``project'' facility.
959 GPS enables you to do much more than is presented here;
960 e.g., you can produce a call graph, interface to a third-party
961 Version Control System, and inspect the generated assembly language
962 for a program.
963 Indeed, GPS also supports languages other than Ada.
964 Such additional information, and an explanation of all of the GPS menu
965 items. may be found in the on-line help, which includes
966 a user's guide and a tutorial (these are also accessible from the GNAT
967 startup menu).
969 @menu
970 * Building a New Program with GPS::
971 * Simple Debugging with GPS::
972 @end menu
974 @node Building a New Program with GPS
975 @subsection Building a New Program with GPS
976 @noindent
977 GPS invokes the GNAT compilation tools using information
978 contained in a @emph{project} (also known as a @emph{project file}):
979 a collection of properties such
980 as source directories, identities of main subprograms, tool switches, etc.,
981 and their associated values.
982 See @ref{GNAT Project Manager} for details.
983 In order to run GPS, you will need to either create a new project
984 or else open an existing one.
986 This section will explain how you can use GPS to create a project,
987 to associate Ada source files with a project, and to build and run
988 programs.
990 @enumerate
991 @item @emph{Creating a project}
993 Invoke GPS, either from the command line or the platform's IDE.
994 After it starts, GPS will display a ``Welcome'' screen with three
995 radio buttons:
997 @itemize @bullet
998 @item
999 @code{Start with default project in directory}
1001 @item
1002 @code{Create new project with wizard}
1004 @item
1005 @code{Open existing project}
1006 @end itemize
1008 @noindent
1009 Select @code{Create new project with wizard} and press @code{OK}.
1010 A new window will appear.  In the text box labeled with
1011 @code{Enter the name of the project to create}, type @file{sample}
1012 as the project name.
1013 In the next box, browse to choose the directory in which you
1014 would like to create the project file.
1015 After selecting an appropriate directory, press @code{Forward}.
1017 A window will appear with the title
1018 @code{Version Control System Configuration}.
1019 Simply press @code{Forward}.
1021 A window will appear with the title
1022 @code{Please select the source directories for this project}.
1023 The directory that you specified for the project file will be selected
1024 by default as the one to use for sources; simply press @code{Forward}.
1026 A window will appear with the title
1027 @code{Please select the build directory for this project}.
1028 The directory that you specified for the project file will be selected
1029 by default for object files and executables;
1030 simply press @code{Forward}.
1032 A window will appear with the title
1033 @code{Please select the main units for this project}.
1034 You will supply this information later, after creating the source file.
1035 Simply press @code{Forward} for now.
1037 A window will appear with the title
1038 @code{Please select the switches to build the project}.
1039 Press @code{Apply}.  This will create a project file named
1040 @file{sample.prj} in the directory that you had specified.
1042 @item @emph{Creating and saving the source file}
1044 After you create the new project, a GPS window will appear, which is
1045 partitioned into two main sections:
1047 @itemize @bullet
1048 @item
1049 A @emph{Workspace area}, initially greyed out, which you will use for
1050 creating and editing source files
1052 @item
1053 Directly below, a @emph{Messages area}, which initially displays a
1054 ``Welcome'' message.
1055 (If the Messages area is not visible, drag its border upward to expand it.)
1056 @end itemize
1058 @noindent
1059 Select @code{File} on the menu bar, and then the @code{New} command.
1060 The Workspace area will become white, and you can now
1061 enter the source program explicitly.
1062 Type the following text
1064 @smallexample @c ada
1065 @group
1066 with Ada.Text_IO; use Ada.Text_IO;
1067 procedure Hello is
1068 begin
1069   Put_Line("Hello from GPS!");
1070 end Hello;
1071 @end group
1072 @end smallexample
1074 @noindent
1075 Select @code{File}, then @code{Save As}, and enter the source file name
1076 @file{hello.adb}.
1077 The file will be saved in the same directory you specified as the
1078 location of the default project file.
1080 @item @emph{Updating the project file}
1082 You need to add the new source file to the project.
1083 To do this, select
1084 the @code{Project} menu and then @code{Edit project properties}.
1085 Click the @code{Main files} tab on the left, and then the
1086 @code{Add} button.
1087 Choose @file{hello.adb} from the list, and press @code{Open}.
1088 The project settings window will reflect this action.
1089 Click @code{OK}.
1091 @item @emph{Building and running the program}
1093 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1094 and select @file{hello.adb}.
1095 The Messages window will display the resulting invocations of @command{gcc},
1096 @command{gnatbind}, and @command{gnatlink}
1097 (reflecting the default switch settings from the
1098 project file that you created) and then a ``successful compilation/build''
1099 message.
1101 To run the program, choose the @code{Build} menu, then @code{Run}, and
1102 select @command{hello}.
1103 An @emph{Arguments Selection} window will appear.
1104 There are no command line arguments, so just click @code{OK}.
1106 The Messages window will now display the program's output (the string
1107 @code{Hello from GPS}), and at the bottom of the GPS window a status
1108 update is displayed (@code{Run: hello}).
1109 Close the GPS window (or select @code{File}, then @code{Exit}) to
1110 terminate this GPS session.
1111 @end enumerate
1113 @node Simple Debugging with GPS
1114 @subsection Simple Debugging with GPS
1115 @noindent
1116 This section illustrates basic debugging techniques (setting breakpoints,
1117 examining/modifying variables, single stepping).
1119 @enumerate
1120 @item @emph{Opening a project}
1122 Start GPS and select @code{Open existing project}; browse to
1123 specify the project file @file{sample.prj} that you had created in the
1124 earlier example.
1126 @item @emph{Creating a source file}
1128 Select @code{File}, then @code{New}, and type in the following program:
1130 @smallexample @c ada
1131 @group
1132 with Ada.Text_IO; use Ada.Text_IO;
1133 procedure Example is
1134    Line : String (1..80);
1135    N    : Natural;
1136 begin
1137    Put_Line("Type a line of text at each prompt; an empty line to exit");
1138    loop
1139       Put(": ");
1140       Get_Line (Line, N);
1141       Put_Line (Line (1..N) );
1142       exit when N=0;
1143    end loop;
1144 end Example;
1145 @end group
1146 @end smallexample
1148 @noindent
1149 Select @code{File}, then @code{Save as}, and enter the file name
1150 @file{example.adb}.
1152 @item @emph{Updating the project file}
1154 Add @code{Example} as a new main unit for the project:
1155 @enumerate a
1156 @item
1157 Select @code{Project}, then @code{Edit Project Properties}.
1159 @item
1160 Select the @code{Main files} tab, click @code{Add}, then
1161 select the file @file{example.adb} from the list, and
1162 click @code{Open}.
1163 You will see the file name appear in the list of main units
1165 @item
1166 Click @code{OK}
1167 @end enumerate
1169 @item @emph{Building/running the executable}
1171 To build the executable
1172 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1174 Run the program to see its effect (in the Messages area).
1175 Each line that you enter is displayed; an empty line will
1176 cause the loop to exit and the program to terminate.
1178 @item @emph{Debugging the program}
1180 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1181 which are required for debugging, are on by default when you create
1182 a new project.
1183 Thus unless you intentionally remove these settings, you will be able
1184 to debug any program that you develop using GPS.
1186 @enumerate a
1187 @item @emph{Initializing}
1189 Select @code{Debug}, then @code{Initialize}, then @file{example}
1191 @item @emph{Setting a breakpoint}
1193 After performing the initialization step, you will observe a small
1194 icon to the right of each line number.
1195 This serves as a toggle for breakpoints; clicking the icon will
1196 set a breakpoint at the corresponding line (the icon will change to
1197 a red circle with an ``x''), and clicking it again
1198 will remove the breakpoint / reset the icon.
1200 For purposes of this example, set a breakpoint at line 10 (the
1201 statement @code{Put_Line@ (Line@ (1..N));}
1203 @item @emph{Starting program execution}
1205 Select @code{Debug}, then @code{Run}.  When the
1206 @code{Program Arguments} window appears, click @code{OK}.
1207 A console window will appear; enter some line of text,
1208 e.g.@: @code{abcde}, at the prompt.
1209 The program will pause execution when it gets to the
1210 breakpoint, and the corresponding line is highlighted.
1212 @item @emph{Examining a variable}
1214 Move the mouse over one of the occurrences of the variable @code{N}.
1215 You will see the value (5) displayed, in ``tool tip'' fashion.
1216 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1217 You will see information about @code{N} appear in the @code{Debugger Data}
1218 pane, showing the value as 5.
1220 @item @emph{Assigning a new value to a variable}
1222 Right click on the @code{N} in the @code{Debugger Data} pane, and
1223 select @code{Set value of N}.
1224 When the input window appears, enter the value @code{4} and click
1225 @code{OK}.
1226 This value does not automatically appear in the @code{Debugger Data}
1227 pane; to see it, right click again on the @code{N} in the
1228 @code{Debugger Data} pane and select @code{Update value}.
1229 The new value, 4, will appear in red.
1231 @item @emph{Single stepping}
1233 Select @code{Debug}, then @code{Next}.
1234 This will cause the next statement to be executed, in this case the
1235 call of @code{Put_Line} with the string slice.
1236 Notice in the console window that the displayed string is simply
1237 @code{abcd} and not @code{abcde} which you had entered.
1238 This is because the upper bound of the slice is now 4 rather than 5.
1240 @item @emph{Removing a breakpoint}
1242 Toggle the breakpoint icon at line 10.
1244 @item @emph{Resuming execution from a breakpoint}
1246 Select @code{Debug}, then @code{Continue}.
1247 The program will reach the next iteration of the loop, and
1248 wait for input after displaying the prompt.
1249 This time, just hit the @kbd{Enter} key.
1250 The value of @code{N} will be 0, and the program will terminate.
1251 The console window will disappear.
1252 @end enumerate
1253 @end enumerate
1254 @end ifclear
1256 @node The GNAT Compilation Model
1257 @chapter The GNAT Compilation Model
1258 @cindex GNAT compilation model
1259 @cindex Compilation model
1261 @menu
1262 * Source Representation::
1263 * Foreign Language Representation::
1264 * File Naming Rules::
1265 * Using Other File Names::
1266 * Alternative File Naming Schemes::
1267 * Generating Object Files::
1268 * Source Dependencies::
1269 * The Ada Library Information Files::
1270 * Binding an Ada Program::
1271 * Mixed Language Programming::
1272 @ifclear vms
1273 * Building Mixed Ada & C++ Programs::
1274 * Comparison between GNAT and C/C++ Compilation Models::
1275 @end ifclear
1276 * Comparison between GNAT and Conventional Ada Library Models::
1277 @ifset vms
1278 * Placement of temporary files::
1279 @end ifset
1280 @end menu
1282 @noindent
1283 This chapter describes the compilation model used by GNAT. Although
1284 similar to that used by other languages, such as C and C++, this model
1285 is substantially different from the traditional Ada compilation models,
1286 which are based on a library. The model is initially described without
1287 reference to the library-based model. If you have not previously used an
1288 Ada compiler, you need only read the first part of this chapter. The
1289 last section describes and discusses the differences between the GNAT
1290 model and the traditional Ada compiler models. If you have used other
1291 Ada compilers, this section will help you to understand those
1292 differences, and the advantages of the GNAT model.
1294 @node Source Representation
1295 @section Source Representation
1296 @cindex Latin-1
1298 @noindent
1299 Ada source programs are represented in standard text files, using
1300 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1301 7-bit ASCII set, plus additional characters used for
1302 representing foreign languages (@pxref{Foreign Language Representation}
1303 for support of non-USA character sets). The format effector characters
1304 are represented using their standard ASCII encodings, as follows:
1306 @table @code
1307 @item VT
1308 @findex VT
1309 Vertical tab, @code{16#0B#}
1311 @item HT
1312 @findex HT
1313 Horizontal tab, @code{16#09#}
1315 @item CR
1316 @findex CR
1317 Carriage return, @code{16#0D#}
1319 @item LF
1320 @findex LF
1321 Line feed, @code{16#0A#}
1323 @item FF
1324 @findex FF
1325 Form feed, @code{16#0C#}
1326 @end table
1328 @noindent
1329 Source files are in standard text file format. In addition, GNAT will
1330 recognize a wide variety of stream formats, in which the end of
1331 physical lines is marked by any of the following sequences:
1332 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1333 in accommodating files that are imported from other operating systems.
1335 @cindex End of source file
1336 @cindex Source file, end
1337 @findex SUB
1338 The end of a source file is normally represented by the physical end of
1339 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1340 recognized as signalling the end of the source file. Again, this is
1341 provided for compatibility with other operating systems where this
1342 code is used to represent the end of file.
1344 Each file contains a single Ada compilation unit, including any pragmas
1345 associated with the unit. For example, this means you must place a
1346 package declaration (a package @dfn{spec}) and the corresponding body in
1347 separate files. An Ada @dfn{compilation} (which is a sequence of
1348 compilation units) is represented using a sequence of files. Similarly,
1349 you will place each subunit or child unit in a separate file.
1351 @node Foreign Language Representation
1352 @section Foreign Language Representation
1354 @noindent
1355 GNAT supports the standard character sets defined in Ada as well as
1356 several other non-standard character sets for use in localized versions
1357 of the compiler (@pxref{Character Set Control}).
1358 @menu
1359 * Latin-1::
1360 * Other 8-Bit Codes::
1361 * Wide Character Encodings::
1362 @end menu
1364 @node Latin-1
1365 @subsection Latin-1
1366 @cindex Latin-1
1368 @noindent
1369 The basic character set is Latin-1. This character set is defined by ISO
1370 standard 8859, part 1. The lower half (character codes @code{16#00#}
1371 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1372 half is used to represent additional characters. These include extended letters
1373 used by European languages, such as French accents, the vowels with umlauts
1374 used in German, and the extra letter A-ring used in Swedish.
1376 @findex Ada.Characters.Latin_1
1377 For a complete list of Latin-1 codes and their encodings, see the source
1378 file of library unit @code{Ada.Characters.Latin_1} in file
1379 @file{a-chlat1.ads}.
1380 You may use any of these extended characters freely in character or
1381 string literals. In addition, the extended characters that represent
1382 letters can be used in identifiers.
1384 @node Other 8-Bit Codes
1385 @subsection Other 8-Bit Codes
1387 @noindent
1388 GNAT also supports several other 8-bit coding schemes:
1390 @table @asis
1391 @item ISO 8859-2 (Latin-2)
1392 @cindex Latin-2
1393 @cindex ISO 8859-2
1394 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1395 equivalence.
1397 @item ISO 8859-3 (Latin-3)
1398 @cindex Latin-3
1399 @cindex ISO 8859-3
1400 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1401 equivalence.
1403 @item ISO 8859-4 (Latin-4)
1404 @cindex Latin-4
1405 @cindex ISO 8859-4
1406 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1407 equivalence.
1409 @item ISO 8859-5 (Cyrillic)
1410 @cindex ISO 8859-5
1411 @cindex Cyrillic
1412 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1413 lowercase equivalence.
1415 @item ISO 8859-15 (Latin-9)
1416 @cindex ISO 8859-15
1417 @cindex Latin-9
1418 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1419 lowercase equivalence
1421 @item IBM PC (code page 437)
1422 @cindex code page 437
1423 This code page is the normal default for PCs in the U.S. It corresponds
1424 to the original IBM PC character set. This set has some, but not all, of
1425 the extended Latin-1 letters, but these letters do not have the same
1426 encoding as Latin-1. In this mode, these letters are allowed in
1427 identifiers with uppercase and lowercase equivalence.
1429 @item IBM PC (code page 850)
1430 @cindex code page 850
1431 This code page is a modification of 437 extended to include all the
1432 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1433 mode, all these letters are allowed in identifiers with uppercase and
1434 lowercase equivalence.
1436 @item Full Upper 8-bit
1437 Any character in the range 80-FF allowed in identifiers, and all are
1438 considered distinct. In other words, there are no uppercase and lowercase
1439 equivalences in this range. This is useful in conjunction with
1440 certain encoding schemes used for some foreign character sets (e.g.,
1441 the typical method of representing Chinese characters on the PC).
1443 @item No Upper-Half
1444 No upper-half characters in the range 80-FF are allowed in identifiers.
1445 This gives Ada 83 compatibility for identifier names.
1446 @end table
1448 @noindent
1449 For precise data on the encodings permitted, and the uppercase and lowercase
1450 equivalences that are recognized, see the file @file{csets.adb} in
1451 the GNAT compiler sources. You will need to obtain a full source release
1452 of GNAT to obtain this file.
1454 @node Wide Character Encodings
1455 @subsection Wide Character Encodings
1457 @noindent
1458 GNAT allows wide character codes to appear in character and string
1459 literals, and also optionally in identifiers, by means of the following
1460 possible encoding schemes:
1462 @table @asis
1464 @item Hex Coding
1465 In this encoding, a wide character is represented by the following five
1466 character sequence:
1468 @smallexample
1469 ESC a b c d
1470 @end smallexample
1472 @noindent
1473 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1474 characters (using uppercase letters) of the wide character code. For
1475 example, ESC A345 is used to represent the wide character with code
1476 @code{16#A345#}.
1477 This scheme is compatible with use of the full Wide_Character set.
1479 @item Upper-Half Coding
1480 @cindex Upper-Half Coding
1481 The wide character with encoding @code{16#abcd#} where the upper bit is on
1482 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1483 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1484 character, but is not required to be in the upper half. This method can
1485 be also used for shift-JIS or EUC, where the internal coding matches the
1486 external coding.
1488 @item Shift JIS Coding
1489 @cindex Shift JIS Coding
1490 A wide character is represented by a two-character sequence,
1491 @code{16#ab#} and
1492 @code{16#cd#}, with the restrictions described for upper-half encoding as
1493 described above. The internal character code is the corresponding JIS
1494 character according to the standard algorithm for Shift-JIS
1495 conversion. Only characters defined in the JIS code set table can be
1496 used with this encoding method.
1498 @item EUC Coding
1499 @cindex EUC Coding
1500 A wide character is represented by a two-character sequence
1501 @code{16#ab#} and
1502 @code{16#cd#}, with both characters being in the upper half. The internal
1503 character code is the corresponding JIS character according to the EUC
1504 encoding algorithm. Only characters defined in the JIS code set table
1505 can be used with this encoding method.
1507 @item UTF-8 Coding
1508 A wide character is represented using
1509 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1510 10646-1/Am.2. Depending on the character value, the representation
1511 is a one, two, or three byte sequence:
1512 @smallexample
1513 @iftex
1514 @leftskip=.7cm
1515 @end iftex
1516 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1517 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1518 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1520 @end smallexample
1522 @noindent
1523 where the @var{xxx} bits correspond to the left-padded bits of the
1524 16-bit character value. Note that all lower half ASCII characters
1525 are represented as ASCII bytes and all upper half characters and
1526 other wide characters are represented as sequences of upper-half
1527 (The full UTF-8 scheme allows for encoding 31-bit characters as
1528 6-byte sequences, but in this implementation, all UTF-8 sequences
1529 of four or more bytes length will be treated as illegal).
1530 @item Brackets Coding
1531 In this encoding, a wide character is represented by the following eight
1532 character sequence:
1534 @smallexample
1535 [ " a b c d " ]
1536 @end smallexample
1538 @noindent
1539 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1540 characters (using uppercase letters) of the wide character code. For
1541 example, [``A345''] is used to represent the wide character with code
1542 @code{16#A345#}. It is also possible (though not required) to use the
1543 Brackets coding for upper half characters. For example, the code
1544 @code{16#A3#} can be represented as @code{[``A3'']}.
1546 This scheme is compatible with use of the full Wide_Character set,
1547 and is also the method used for wide character encoding in the standard
1548 ACVC (Ada Compiler Validation Capability) test suite distributions.
1550 @end table
1552 @noindent
1553 Note: Some of these coding schemes do not permit the full use of the
1554 Ada character set. For example, neither Shift JIS, nor EUC allow the
1555 use of the upper half of the Latin-1 set.
1557 @node File Naming Rules
1558 @section File Naming Rules
1560 @noindent
1561 The default file name is determined by the name of the unit that the
1562 file contains. The name is formed by taking the full expanded name of
1563 the unit and replacing the separating dots with hyphens and using
1564 ^lowercase^uppercase^ for all letters.
1566 An exception arises if the file name generated by the above rules starts
1567 with one of the characters
1568 @ifset vms
1569 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1570 @end ifset
1571 @ifclear vms
1572 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1573 @end ifclear
1574 and the second character is a
1575 minus. In this case, the character ^tilde^dollar sign^ is used in place
1576 of the minus. The reason for this special rule is to avoid clashes with
1577 the standard names for child units of the packages System, Ada,
1578 Interfaces, and GNAT, which use the prefixes
1579 @ifset vms
1580 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1581 @end ifset
1582 @ifclear vms
1583 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1584 @end ifclear
1585 respectively.
1587 The file extension is @file{.ads} for a spec and
1588 @file{.adb} for a body. The following list shows some
1589 examples of these rules.
1591 @table @file
1592 @item main.ads
1593 Main (spec)
1594 @item main.adb
1595 Main (body)
1596 @item arith_functions.ads
1597 Arith_Functions (package spec)
1598 @item arith_functions.adb
1599 Arith_Functions (package body)
1600 @item func-spec.ads
1601 Func.Spec (child package spec)
1602 @item func-spec.adb
1603 Func.Spec (child package body)
1604 @item main-sub.adb
1605 Sub (subunit of Main)
1606 @item ^a~bad.adb^A$BAD.ADB^
1607 A.Bad (child package body)
1608 @end table
1610 @noindent
1611 Following these rules can result in excessively long
1612 file names if corresponding
1613 unit names are long (for example, if child units or subunits are
1614 heavily nested). An option is available to shorten such long file names
1615 (called file name ``krunching''). This may be particularly useful when
1616 programs being developed with GNAT are to be used on operating systems
1617 with limited file name lengths. @xref{Using gnatkr}.
1619 Of course, no file shortening algorithm can guarantee uniqueness over
1620 all possible unit names; if file name krunching is used, it is your
1621 responsibility to ensure no name clashes occur. Alternatively you
1622 can specify the exact file names that you want used, as described
1623 in the next section. Finally, if your Ada programs are migrating from a
1624 compiler with a different naming convention, you can use the gnatchop
1625 utility to produce source files that follow the GNAT naming conventions.
1626 (For details @pxref{Renaming Files with gnatchop}.)
1628 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1629 systems, case is not significant. So for example on @code{Windows XP}
1630 if the canonical name is @code{main-sub.adb}, you can use the file name
1631 @code{Main-Sub.adb} instead. However, case is significant for other
1632 operating systems, so for example, if you want to use other than
1633 canonically cased file names on a Unix system, you need to follow
1634 the procedures described in the next section.
1636 @node Using Other File Names
1637 @section Using Other File Names
1638 @cindex File names
1640 @noindent
1641 In the previous section, we have described the default rules used by
1642 GNAT to determine the file name in which a given unit resides. It is
1643 often convenient to follow these default rules, and if you follow them,
1644 the compiler knows without being explicitly told where to find all
1645 the files it needs.
1647 However, in some cases, particularly when a program is imported from
1648 another Ada compiler environment, it may be more convenient for the
1649 programmer to specify which file names contain which units. GNAT allows
1650 arbitrary file names to be used by means of the Source_File_Name pragma.
1651 The form of this pragma is as shown in the following examples:
1652 @cindex Source_File_Name pragma
1654 @smallexample @c ada
1655 @cartouche
1656 pragma Source_File_Name (My_Utilities.Stacks,
1657   Spec_File_Name => "myutilst_a.ada");
1658 pragma Source_File_name (My_Utilities.Stacks,
1659   Body_File_Name => "myutilst.ada");
1660 @end cartouche
1661 @end smallexample
1663 @noindent
1664 As shown in this example, the first argument for the pragma is the unit
1665 name (in this example a child unit). The second argument has the form
1666 of a named association. The identifier
1667 indicates whether the file name is for a spec or a body;
1668 the file name itself is given by a string literal.
1670 The source file name pragma is a configuration pragma, which means that
1671 normally it will be placed in the @file{gnat.adc}
1672 file used to hold configuration
1673 pragmas that apply to a complete compilation environment.
1674 For more details on how the @file{gnat.adc} file is created and used
1675 see @ref{Handling of Configuration Pragmas}.
1676 @cindex @file{gnat.adc}
1678 @ifclear vms
1679 GNAT allows completely arbitrary file names to be specified using the
1680 source file name pragma. However, if the file name specified has an
1681 extension other than @file{.ads} or @file{.adb} it is necessary to use
1682 a special syntax when compiling the file. The name in this case must be
1683 preceded by the special sequence @option{-x} followed by a space and the name
1684 of the language, here @code{ada}, as in:
1686 @smallexample
1687 $ gcc -c -x ada peculiar_file_name.sim
1688 @end smallexample
1689 @end ifclear
1691 @noindent
1692 @command{gnatmake} handles non-standard file names in the usual manner (the
1693 non-standard file name for the main program is simply used as the
1694 argument to gnatmake). Note that if the extension is also non-standard,
1695 then it must be included in the @command{gnatmake} command, it may not
1696 be omitted.
1698 @node Alternative File Naming Schemes
1699 @section Alternative File Naming Schemes
1700 @cindex File naming schemes, alternative
1701 @cindex File names
1703 In the previous section, we described the use of the @code{Source_File_Name}
1704 pragma to allow arbitrary names to be assigned to individual source files.
1705 However, this approach requires one pragma for each file, and especially in
1706 large systems can result in very long @file{gnat.adc} files, and also create
1707 a maintenance problem.
1709 GNAT also provides a facility for specifying systematic file naming schemes
1710 other than the standard default naming scheme previously described. An
1711 alternative scheme for naming is specified by the use of
1712 @code{Source_File_Name} pragmas having the following format:
1713 @cindex Source_File_Name pragma
1715 @smallexample @c ada
1716 pragma Source_File_Name (
1717    Spec_File_Name  => FILE_NAME_PATTERN
1718  @r{[},Casing          => CASING_SPEC@r{]}
1719  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1721 pragma Source_File_Name (
1722    Body_File_Name  => FILE_NAME_PATTERN
1723  @r{[},Casing          => CASING_SPEC@r{]}
1724  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1726 pragma Source_File_Name (
1727    Subunit_File_Name  => FILE_NAME_PATTERN
1728  @r{[},Casing             => CASING_SPEC@r{]}
1729  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
1731 FILE_NAME_PATTERN ::= STRING_LITERAL
1732 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1733 @end smallexample
1735 @noindent
1736 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1737 It contains a single asterisk character, and the unit name is substituted
1738 systematically for this asterisk. The optional parameter
1739 @code{Casing} indicates
1740 whether the unit name is to be all upper-case letters, all lower-case letters,
1741 or mixed-case. If no
1742 @code{Casing} parameter is used, then the default is all
1743 ^lower-case^upper-case^.
1745 The optional @code{Dot_Replacement} string is used to replace any periods
1746 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1747 argument is used then separating dots appear unchanged in the resulting
1748 file name.
1749 Although the above syntax indicates that the
1750 @code{Casing} argument must appear
1751 before the @code{Dot_Replacement} argument, but it
1752 is also permissible to write these arguments in the opposite order.
1754 As indicated, it is possible to specify different naming schemes for
1755 bodies, specs, and subunits. Quite often the rule for subunits is the
1756 same as the rule for bodies, in which case, there is no need to give
1757 a separate @code{Subunit_File_Name} rule, and in this case the
1758 @code{Body_File_name} rule is used for subunits as well.
1760 The separate rule for subunits can also be used to implement the rather
1761 unusual case of a compilation environment (e.g.@: a single directory) which
1762 contains a subunit and a child unit with the same unit name. Although
1763 both units cannot appear in the same partition, the Ada Reference Manual
1764 allows (but does not require) the possibility of the two units coexisting
1765 in the same environment.
1767 The file name translation works in the following steps:
1769 @itemize @bullet
1771 @item
1772 If there is a specific @code{Source_File_Name} pragma for the given unit,
1773 then this is always used, and any general pattern rules are ignored.
1775 @item
1776 If there is a pattern type @code{Source_File_Name} pragma that applies to
1777 the unit, then the resulting file name will be used if the file exists. If
1778 more than one pattern matches, the latest one will be tried first, and the
1779 first attempt resulting in a reference to a file that exists will be used.
1781 @item
1782 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1783 for which the corresponding file exists, then the standard GNAT default
1784 naming rules are used.
1786 @end itemize
1788 @noindent
1789 As an example of the use of this mechanism, consider a commonly used scheme
1790 in which file names are all lower case, with separating periods copied
1791 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1792 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1793 two pragmas appear:
1795 @smallexample @c ada
1796 pragma Source_File_Name
1797   (Spec_File_Name => "*.1.ada");
1798 pragma Source_File_Name
1799   (Body_File_Name => "*.2.ada");
1800 @end smallexample
1802 @noindent
1803 The default GNAT scheme is actually implemented by providing the following
1804 default pragmas internally:
1806 @smallexample @c ada
1807 pragma Source_File_Name
1808   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1809 pragma Source_File_Name
1810   (Body_File_Name => "*.adb", Dot_Replacement => "-");
1811 @end smallexample
1813 @noindent
1814 Our final example implements a scheme typically used with one of the
1815 Ada 83 compilers, where the separator character for subunits was ``__''
1816 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1817 by adding @file{.ADA}, and subunits by
1818 adding @file{.SEP}. All file names were
1819 upper case. Child units were not present of course since this was an
1820 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1821 the same double underscore separator for child units.
1823 @smallexample @c ada
1824 pragma Source_File_Name
1825   (Spec_File_Name => "*_.ADA",
1826    Dot_Replacement => "__",
1827    Casing = Uppercase);
1828 pragma Source_File_Name
1829   (Body_File_Name => "*.ADA",
1830    Dot_Replacement => "__",
1831    Casing = Uppercase);
1832 pragma Source_File_Name
1833   (Subunit_File_Name => "*.SEP",
1834    Dot_Replacement => "__",
1835    Casing = Uppercase);
1836 @end smallexample
1838 @node Generating Object Files
1839 @section Generating Object Files
1841 @noindent
1842 An Ada program consists of a set of source files, and the first step in
1843 compiling the program is to generate the corresponding object files.
1844 These are generated by compiling a subset of these source files.
1845 The files you need to compile are the following:
1847 @itemize @bullet
1848 @item
1849 If a package spec has no body, compile the package spec to produce the
1850 object file for the package.
1852 @item
1853 If a package has both a spec and a body, compile the body to produce the
1854 object file for the package. The source file for the package spec need
1855 not be compiled in this case because there is only one object file, which
1856 contains the code for both the spec and body of the package.
1858 @item
1859 For a subprogram, compile the subprogram body to produce the object file
1860 for the subprogram. The spec, if one is present, is as usual in a
1861 separate file, and need not be compiled.
1863 @item
1864 @cindex Subunits
1865 In the case of subunits, only compile the parent unit. A single object
1866 file is generated for the entire subunit tree, which includes all the
1867 subunits.
1869 @item
1870 Compile child units independently of their parent units
1871 (though, of course, the spec of all the ancestor unit must be present in order
1872 to compile a child unit).
1874 @item
1875 @cindex Generics
1876 Compile generic units in the same manner as any other units. The object
1877 files in this case are small dummy files that contain at most the
1878 flag used for elaboration checking. This is because GNAT always handles generic
1879 instantiation by means of macro expansion. However, it is still necessary to
1880 compile generic units, for dependency checking and elaboration purposes.
1881 @end itemize
1883 @noindent
1884 The preceding rules describe the set of files that must be compiled to
1885 generate the object files for a program. Each object file has the same
1886 name as the corresponding source file, except that the extension is
1887 @file{.o} as usual.
1889 You may wish to compile other files for the purpose of checking their
1890 syntactic and semantic correctness. For example, in the case where a
1891 package has a separate spec and body, you would not normally compile the
1892 spec. However, it is convenient in practice to compile the spec to make
1893 sure it is error-free before compiling clients of this spec, because such
1894 compilations will fail if there is an error in the spec.
1896 GNAT provides an option for compiling such files purely for the
1897 purposes of checking correctness; such compilations are not required as
1898 part of the process of building a program. To compile a file in this
1899 checking mode, use the @option{-gnatc} switch.
1901 @node Source Dependencies
1902 @section Source Dependencies
1904 @noindent
1905 A given object file clearly depends on the source file which is compiled
1906 to produce it. Here we are using @dfn{depends} in the sense of a typical
1907 @code{make} utility; in other words, an object file depends on a source
1908 file if changes to the source file require the object file to be
1909 recompiled.
1910 In addition to this basic dependency, a given object may depend on
1911 additional source files as follows:
1913 @itemize @bullet
1914 @item
1915 If a file being compiled @code{with}'s a unit @var{X}, the object file
1916 depends on the file containing the spec of unit @var{X}. This includes
1917 files that are @code{with}'ed implicitly either because they are parents
1918 of @code{with}'ed child units or they are run-time units required by the
1919 language constructs used in a particular unit.
1921 @item
1922 If a file being compiled instantiates a library level generic unit, the
1923 object file depends on both the spec and body files for this generic
1924 unit.
1926 @item
1927 If a file being compiled instantiates a generic unit defined within a
1928 package, the object file depends on the body file for the package as
1929 well as the spec file.
1931 @item
1932 @findex Inline
1933 @cindex @option{-gnatn} switch
1934 If a file being compiled contains a call to a subprogram for which
1935 pragma @code{Inline} applies and inlining is activated with the
1936 @option{-gnatn} switch, the object file depends on the file containing the
1937 body of this subprogram as well as on the file containing the spec. Note
1938 that for inlining to actually occur as a result of the use of this switch,
1939 it is necessary to compile in optimizing mode.
1941 @cindex @option{-gnatN} switch
1942 The use of @option{-gnatN} activates  inlining optimization
1943 that is performed by the front end of the compiler. This inlining does
1944 not require that the code generation be optimized. Like @option{-gnatn},
1945 the use of this switch generates additional dependencies.
1947 When using a gcc-based back end (in practice this means using any version
1948 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1949 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1950 Historically front end inlining was more extensive than the gcc back end
1951 inlining, but that is no longer the case.
1953 @item
1954 If an object file @file{O} depends on the proper body of a subunit through
1955 inlining or instantiation, it depends on the parent unit of the subunit.
1956 This means that any modification of the parent unit or one of its subunits
1957 affects the compilation of @file{O}.
1959 @item
1960 The object file for a parent unit depends on all its subunit body files.
1962 @item
1963 The previous two rules meant that for purposes of computing dependencies and
1964 recompilation, a body and all its subunits are treated as an indivisible whole.
1966 @noindent
1967 These rules are applied transitively: if unit @code{A} @code{with}'s
1968 unit @code{B}, whose elaboration calls an inlined procedure in package
1969 @code{C}, the object file for unit @code{A} will depend on the body of
1970 @code{C}, in file @file{c.adb}.
1972 The set of dependent files described by these rules includes all the
1973 files on which the unit is semantically dependent, as dictated by the
1974 Ada language standard. However, it is a superset of what the
1975 standard describes, because it includes generic, inline, and subunit
1976 dependencies.
1978 An object file must be recreated by recompiling the corresponding source
1979 file if any of the source files on which it depends are modified. For
1980 example, if the @code{make} utility is used to control compilation,
1981 the rule for an Ada object file must mention all the source files on
1982 which the object file depends, according to the above definition.
1983 The determination of the necessary
1984 recompilations is done automatically when one uses @command{gnatmake}.
1985 @end itemize
1987 @node The Ada Library Information Files
1988 @section The Ada Library Information Files
1989 @cindex Ada Library Information files
1990 @cindex @file{ALI} files
1992 @noindent
1993 Each compilation actually generates two output files. The first of these
1994 is the normal object file that has a @file{.o} extension. The second is a
1995 text file containing full dependency information. It has the same
1996 name as the source file, but an @file{.ali} extension.
1997 This file is known as the Ada Library Information (@file{ALI}) file.
1998 The following information is contained in the @file{ALI} file.
2000 @itemize @bullet
2001 @item
2002 Version information (indicates which version of GNAT was used to compile
2003 the unit(s) in question)
2005 @item
2006 Main program information (including priority and time slice settings,
2007 as well as the wide character encoding used during compilation).
2009 @item
2010 List of arguments used in the @command{gcc} command for the compilation
2012 @item
2013 Attributes of the unit, including configuration pragmas used, an indication
2014 of whether the compilation was successful, exception model used etc.
2016 @item
2017 A list of relevant restrictions applying to the unit (used for consistency)
2018 checking.
2020 @item
2021 Categorization information (e.g.@: use of pragma @code{Pure}).
2023 @item
2024 Information on all @code{with}'ed units, including presence of
2025 @code{Elaborate} or @code{Elaborate_All} pragmas.
2027 @item
2028 Information from any @code{Linker_Options} pragmas used in the unit
2030 @item
2031 Information on the use of @code{Body_Version} or @code{Version}
2032 attributes in the unit.
2034 @item
2035 Dependency information. This is a list of files, together with
2036 time stamp and checksum information. These are files on which
2037 the unit depends in the sense that recompilation is required
2038 if any of these units are modified.
2040 @item
2041 Cross-reference data. Contains information on all entities referenced
2042 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2043 provide cross-reference information.
2045 @end itemize
2047 @noindent
2048 For a full detailed description of the format of the @file{ALI} file,
2049 see the source of the body of unit @code{Lib.Writ}, contained in file
2050 @file{lib-writ.adb} in the GNAT compiler sources.
2052 @node Binding an Ada Program
2053 @section Binding an Ada Program
2055 @noindent
2056 When using languages such as C and C++, once the source files have been
2057 compiled the only remaining step in building an executable program
2058 is linking the object modules together. This means that it is possible to
2059 link an inconsistent version of a program, in which two units have
2060 included different versions of the same header.
2062 The rules of Ada do not permit such an inconsistent program to be built.
2063 For example, if two clients have different versions of the same package,
2064 it is illegal to build a program containing these two clients.
2065 These rules are enforced by the GNAT binder, which also determines an
2066 elaboration order consistent with the Ada rules.
2068 The GNAT binder is run after all the object files for a program have
2069 been created. It is given the name of the main program unit, and from
2070 this it determines the set of units required by the program, by reading the
2071 corresponding ALI files. It generates error messages if the program is
2072 inconsistent or if no valid order of elaboration exists.
2074 If no errors are detected, the binder produces a main program, in Ada by
2075 default, that contains calls to the elaboration procedures of those
2076 compilation unit that require them, followed by
2077 a call to the main program. This Ada program is compiled to generate the
2078 object file for the main program. The name of
2079 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2080 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2081 main program unit.
2083 Finally, the linker is used to build the resulting executable program,
2084 using the object from the main program from the bind step as well as the
2085 object files for the Ada units of the program.
2087 @node Mixed Language Programming
2088 @section Mixed Language Programming
2089 @cindex Mixed Language Programming
2091 @noindent
2092 This section describes how to develop a mixed-language program,
2093 specifically one that comprises units in both Ada and C.
2095 @menu
2096 * Interfacing to C::
2097 * Calling Conventions::
2098 @end menu
2100 @node Interfacing to C
2101 @subsection Interfacing to C
2102 @noindent
2103 Interfacing Ada with a foreign language such as C involves using
2104 compiler directives to import and/or export entity definitions in each
2105 language---using @code{extern} statements in C, for instance, and the
2106 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2107 A full treatment of these topics is provided in Appendix B, section 1
2108 of the Ada Reference Manual.
2110 There are two ways to build a program using GNAT that contains some Ada
2111 sources and some foreign language sources, depending on whether or not
2112 the main subprogram is written in Ada.  Here is a source example with
2113 the main subprogram in Ada:
2115 @smallexample
2116 /* file1.c */
2117 #include <stdio.h>
2119 void print_num (int num)
2121   printf ("num is %d.\n", num);
2122   return;
2125 /* file2.c */
2127 /* num_from_Ada is declared in my_main.adb */
2128 extern int num_from_Ada;
2130 int get_num (void)
2132   return num_from_Ada;
2134 @end smallexample
2136 @smallexample @c ada
2137 --  my_main.adb
2138 procedure My_Main is
2140    --  Declare then export an Integer entity called num_from_Ada
2141    My_Num : Integer := 10;
2142    pragma Export (C, My_Num, "num_from_Ada");
2144    --  Declare an Ada function spec for Get_Num, then use
2145    --  C function get_num for the implementation.
2146    function Get_Num return Integer;
2147    pragma Import (C, Get_Num, "get_num");
2149    --  Declare an Ada procedure spec for Print_Num, then use
2150    --  C function print_num for the implementation.
2151    procedure Print_Num (Num : Integer);
2152    pragma Import (C, Print_Num, "print_num");
2154 begin
2155    Print_Num (Get_Num);
2156 end My_Main;
2157 @end smallexample
2159 @enumerate
2160 @item
2161 To build this example, first compile the foreign language files to
2162 generate object files:
2163 @smallexample
2164 ^gcc -c file1.c^gcc -c FILE1.C^
2165 ^gcc -c file2.c^gcc -c FILE2.C^
2166 @end smallexample
2168 @item
2169 Then, compile the Ada units to produce a set of object files and ALI
2170 files:
2171 @smallexample
2172 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2173 @end smallexample
2175 @item
2176 Run the Ada binder on the Ada main program:
2177 @smallexample
2178 gnatbind my_main.ali
2179 @end smallexample
2181 @item
2182 Link the Ada main program, the Ada objects and the other language
2183 objects:
2184 @smallexample
2185 gnatlink my_main.ali file1.o file2.o
2186 @end smallexample
2187 @end enumerate
2189 The last three steps can be grouped in a single command:
2190 @smallexample
2191 gnatmake my_main.adb -largs file1.o file2.o
2192 @end smallexample
2194 @cindex Binder output file
2195 @noindent
2196 If the main program is in a language other than Ada, then you may have
2197 more than one entry point into the Ada subsystem. You must use a special
2198 binder option to generate callable routines that initialize and
2199 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2200 Calls to the initialization and finalization routines must be inserted
2201 in the main program, or some other appropriate point in the code. The
2202 call to initialize the Ada units must occur before the first Ada
2203 subprogram is called, and the call to finalize the Ada units must occur
2204 after the last Ada subprogram returns. The binder will place the
2205 initialization and finalization subprograms into the
2206 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2207 sources.  To illustrate, we have the following example:
2209 @smallexample
2210 /* main.c */
2211 extern void adainit (void);
2212 extern void adafinal (void);
2213 extern int add (int, int);
2214 extern int sub (int, int);
2216 int main (int argc, char *argv[])
2218   int a = 21, b = 7;
2220   adainit();
2222   /* Should print "21 + 7 = 28" */
2223   printf ("%d + %d = %d\n", a, b, add (a, b));
2224   /* Should print "21 - 7 = 14" */
2225   printf ("%d - %d = %d\n", a, b, sub (a, b));
2227   adafinal();
2229 @end smallexample
2231 @smallexample @c ada
2232 --  unit1.ads
2233 package Unit1 is
2234    function Add (A, B : Integer) return Integer;
2235    pragma Export (C, Add, "add");
2236 end Unit1;
2238 --  unit1.adb
2239 package body Unit1 is
2240    function Add (A, B : Integer) return Integer is
2241    begin
2242       return A + B;
2243    end Add;
2244 end Unit1;
2246 --  unit2.ads
2247 package Unit2 is
2248    function Sub (A, B : Integer) return Integer;
2249    pragma Export (C, Sub, "sub");
2250 end Unit2;
2252 --  unit2.adb
2253 package body Unit2 is
2254    function Sub (A, B : Integer) return Integer is
2255    begin
2256       return A - B;
2257    end Sub;
2258 end Unit2;
2259 @end smallexample
2261 @enumerate
2262 @item
2263 The build procedure for this application is similar to the last
2264 example's.  First, compile the foreign language files to generate object
2265 files:
2266 @smallexample
2267 ^gcc -c main.c^gcc -c main.c^
2268 @end smallexample
2270 @item
2271 Next, compile the Ada units to produce a set of object files and ALI
2272 files:
2273 @smallexample
2274 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2275 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2276 @end smallexample
2278 @item
2279 Run the Ada binder on every generated ALI file.  Make sure to use the
2280 @option{-n} option to specify a foreign main program:
2281 @smallexample
2282 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2283 @end smallexample
2285 @item
2286 Link the Ada main program, the Ada objects and the foreign language
2287 objects. You need only list the last ALI file here:
2288 @smallexample
2289 gnatlink unit2.ali main.o -o exec_file
2290 @end smallexample
2292 This procedure yields a binary executable called @file{exec_file}.
2293 @end enumerate
2295 @noindent
2296 Depending on the circumstances (for example when your non-Ada main object
2297 does not provide symbol @code{main}), you may also need to instruct the
2298 GNAT linker not to include the standard startup objects by passing the
2299 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2301 @node Calling Conventions
2302 @subsection Calling Conventions
2303 @cindex Foreign Languages
2304 @cindex Calling Conventions
2305 GNAT follows standard calling sequence conventions and will thus interface
2306 to any other language that also follows these conventions. The following
2307 Convention identifiers are recognized by GNAT:
2309 @table @code
2310 @cindex Interfacing to Ada
2311 @cindex Other Ada compilers
2312 @cindex Convention Ada
2313 @item Ada
2314 This indicates that the standard Ada calling sequence will be
2315 used and all Ada data items may be passed without any limitations in the
2316 case where GNAT is used to generate both the caller and callee. It is also
2317 possible to mix GNAT generated code and code generated by another Ada
2318 compiler. In this case, the data types should be restricted to simple
2319 cases, including primitive types. Whether complex data types can be passed
2320 depends on the situation. Probably it is safe to pass simple arrays, such
2321 as arrays of integers or floats. Records may or may not work, depending
2322 on whether both compilers lay them out identically. Complex structures
2323 involving variant records, access parameters, tasks, or protected types,
2324 are unlikely to be able to be passed.
2326 Note that in the case of GNAT running
2327 on a platform that supports HP Ada 83, a higher degree of compatibility
2328 can be guaranteed, and in particular records are laid out in an identical
2329 manner in the two compilers. Note also that if output from two different
2330 compilers is mixed, the program is responsible for dealing with elaboration
2331 issues. Probably the safest approach is to write the main program in the
2332 version of Ada other than GNAT, so that it takes care of its own elaboration
2333 requirements, and then call the GNAT-generated adainit procedure to ensure
2334 elaboration of the GNAT components. Consult the documentation of the other
2335 Ada compiler for further details on elaboration.
2337 However, it is not possible to mix the tasking run time of GNAT and
2338 HP Ada 83, All the tasking operations must either be entirely within
2339 GNAT compiled sections of the program, or entirely within HP Ada 83
2340 compiled sections of the program.
2342 @cindex Interfacing to Assembly
2343 @cindex Convention Assembler
2344 @item Assembler
2345 Specifies assembler as the convention. In practice this has the
2346 same effect as convention Ada (but is not equivalent in the sense of being
2347 considered the same convention).
2349 @cindex Convention Asm
2350 @findex Asm
2351 @item Asm
2352 Equivalent to Assembler.
2354 @cindex Interfacing to COBOL
2355 @cindex Convention COBOL
2356 @findex COBOL
2357 @item COBOL
2358 Data will be passed according to the conventions described
2359 in section B.4 of the Ada Reference Manual.
2361 @findex C
2362 @cindex Interfacing to C
2363 @cindex Convention C
2364 @item C
2365 Data will be passed according to the conventions described
2366 in section B.3 of the Ada Reference Manual.
2368 A note on interfacing to a C ``varargs'' function:
2369 @findex C varargs function
2370 @cindex Interfacing to C varargs function
2371 @cindex varargs function interfaces
2373 @itemize @bullet
2374 @item
2375 In C, @code{varargs} allows a function to take a variable number of
2376 arguments. There is no direct equivalent in this to Ada. One
2377 approach that can be used is to create a C wrapper for each
2378 different profile and then interface to this C wrapper. For
2379 example, to print an @code{int} value using @code{printf},
2380 create a C function @code{printfi} that takes two arguments, a
2381 pointer to a string and an int, and calls @code{printf}.
2382 Then in the Ada program, use pragma @code{Import} to
2383 interface to @code{printfi}.
2385 @item
2386 It may work on some platforms to directly interface to
2387 a @code{varargs} function by providing a specific Ada profile
2388 for a particular call. However, this does not work on
2389 all platforms, since there is no guarantee that the
2390 calling sequence for a two argument normal C function
2391 is the same as for calling a @code{varargs} C function with
2392 the same two arguments.
2393 @end itemize
2395 @cindex Convention Default
2396 @findex Default
2397 @item Default
2398 Equivalent to C.
2400 @cindex Convention External
2401 @findex External
2402 @item External
2403 Equivalent to C.
2405 @ifclear vms
2406 @findex C++
2407 @cindex Interfacing to C++
2408 @cindex Convention C++
2409 @item C_Plus_Plus (or CPP)
2410 This stands for C++. For most purposes this is identical to C.
2411 See the separate description of the specialized GNAT pragmas relating to
2412 C++ interfacing for further details.
2413 @end ifclear
2415 @findex Fortran
2416 @cindex Interfacing to Fortran
2417 @cindex Convention Fortran
2418 @item Fortran
2419 Data will be passed according to the conventions described
2420 in section B.5 of the Ada Reference Manual.
2422 @item Intrinsic
2423 This applies to an intrinsic operation, as defined in the Ada
2424 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2425 this means that the body of the subprogram is provided by the compiler itself,
2426 usually by means of an efficient code sequence, and that the user does not
2427 supply an explicit body for it. In an application program, the pragma may
2428 be applied to the following sets of names:
2430 @itemize @bullet
2431 @item
2432 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2433 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2434 two formal parameters. The
2435 first one must be a signed integer type or a modular type with a binary
2436 modulus, and the second parameter must be of type Natural.
2437 The return type must be the same as the type of the first argument. The size
2438 of this type can only be 8, 16, 32, or 64.
2440 @item
2441 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2442 The corresponding operator declaration must have parameters and result type
2443 that have the same root numeric type (for example, all three are long_float
2444 types). This simplifies the definition of operations that use type checking
2445 to perform dimensional checks:
2447 @smallexample @c ada
2448 type Distance is new Long_Float;
2449 type Time     is new Long_Float;
2450 type Velocity is new Long_Float;
2451 function "/" (D : Distance; T : Time)
2452   return Velocity;
2453 pragma Import (Intrinsic, "/");
2454 @end smallexample
2456 @noindent
2457 This common idiom is often programmed with a generic definition and an
2458 explicit body. The pragma makes it simpler to introduce such declarations.
2459 It incurs no overhead in compilation time or code size, because it is
2460 implemented as a single machine instruction.
2462 @item
2463 General subprogram entities, to bind an Ada subprogram declaration to
2464 a compiler builtin by name with back-ends where such interfaces are
2465 available. A typical example is the set of ``__builtin'' functions
2466 exposed by the GCC back-end, as in the following example:
2468 @smallexample @c ada
2469    function builtin_sqrt (F : Float) return Float;
2470    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2471 @end smallexample
2473 Most of the GCC builtins are accessible this way, and as for other
2474 import conventions (e.g. C), it is the user's responsibility to ensure
2475 that the Ada subprogram profile matches the underlying builtin
2476 expectations.
2477 @end itemize
2479 @noindent
2481 @ifset unw
2482 @findex Stdcall
2483 @cindex Convention Stdcall
2484 @item Stdcall
2485 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2486 and specifies that the @code{Stdcall} calling sequence will be used,
2487 as defined by the NT API. Nevertheless, to ease building
2488 cross-platform bindings this convention will be handled as a @code{C} calling
2489 convention on non-Windows platforms.
2491 @findex DLL
2492 @cindex Convention DLL
2493 @item DLL
2494 This is equivalent to @code{Stdcall}.
2496 @findex Win32
2497 @cindex Convention Win32
2498 @item Win32
2499 This is equivalent to @code{Stdcall}.
2500 @end ifset
2502 @findex Stubbed
2503 @cindex Convention Stubbed
2504 @item Stubbed
2505 This is a special convention that indicates that the compiler
2506 should provide a stub body that raises @code{Program_Error}.
2507 @end table
2509 @noindent
2510 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2511 that can be used to parameterize conventions and allow additional synonyms
2512 to be specified. For example if you have legacy code in which the convention
2513 identifier Fortran77 was used for Fortran, you can use the configuration
2514 pragma:
2516 @smallexample @c ada
2517 pragma Convention_Identifier (Fortran77, Fortran);
2518 @end smallexample
2520 @noindent
2521 And from now on the identifier Fortran77 may be used as a convention
2522 identifier (for example in an @code{Import} pragma) with the same
2523 meaning as Fortran.
2525 @ifclear vms
2526 @node Building Mixed Ada & C++ Programs
2527 @section Building Mixed Ada and C++ Programs
2529 @noindent
2530 A programmer inexperienced with mixed-language development may find that
2531 building an application containing both Ada and C++ code can be a
2532 challenge.  This section gives a few
2533 hints that should make this task easier. The first section addresses
2534 the differences between interfacing with C and interfacing with C++.
2535 The second section
2536 looks into the delicate problem of linking the complete application from
2537 its Ada and C++ parts. The last section gives some hints on how the GNAT
2538 run-time library can be adapted in order to allow inter-language dispatching
2539 with a new C++ compiler.
2541 @menu
2542 * Interfacing to C++::
2543 * Linking a Mixed C++ & Ada Program::
2544 * A Simple Example::
2545 * Interfacing with C++ constructors::
2546 * Interfacing with C++ at the Class Level::
2547 @end menu
2549 @node Interfacing to C++
2550 @subsection Interfacing to C++
2552 @noindent
2553 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2554 generating code that is compatible with the G++ Application Binary
2555 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2557 @noindent
2558 Interfacing can be done at 3 levels: simple data, subprograms, and
2559 classes. In the first two cases, GNAT offers a specific @code{Convention
2560 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2561 Usually, C++ mangles the names of subprograms. To generate proper mangled
2562 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2563 This problem can also be addressed manually in two ways:
2565 @itemize @bullet
2566 @item
2567 by modifying the C++ code in order to force a C convention using
2568 the @code{extern "C"} syntax.
2570 @item
2571 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2572 Link_Name argument of the pragma import.
2573 @end itemize
2575 @noindent
2576 Interfacing at the class level can be achieved by using the GNAT specific
2577 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
2578 gnat_rm, GNAT Reference Manual}, for additional information.
2580 @node Linking a Mixed C++ & Ada Program
2581 @subsection Linking a Mixed C++ & Ada Program
2583 @noindent
2584 Usually the linker of the C++ development system must be used to link
2585 mixed applications because most C++ systems will resolve elaboration
2586 issues (such as calling constructors on global class instances)
2587 transparently during the link phase. GNAT has been adapted to ease the
2588 use of a foreign linker for the last phase. Three cases can be
2589 considered:
2590 @enumerate
2592 @item
2593 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2594 The C++ linker can simply be called by using the C++ specific driver
2595 called @code{g++}.
2597 Note that if the C++ code uses inline functions, you will need to
2598 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2599 order to provide an existing function implementation that the Ada code can
2600 link with.
2602 @smallexample
2603 $ g++ -c -fkeep-inline-functions file1.C
2604 $ g++ -c -fkeep-inline-functions file2.C
2605 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2606 @end smallexample
2608 @item
2609 Using GNAT and G++ from two different GCC installations: If both
2610 compilers are on the @env{PATH}, the previous method may be used. It is
2611 important to note that environment variables such as
2612 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2613 @env{GCC_ROOT} will affect both compilers
2614 at the same time and may make one of the two compilers operate
2615 improperly if set during invocation of the wrong compiler.  It is also
2616 very important that the linker uses the proper @file{libgcc.a} GCC
2617 library -- that is, the one from the C++ compiler installation. The
2618 implicit link command as suggested in the @command{gnatmake} command
2619 from the former example can be replaced by an explicit link command with
2620 the full-verbosity option in order to verify which library is used:
2621 @smallexample
2622 $ gnatbind ada_unit
2623 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2624 @end smallexample
2625 If there is a problem due to interfering environment variables, it can
2626 be worked around by using an intermediate script. The following example
2627 shows the proper script to use when GNAT has not been installed at its
2628 default location and g++ has been installed at its default location:
2630 @smallexample
2631 $ cat ./my_script
2632 #!/bin/sh
2633 unset BINUTILS_ROOT
2634 unset GCC_ROOT
2635 c++ $*
2636 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2637 @end smallexample
2639 @item
2640 Using a non-GNU C++ compiler: The commands previously described can be
2641 used to insure that the C++ linker is used. Nonetheless, you need to add
2642 a few more parameters to the link command line, depending on the exception
2643 mechanism used.
2645 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2646 to the libgcc libraries are required:
2648 @smallexample
2649 $ cat ./my_script
2650 #!/bin/sh
2651 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2652 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2653 @end smallexample
2655 Where CC is the name of the non-GNU C++ compiler.
2657 If the @code{zero cost} exception mechanism is used, and the platform
2658 supports automatic registration of exception tables (e.g.@: Solaris),
2659 paths to more objects are required:
2661 @smallexample
2662 $ cat ./my_script
2663 #!/bin/sh
2664 CC `gcc -print-file-name=crtbegin.o` $* \
2665 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2666 `gcc -print-file-name=crtend.o`
2667 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2668 @end smallexample
2670 If the @code{zero cost} exception mechanism is used, and the platform
2671 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2672 or AIX), the simple approach described above will not work and
2673 a pre-linking phase using GNAT will be necessary.
2675 @end enumerate
2677 Another alternative is to use the @command{gprbuild} multi-language builder
2678 which has a large knowledge base and knows how to link Ada and C++ code
2679 together automatically in most cases.
2681 @node A Simple Example
2682 @subsection  A Simple Example
2683 @noindent
2684 The following example, provided as part of the GNAT examples, shows how
2685 to achieve procedural interfacing between Ada and C++ in both
2686 directions. The C++ class A has two methods. The first method is exported
2687 to Ada by the means of an extern C wrapper function. The second method
2688 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2689 a limited record with a layout comparable to the C++ class. The Ada
2690 subprogram, in turn, calls the C++ method. So, starting from the C++
2691 main program, the process passes back and forth between the two
2692 languages.
2694 @noindent
2695 Here are the compilation commands:
2696 @smallexample
2697 $ gnatmake -c simple_cpp_interface
2698 $ g++ -c cpp_main.C
2699 $ g++ -c ex7.C
2700 $ gnatbind -n simple_cpp_interface
2701 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2702       -lstdc++ ex7.o cpp_main.o
2703 @end smallexample
2705 @noindent
2706 Here are the corresponding sources:
2707 @smallexample
2709 //cpp_main.C
2711 #include "ex7.h"
2713 extern "C" @{
2714   void adainit (void);
2715   void adafinal (void);
2716   void method1 (A *t);
2719 void method1 (A *t)
2721   t->method1 ();
2724 int main ()
2726   A obj;
2727   adainit ();
2728   obj.method2 (3030);
2729   adafinal ();
2732 //ex7.h
2734 class Origin @{
2735  public:
2736   int o_value;
2738 class A : public Origin @{
2739  public:
2740   void method1 (void);
2741   void method2 (int v);
2742   A();
2743   int   a_value;
2746 //ex7.C
2748 #include "ex7.h"
2749 #include <stdio.h>
2751 extern "C" @{ void ada_method2 (A *t, int v);@}
2753 void A::method1 (void)
2755   a_value = 2020;
2756   printf ("in A::method1, a_value = %d \n",a_value);
2760 void A::method2 (int v)
2762    ada_method2 (this, v);
2763    printf ("in A::method2, a_value = %d \n",a_value);
2767 A::A(void)
2769    a_value = 1010;
2770   printf ("in A::A, a_value = %d \n",a_value);
2772 @end smallexample
2774 @smallexample @c ada
2775 -- Ada sources
2776 package body Simple_Cpp_Interface is
2778    procedure Ada_Method2 (This : in out A; V : Integer) is
2779    begin
2780       Method1 (This);
2781       This.A_Value := V;
2782    end Ada_Method2;
2784 end Simple_Cpp_Interface;
2786 with System;
2787 package Simple_Cpp_Interface is
2788    type A is limited
2789       record
2790          Vptr    : System.Address;
2791          O_Value : Integer;
2792          A_Value : Integer;
2793       end record;
2794    pragma Convention (C, A);
2796    procedure Method1 (This : in out A);
2797    pragma Import (C, Method1);
2799    procedure Ada_Method2 (This : in out A; V : Integer);
2800    pragma Export (C, Ada_Method2);
2802 end Simple_Cpp_Interface;
2803 @end smallexample
2805 @node Interfacing with C++ constructors
2806 @subsection Interfacing with C++ constructors
2807 @noindent
2809 In order to interface with C++ constructors GNAT provides the
2810 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2811 gnat_rm, GNAT Reference Manual}, for additional information).
2812 In this section we present some common uses of C++ constructors
2813 in mixed-languages programs in GNAT.
2815 Let us assume that we need to interface with the following
2816 C++ class:
2818 @smallexample
2819 @b{class} Root @{
2820 @b{public}:
2821   int  a_value;
2822   int  b_value;
2823   @b{virtual} int Get_Value ();
2824   Root();              // Default constructor
2825   Root(int v);         // 1st non-default constructor
2826   Root(int v, int w);  // 2nd non-default constructor
2828 @end smallexample
2830 For this purpose we can write the following package spec (further
2831 information on how to build this spec is available in
2832 @ref{Interfacing with C++ at the Class Level} and
2833 @ref{Generating Ada Bindings for C and C++ headers}).
2835 @smallexample @c ada
2836 with Interfaces.C; use Interfaces.C;
2837 package Pkg_Root is
2838   type Root is tagged limited record
2839      A_Value : int;
2840      B_Value : int;
2841   end record;
2842   pragma Import (CPP, Root);
2844   function Get_Value (Obj : Root) return int;
2845   pragma Import (CPP, Get_Value);
2847   function Constructor return Root;
2848   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2850   function Constructor (v : Integer) return Root;
2851   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2853   function Constructor (v, w : Integer) return Root;
2854   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2855 end Pkg_Root;
2856 @end smallexample
2858 On the Ada side the constructor is represented by a function (whose
2859 name is arbitrary) that returns the classwide type corresponding to
2860 the imported C++ class. Although the constructor is described as a
2861 function, it is typically a procedure with an extra implicit argument
2862 (the object being initialized) at the implementation level. GNAT
2863 issues the appropriate call, whatever it is, to get the object
2864 properly initialized.
2866 Constructors can only appear in the following contexts:
2868 @itemize @bullet
2869 @item
2870 On the right side of an initialization of an object of type @var{T}.
2871 @item
2872 On the right side of an initialization of a record component of type @var{T}.
2873 @item
2874 In an Ada 2005 limited aggregate.
2875 @item
2876 In an Ada 2005 nested limited aggregate.
2877 @item
2878 In an Ada 2005 limited aggregate that initializes an object built in
2879 place by an extended return statement.
2880 @end itemize
2882 @noindent
2883 In a declaration of an object whose type is a class imported from C++,
2884 either the default C++ constructor is implicitly called by GNAT, or
2885 else the required C++ constructor must be explicitly called in the
2886 expression that initializes the object. For example:
2888 @smallexample @c ada
2889   Obj1 : Root;
2890   Obj2 : Root := Constructor;
2891   Obj3 : Root := Constructor (v => 10);
2892   Obj4 : Root := Constructor (30, 40);
2893 @end smallexample
2895 The first two declarations are equivalent: in both cases the default C++
2896 constructor is invoked (in the former case the call to the constructor is
2897 implicit, and in the latter case the call is explicit in the object
2898 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2899 that takes an integer argument, and @code{Obj4} is initialized by the
2900 non-default C++ constructor that takes two integers.
2902 Let us derive the imported C++ class in the Ada side. For example:
2904 @smallexample @c ada
2905   type DT is new Root with record
2906      C_Value : Natural := 2009;
2907   end record;
2908 @end smallexample
2910 In this case the components DT inherited from the C++ side must be
2911 initialized by a C++ constructor, and the additional Ada components
2912 of type DT are initialized by GNAT. The initialization of such an
2913 object is done either by default, or by means of a function returning
2914 an aggregate of type DT, or by means of an extension aggregate.
2916 @smallexample @c ada
2917   Obj5 : DT;
2918   Obj6 : DT := Function_Returning_DT (50);
2919   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
2920 @end smallexample
2922 The declaration of @code{Obj5} invokes the default constructors: the
2923 C++ default constructor of the parent type takes care of the initialization
2924 of the components inherited from Root, and GNAT takes care of the default
2925 initialization of the additional Ada components of type DT (that is,
2926 @code{C_Value} is initialized to value 2009). The order of invocation of
2927 the constructors is consistent with the order of elaboration required by
2928 Ada and C++. That is, the constructor of the parent type is always called
2929 before the constructor of the derived type.
2931 Let us now consider a record that has components whose type is imported
2932 from C++. For example:
2934 @smallexample @c ada
2935   type Rec1 is limited record
2936      Data1 : Root := Constructor (10);
2937      Value : Natural := 1000;
2938   end record;
2940   type Rec2 (D : Integer := 20) is limited record
2941      Rec   : Rec1;
2942      Data2 : Root := Constructor (D, 30);
2943   end record;
2944 @end smallexample
2946 The initialization of an object of type @code{Rec2} will call the
2947 non-default C++ constructors specified for the imported components.
2948 For example:
2950 @smallexample @c ada
2951   Obj8 : Rec2 (40);
2952 @end smallexample
2954 Using Ada 2005 we can use limited aggregates to initialize an object
2955 invoking C++ constructors that differ from those specified in the type
2956 declarations. For example:
2958 @smallexample @c ada
2959   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2960                           others => <>),
2961                   others => <>);
2962 @end smallexample
2964 The above declaration uses an Ada 2005 limited aggregate to
2965 initialize @code{Obj9}, and the C++ constructor that has two integer
2966 arguments is invoked to initialize the @code{Data1} component instead
2967 of the constructor specified in the declaration of type @code{Rec1}. In
2968 Ada 2005 the box in the aggregate indicates that unspecified components
2969 are initialized using the expression (if any) available in the component
2970 declaration. That is, in this case discriminant @code{D} is initialized
2971 to value @code{20}, @code{Value} is initialized to value 1000, and the
2972 non-default C++ constructor that handles two integers takes care of
2973 initializing component @code{Data2} with values @code{20,30}.
2975 In Ada 2005 we can use the extended return statement to build the Ada
2976 equivalent to C++ non-default constructors. For example:
2978 @smallexample @c ada
2979   function Constructor (V : Integer) return Rec2 is
2980   begin
2981      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
2982                                    others => <>),
2983                            others => <>) do
2984         --  Further actions required for construction of
2985         --  objects of type Rec2
2986         ...
2987      end record;
2988   end Constructor;
2989 @end smallexample
2991 In this example the extended return statement construct is used to
2992 build in place the returned object whose components are initialized
2993 by means of a limited aggregate. Any further action associated with
2994 the constructor can be placed inside the construct.
2996 @node Interfacing with C++ at the Class Level
2997 @subsection Interfacing with C++ at the Class Level
2998 @noindent
2999 In this section we demonstrate the GNAT features for interfacing with
3000 C++ by means of an example making use of Ada 2005 abstract interface
3001 types. This example consists of a classification of animals; classes
3002 have been used to model our main classification of animals, and
3003 interfaces provide support for the management of secondary
3004 classifications. We first demonstrate a case in which the types and
3005 constructors are defined on the C++ side and imported from the Ada
3006 side, and latter the reverse case.
3008 The root of our derivation will be the @code{Animal} class, with a
3009 single private attribute (the @code{Age} of the animal) and two public
3010 primitives to set and get the value of this attribute.
3012 @smallexample
3013 @b{class} Animal @{
3014  @b{public}:
3015    @b{virtual} void Set_Age (int New_Age);
3016    @b{virtual} int Age ();
3017  @b{private}:
3018    int Age_Count;
3020 @end smallexample
3022 Abstract interface types are defined in C++ by means of classes with pure
3023 virtual functions and no data members. In our example we will use two
3024 interfaces that provide support for the common management of @code{Carnivore}
3025 and @code{Domestic} animals:
3027 @smallexample
3028 @b{class} Carnivore @{
3029 @b{public}:
3030    @b{virtual} int Number_Of_Teeth () = 0;
3033 @b{class} Domestic @{
3034 @b{public}:
3035    @b{virtual void} Set_Owner (char* Name) = 0;
3037 @end smallexample
3039 Using these declarations, we can now say that a @code{Dog} is an animal that is
3040 both Carnivore and Domestic, that is:
3042 @smallexample
3043 @b{class} Dog : Animal, Carnivore, Domestic @{
3044  @b{public}:
3045    @b{virtual} int  Number_Of_Teeth ();
3046    @b{virtual} void Set_Owner (char* Name);
3048    Dog(); // Constructor
3049  @b{private}:
3050    int  Tooth_Count;
3051    char *Owner;
3053 @end smallexample
3055 In the following examples we will assume that the previous declarations are
3056 located in a file named @code{animals.h}. The following package demonstrates
3057 how to import these C++ declarations from the Ada side:
3059 @smallexample @c ada
3060 with Interfaces.C.Strings; use Interfaces.C.Strings;
3061 package Animals is
3062   type Carnivore is interface;
3063   pragma Convention (C_Plus_Plus, Carnivore);
3064   function Number_Of_Teeth (X : Carnivore)
3065      return Natural is abstract;
3067   type Domestic is interface;
3068   pragma Convention (C_Plus_Plus, Set_Owner);
3069   procedure Set_Owner
3070     (X    : in out Domestic;
3071      Name : Chars_Ptr) is abstract;
3073   type Animal is tagged record
3074     Age : Natural := 0;
3075   end record;
3076   pragma Import (C_Plus_Plus, Animal);
3078   procedure Set_Age (X : in out Animal; Age : Integer);
3079   pragma Import (C_Plus_Plus, Set_Age);
3081   function Age (X : Animal) return Integer;
3082   pragma Import (C_Plus_Plus, Age);
3084   type Dog is new Animal and Carnivore and Domestic with record
3085     Tooth_Count : Natural;
3086     Owner       : String (1 .. 30);
3087   end record;
3088   pragma Import (C_Plus_Plus, Dog);
3090   function Number_Of_Teeth (A : Dog) return Integer;
3091   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3093   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3094   pragma Import (C_Plus_Plus, Set_Owner);
3096   function New_Dog return Dog;
3097   pragma CPP_Constructor (New_Dog);
3098   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3099 end Animals;
3100 @end smallexample
3102 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3103 interfacing with these C++ classes is easy. The only requirement is that all
3104 the primitives and components must be declared exactly in the same order in
3105 the two languages.
3107 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3108 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3109 the arguments to the called primitives will be the same as for C++. For the
3110 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3111 to indicate that they have been defined on the C++ side; this is required
3112 because the dispatch table associated with these tagged types will be built
3113 in the C++ side and therefore will not contain the predefined Ada primitives
3114 which Ada would otherwise expect.
3116 As the reader can see there is no need to indicate the C++ mangled names
3117 associated with each subprogram because it is assumed that all the calls to
3118 these primitives will be dispatching calls. The only exception is the
3119 constructor, which must be registered with the compiler by means of
3120 @code{pragma CPP_Constructor} and needs to provide its associated C++
3121 mangled name because the Ada compiler generates direct calls to it.
3123 With the above packages we can now declare objects of type Dog on the Ada side
3124 and dispatch calls to the corresponding subprograms on the C++ side. We can
3125 also extend the tagged type Dog with further fields and primitives, and
3126 override some of its C++ primitives on the Ada side. For example, here we have
3127 a type derivation defined on the Ada side that inherits all the dispatching
3128 primitives of the ancestor from the C++ side.
3130 @smallexample
3131 @b{with} Animals; @b{use} Animals;
3132 @b{package} Vaccinated_Animals @b{is}
3133   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3134   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3135 @b{end} Vaccinated_Animals;
3136 @end smallexample
3138 It is important to note that, because of the ABI compatibility, the programmer
3139 does not need to add any further information to indicate either the object
3140 layout or the dispatch table entry associated with each dispatching operation.
3142 Now let us define all the types and constructors on the Ada side and export
3143 them to C++, using the same hierarchy of our previous example:
3145 @smallexample @c ada
3146 with Interfaces.C.Strings;
3147 use Interfaces.C.Strings;
3148 package Animals is
3149   type Carnivore is interface;
3150   pragma Convention (C_Plus_Plus, Carnivore);
3151   function Number_Of_Teeth (X : Carnivore)
3152      return Natural is abstract;
3154   type Domestic is interface;
3155   pragma Convention (C_Plus_Plus, Set_Owner);
3156   procedure Set_Owner
3157     (X    : in out Domestic;
3158      Name : Chars_Ptr) is abstract;
3160   type Animal is tagged record
3161     Age : Natural := 0;
3162   end record;
3163   pragma Convention (C_Plus_Plus, Animal);
3165   procedure Set_Age (X : in out Animal; Age : Integer);
3166   pragma Export (C_Plus_Plus, Set_Age);
3168   function Age (X : Animal) return Integer;
3169   pragma Export (C_Plus_Plus, Age);
3171   type Dog is new Animal and Carnivore and Domestic with record
3172     Tooth_Count : Natural;
3173     Owner       : String (1 .. 30);
3174   end record;
3175   pragma Convention (C_Plus_Plus, Dog);
3177   function Number_Of_Teeth (A : Dog) return Integer;
3178   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3180   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3181   pragma Export (C_Plus_Plus, Set_Owner);
3183   function New_Dog return Dog'Class;
3184   pragma Export (C_Plus_Plus, New_Dog);
3185 end Animals;
3186 @end smallexample
3188 Compared with our previous example the only difference is the use of
3189 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3190 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3191 nothing else to be done; as explained above, the only requirement is that all
3192 the primitives and components are declared in exactly the same order.
3194 For completeness, let us see a brief C++ main program that uses the
3195 declarations available in @code{animals.h} (presented in our first example) to
3196 import and use the declarations from the Ada side, properly initializing and
3197 finalizing the Ada run-time system along the way:
3199 @smallexample
3200 @b{#include} "animals.h"
3201 @b{#include} <iostream>
3202 @b{using namespace} std;
3204 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3205 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3206 void Check_Animal (Animal *obj)       @{@dots{}@}
3207 void Check_Dog (Dog *obj)             @{@dots{}@}
3209 @b{extern} "C" @{
3210   void adainit (void);
3211   void adafinal (void);
3212   Dog* new_dog ();
3215 void test ()
3217   Dog *obj = new_dog();  // Ada constructor
3218   Check_Carnivore (obj); // Check secondary DT
3219   Check_Domestic (obj);  // Check secondary DT
3220   Check_Animal (obj);    // Check primary DT
3221   Check_Dog (obj);       // Check primary DT
3224 int main ()
3226   adainit ();  test();  adafinal ();
3227   return 0;
3229 @end smallexample
3231 @node Comparison between GNAT and C/C++ Compilation Models
3232 @section Comparison between GNAT and C/C++ Compilation Models
3234 @noindent
3235 The GNAT model of compilation is close to the C and C++ models. You can
3236 think of Ada specs as corresponding to header files in C. As in C, you
3237 don't need to compile specs; they are compiled when they are used. The
3238 Ada @code{with} is similar in effect to the @code{#include} of a C
3239 header.
3241 One notable difference is that, in Ada, you may compile specs separately
3242 to check them for semantic and syntactic accuracy. This is not always
3243 possible with C headers because they are fragments of programs that have
3244 less specific syntactic or semantic rules.
3246 The other major difference is the requirement for running the binder,
3247 which performs two important functions. First, it checks for
3248 consistency. In C or C++, the only defense against assembling
3249 inconsistent programs lies outside the compiler, in a makefile, for
3250 example. The binder satisfies the Ada requirement that it be impossible
3251 to construct an inconsistent program when the compiler is used in normal
3252 mode.
3254 @cindex Elaboration order control
3255 The other important function of the binder is to deal with elaboration
3256 issues. There are also elaboration issues in C++ that are handled
3257 automatically. This automatic handling has the advantage of being
3258 simpler to use, but the C++ programmer has no control over elaboration.
3259 Where @code{gnatbind} might complain there was no valid order of
3260 elaboration, a C++ compiler would simply construct a program that
3261 malfunctioned at run time.
3262 @end ifclear
3264 @node Comparison between GNAT and Conventional Ada Library Models
3265 @section Comparison between GNAT and Conventional Ada Library Models
3267 @noindent
3268 This section is intended for Ada programmers who have
3269 used an Ada compiler implementing the traditional Ada library
3270 model, as described in the Ada Reference Manual.
3272 @cindex GNAT library
3273 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3274 source files themselves acts as the library. Compiling Ada programs does
3275 not generate any centralized information, but rather an object file and
3276 a ALI file, which are of interest only to the binder and linker.
3277 In a traditional system, the compiler reads information not only from
3278 the source file being compiled, but also from the centralized library.
3279 This means that the effect of a compilation depends on what has been
3280 previously compiled. In particular:
3282 @itemize @bullet
3283 @item
3284 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3285 to the version of the unit most recently compiled into the library.
3287 @item
3288 Inlining is effective only if the necessary body has already been
3289 compiled into the library.
3291 @item
3292 Compiling a unit may obsolete other units in the library.
3293 @end itemize
3295 @noindent
3296 In GNAT, compiling one unit never affects the compilation of any other
3297 units because the compiler reads only source files. Only changes to source
3298 files can affect the results of a compilation. In particular:
3300 @itemize @bullet
3301 @item
3302 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3303 to the source version of the unit that is currently accessible to the
3304 compiler.
3306 @item
3307 @cindex Inlining
3308 Inlining requires the appropriate source files for the package or
3309 subprogram bodies to be available to the compiler. Inlining is always
3310 effective, independent of the order in which units are complied.
3312 @item
3313 Compiling a unit never affects any other compilations. The editing of
3314 sources may cause previous compilations to be out of date if they
3315 depended on the source file being modified.
3316 @end itemize
3318 @noindent
3319 The most important result of these differences is that order of compilation
3320 is never significant in GNAT. There is no situation in which one is
3321 required to do one compilation before another. What shows up as order of
3322 compilation requirements in the traditional Ada library becomes, in
3323 GNAT, simple source dependencies; in other words, there is only a set
3324 of rules saying what source files must be present when a file is
3325 compiled.
3327 @ifset vms
3328 @node Placement of temporary files
3329 @section Placement of temporary files
3330 @cindex Temporary files (user control over placement)
3332 @noindent
3333 GNAT creates temporary files in the directory designated by the environment
3334 variable @env{TMPDIR}.
3335 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3336 for detailed information on how environment variables are resolved.
3337 For most users the easiest way to make use of this feature is to simply
3338 define @env{TMPDIR} as a job level logical name).
3339 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3340 for compiler temporary files, then you can include something like the
3341 following command in your @file{LOGIN.COM} file:
3343 @smallexample
3344 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3345 @end smallexample
3347 @noindent
3348 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3349 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3350 designated by @env{TEMP}.
3351 If none of these environment variables are defined then GNAT uses the
3352 directory designated by the logical name @code{SYS$SCRATCH:}
3353 (by default the user's home directory). If all else fails
3354 GNAT uses the current directory for temporary files.
3355 @end ifset
3357 @c *************************
3358 @node Compiling with gcc
3359 @chapter Compiling with @command{gcc}
3361 @noindent
3362 This chapter discusses how to compile Ada programs using the @command{gcc}
3363 command. It also describes the set of switches
3364 that can be used to control the behavior of the compiler.
3365 @menu
3366 * Compiling Programs::
3367 * Switches for gcc::
3368 * Search Paths and the Run-Time Library (RTL)::
3369 * Order of Compilation Issues::
3370 * Examples::
3371 @end menu
3373 @node Compiling Programs
3374 @section Compiling Programs
3376 @noindent
3377 The first step in creating an executable program is to compile the units
3378 of the program using the @command{gcc} command. You must compile the
3379 following files:
3381 @itemize @bullet
3382 @item
3383 the body file (@file{.adb}) for a library level subprogram or generic
3384 subprogram
3386 @item
3387 the spec file (@file{.ads}) for a library level package or generic
3388 package that has no body
3390 @item
3391 the body file (@file{.adb}) for a library level package
3392 or generic package that has a body
3394 @end itemize
3396 @noindent
3397 You need @emph{not} compile the following files
3399 @itemize @bullet
3401 @item
3402 the spec of a library unit which has a body
3404 @item
3405 subunits
3406 @end itemize
3408 @noindent
3409 because they are compiled as part of compiling related units. GNAT
3410 package specs
3411 when the corresponding body is compiled, and subunits when the parent is
3412 compiled.
3414 @cindex cannot generate code
3415 If you attempt to compile any of these files, you will get one of the
3416 following error messages (where @var{fff} is the name of the file you
3417 compiled):
3419 @smallexample
3420 cannot generate code for file @var{fff} (package spec)
3421 to check package spec, use -gnatc
3423 cannot generate code for file @var{fff} (missing subunits)
3424 to check parent unit, use -gnatc
3426 cannot generate code for file @var{fff} (subprogram spec)
3427 to check subprogram spec, use -gnatc
3429 cannot generate code for file @var{fff} (subunit)
3430 to check subunit, use -gnatc
3431 @end smallexample
3433 @noindent
3434 As indicated by the above error messages, if you want to submit
3435 one of these files to the compiler to check for correct semantics
3436 without generating code, then use the @option{-gnatc} switch.
3438 The basic command for compiling a file containing an Ada unit is
3440 @smallexample
3441 @c $ gcc -c @ovar{switches} @file{file name}
3442 @c Expanding @ovar macro inline (explanation in macro def comments)
3443 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3444 @end smallexample
3446 @noindent
3447 where @var{file name} is the name of the Ada file (usually
3448 having an extension
3449 @file{.ads} for a spec or @file{.adb} for a body).
3450 @ifclear vms
3451 You specify the
3452 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3453 @end ifclear
3454 The result of a successful compilation is an object file, which has the
3455 same name as the source file but an extension of @file{.o} and an Ada
3456 Library Information (ALI) file, which also has the same name as the
3457 source file, but with @file{.ali} as the extension. GNAT creates these
3458 two output files in the current directory, but you may specify a source
3459 file in any directory using an absolute or relative path specification
3460 containing the directory information.
3462 @findex gnat1
3463 @command{gcc} is actually a driver program that looks at the extensions of
3464 the file arguments and loads the appropriate compiler. For example, the
3465 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3466 These programs are in directories known to the driver program (in some
3467 configurations via environment variables you set), but need not be in
3468 your path. The @command{gcc} driver also calls the assembler and any other
3469 utilities needed to complete the generation of the required object
3470 files.
3472 It is possible to supply several file names on the same @command{gcc}
3473 command. This causes @command{gcc} to call the appropriate compiler for
3474 each file. For example, the following command lists two separate
3475 files to be compiled:
3477 @smallexample
3478 $ gcc -c x.adb y.adb
3479 @end smallexample
3481 @noindent
3482 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3483 @file{y.adb}.
3484 The compiler generates two object files @file{x.o} and @file{y.o}
3485 and the two ALI files @file{x.ali} and @file{y.ali}.
3486 Any switches apply to all the files ^listed,^listed.^
3488 @node Switches for gcc
3489 @section Switches for @command{gcc}
3491 @noindent
3492 The @command{gcc} command accepts switches that control the
3493 compilation process. These switches are fully described in this section.
3494 First we briefly list all the switches, in alphabetical order, then we
3495 describe the switches in more detail in functionally grouped sections.
3497 More switches exist for GCC than those documented here, especially
3498 for specific targets. However, their use is not recommended as
3499 they may change code generation in ways that are incompatible with
3500 the Ada run-time library, or can cause inconsistencies between
3501 compilation units.
3503 @menu
3504 * Output and Error Message Control::
3505 * Warning Message Control::
3506 * Debugging and Assertion Control::
3507 * Validity Checking::
3508 * Style Checking::
3509 * Run-Time Checks::
3510 * Using gcc for Syntax Checking::
3511 * Using gcc for Semantic Checking::
3512 * Compiling Different Versions of Ada::
3513 * Character Set Control::
3514 * File Naming Control::
3515 * Subprogram Inlining Control::
3516 * Auxiliary Output Control::
3517 * Debugging Control::
3518 * Exception Handling Control::
3519 * Units to Sources Mapping Files::
3520 * Integrated Preprocessing::
3521 * Code Generation Control::
3522 @ifset vms
3523 * Return Codes::
3524 @end ifset
3525 @end menu
3527 @table @option
3528 @c !sort!
3529 @ifclear vms
3530 @cindex @option{-b} (@command{gcc})
3531 @item -b @var{target}
3532 Compile your program to run on @var{target}, which is the name of a
3533 system configuration. You must have a GNAT cross-compiler built if
3534 @var{target} is not the same as your host system.
3536 @item -B@var{dir}
3537 @cindex @option{-B} (@command{gcc})
3538 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3539 from @var{dir} instead of the default location. Only use this switch
3540 when multiple versions of the GNAT compiler are available.
3541 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3542 GNU Compiler Collection (GCC)}, for further details. You would normally
3543 use the @option{-b} or @option{-V} switch instead.
3545 @item -c
3546 @cindex @option{-c} (@command{gcc})
3547 Compile. Always use this switch when compiling Ada programs.
3549 Note: for some other languages when using @command{gcc}, notably in
3550 the case of C and C++, it is possible to use
3551 use @command{gcc} without a @option{-c} switch to
3552 compile and link in one step. In the case of GNAT, you
3553 cannot use this approach, because the binder must be run
3554 and @command{gcc} cannot be used to run the GNAT binder.
3555 @end ifclear
3557 @item -fcallgraph-info@r{[}=su,da@r{]}
3558 @cindex @option{-fcallgraph-info} (@command{gcc})
3559 Makes the compiler output callgraph information for the program, on a
3560 per-file basis. The information is generated in the VCG format.  It can
3561 be decorated with additional, per-node and/or per-edge information, if a
3562 list of comma-separated markers is additionally specified. When the
3563 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3564 marker is specified, the callgraph is decorated with information about
3565 dynamically allocated objects.
3567 @item -fdump-scos
3568 @cindex @option{-fdump-scos} (@command{gcc})
3569 Generates SCO (Source Coverage Obligation) information in the ALI file.
3570 This information is used by advanced coverage tools. See unit @file{SCOs}
3571 in the compiler sources for details in files @file{scos.ads} and
3572 @file{scos.adb}.
3574 @item -flto@r{[}=n@r{]}
3575 @cindex @option{-flto} (@command{gcc})
3576 Enables Link Time Optimization. This switch must be used in conjunction
3577 with the traditional @option{-Ox} switches and instructs the compiler to
3578 defer most optimizations until the link stage. The advantage of this
3579 approach is that the compiler can do a whole-program analysis and choose
3580 the best interprocedural optimization strategy based on a complete view
3581 of the program, instead of a fragmentary view with the usual approach.
3582 This can also speed up the compilation of huge programs and reduce the
3583 size of the final executable, compared with a per-unit compilation with
3584 full inlining across modules enabled with the @option{-gnatn2} switch.
3585 The drawback of this approach is that it may require much more memory.
3586 The switch, as well as the accompanying @option{-Ox} switches, must be
3587 specified both for the compilation and the link phases.
3588 If the @var{n} parameter is specified, the optimization and final code
3589 generation at link time are executed using @var{n} parallel jobs by
3590 means of an installed @command{make} program.
3592 @item -fno-inline
3593 @cindex @option{-fno-inline} (@command{gcc})
3594 Suppresses all inlining, even if other optimization or inlining
3595 switches are set.  This includes suppression of inlining that
3596 results from the use of the pragma @code{Inline_Always}.
3597 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3598 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3599 effects if this switch is present.  Note that inlining can also
3600 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3602 @item -fno-inline-functions
3603 @cindex @option{-fno-inline-functions} (@command{gcc})
3604 Suppresses automatic inlining of subprograms, which is enabled
3605 if @option{-O3} is used.
3607 @item -fno-inline-small-functions
3608 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3609 Suppresses automatic inlining of small subprograms, which is enabled
3610 if @option{-O2} is used.
3612 @item -fno-inline-functions-called-once
3613 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3614 Suppresses inlining of subprograms local to the unit and called once
3615 from within it, which is enabled if @option{-O1} is used.
3617 @item -fno-ivopts
3618 @cindex @option{-fno-ivopts} (@command{gcc})
3619 Suppresses high-level loop induction variable optimizations, which are
3620 enabled if @option{-O1} is used. These optimizations are generally
3621 profitable but, for some specific cases of loops with numerous uses
3622 of the iteration variable that follow a common pattern, they may end
3623 up destroying the regularity that could be exploited at a lower level
3624 and thus producing inferior code.
3626 @item -fno-strict-aliasing
3627 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3628 Causes the compiler to avoid assumptions regarding non-aliasing
3629 of objects of different types. See
3630 @ref{Optimization and Strict Aliasing} for details.
3632 @item -fstack-check
3633 @cindex @option{-fstack-check} (@command{gcc})
3634 Activates stack checking.
3635 See @ref{Stack Overflow Checking} for details.
3637 @item -fstack-usage
3638 @cindex @option{-fstack-usage} (@command{gcc})
3639 Makes the compiler output stack usage information for the program, on a
3640 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3642 @item ^-g^/DEBUG^
3643 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3644 Generate debugging information. This information is stored in the object
3645 file and copied from there to the final executable file by the linker,
3646 where it can be read by the debugger. You must use the
3647 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3649 @item -gnat83
3650 @cindex @option{-gnat83} (@command{gcc})
3651 Enforce Ada 83 restrictions.
3653 @item -gnat95
3654 @cindex @option{-gnat95} (@command{gcc})
3655 Enforce Ada 95 restrictions.
3657 @item -gnat05
3658 @cindex @option{-gnat05} (@command{gcc})
3659 Allow full Ada 2005 features.
3661 @item -gnat2005
3662 @cindex @option{-gnat2005} (@command{gcc})
3663 Allow full Ada 2005 features (same as @option{-gnat05})
3665 @item -gnat12
3666 @cindex @option{-gnat12} (@command{gcc})
3668 @item -gnat2012
3669 @cindex @option{-gnat2012} (@command{gcc})
3670 Allow full Ada 2012 features (same as @option{-gnat12})
3672 @item -gnata
3673 @cindex @option{-gnata} (@command{gcc})
3674 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3675 activated. Note that these pragmas can also be controlled using the
3676 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3677 It also activates pragmas @code{Check}, @code{Precondition}, and
3678 @code{Postcondition}. Note that these pragmas can also be controlled
3679 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3680 also activates all assertions defined in the RM as aspects: preconditions,
3681 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3682 corresponding pragmas for type invariants and (sub)type predicates are
3683 also activated.
3685 @item -gnatA
3686 @cindex @option{-gnatA} (@command{gcc})
3687 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3688 it will be ignored.
3690 @item -gnatb
3691 @cindex @option{-gnatb} (@command{gcc})
3692 Generate brief messages to @file{stderr} even if verbose mode set.
3694 @item -gnatB
3695 @cindex @option{-gnatB} (@command{gcc})
3696 Assume no invalid (bad) values except for 'Valid attribute use
3697 (@pxref{Validity Checking}).
3699 @item -gnatc
3700 @cindex @option{-gnatc} (@command{gcc})
3701 Check syntax and semantics only (no code generation attempted). When the
3702 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3703 only given to the compiler (after @option{-cargs} or in package Compiler of
3704 the project file, @command{gnatmake} will fail because it will not find the
3705 object file after compilation. If @command{gnatmake} is called with
3706 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3707 Builder of the project file) then @command{gnatmake} will not fail because
3708 it will not look for the object files after compilation, and it will not try
3709 to build and link. This switch may not be given if a previous @code{-gnatR}
3710 switch has been given, since @code{-gnatR} requires that the code generator
3711 be called to complete determination of representation information.
3713 @item -gnatC
3714 @cindex @option{-gnatC} (@command{gcc})
3715 Generate CodePeer information (no code generation attempted).
3716 This switch will generate an intermediate representation suitable for
3717 use by CodePeer (@file{.scil} files). This switch is not compatible with
3718 code generation (it will, among other things, disable some switches such
3719 as -gnatn, and enable others such as -gnata).
3721 @item -gnatd
3722 @cindex @option{-gnatd} (@command{gcc})
3723 Specify debug options for the compiler. The string of characters after
3724 the @option{-gnatd} specify the specific debug options. The possible
3725 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3726 compiler source file @file{debug.adb} for details of the implemented
3727 debug options. Certain debug options are relevant to applications
3728 programmers, and these are documented at appropriate points in this
3729 users guide.
3731 @ifclear vms
3732 @item -gnatD
3733 @cindex @option{-gnatD[nn]} (@command{gcc})
3734 @end ifclear
3735 @ifset vms
3736 @item /XDEBUG /LXDEBUG=nnn
3737 @end ifset
3738 Create expanded source files for source level debugging. This switch
3739 also suppress generation of cross-reference information
3740 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3741 -gnatR switch has been given, since these two switches are not compatible.
3743 @item ^-gnateA^/ALIASING_CHECK^
3744 @cindex @option{-gnateA} (@command{gcc})
3745 Check that there is no aliasing between two parameters of the same subprogram.
3747 @item -gnatec=@var{path}
3748 @cindex @option{-gnatec} (@command{gcc})
3749 Specify a configuration pragma file
3750 @ifclear vms
3751 (the equal sign is optional)
3752 @end ifclear
3753 (@pxref{The Configuration Pragmas Files}).
3755 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3756 @cindex @option{-gnated} (@command{gcc})
3757 Disable atomic synchronization
3759 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3760 @cindex @option{-gnateD} (@command{gcc})
3761 Defines a symbol, associated with @var{value}, for preprocessing.
3762 (@pxref{Integrated Preprocessing}).
3764 @item -gnateE
3765 @cindex @option{-gnateE} (@command{gcc})
3766 Generate extra information in exception messages. In particular, display
3767 extra column information and the value and range associated with index and
3768 range check failures, and extra column information for access checks.
3769 In cases where the compiler is able to determine at compile time that
3770 a check will fail, it gives a warning, and the extra information is not
3771 produced at run time.
3773 @item -gnatef
3774 @cindex @option{-gnatef} (@command{gcc})
3775 Display full source path name in brief error messages.
3777 @item -gnateF
3778 @cindex @option{-gnateF} (@command{gcc})
3779 Check for overflow on all floating-point operations, including those
3780 for unconstrained predefined types. See description of pragma
3781 @code{Check_Float_Overflow} in GNAT RM.
3783 @item -gnateG
3784 @cindex @option{-gnateG} (@command{gcc})
3785 Save result of preprocessing in a text file.
3787 @item -gnatei@var{nnn}
3788 @cindex @option{-gnatei} (@command{gcc})
3789 Set maximum number of instantiations during compilation of a single unit to
3790 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3791 the rare case when a single unit legitimately exceeds this limit.
3793 @item -gnateI@var{nnn}
3794 @cindex @option{-gnateI} (@command{gcc})
3795 Indicates that the source is a multi-unit source and that the index of the
3796 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3797 to be a valid index in the multi-unit source.
3799 @item -gnatem=@var{path}
3800 @cindex @option{-gnatem} (@command{gcc})
3801 Specify a mapping file
3802 @ifclear vms
3803 (the equal sign is optional)
3804 @end ifclear
3805 (@pxref{Units to Sources Mapping Files}).
3807 @item -gnatep=@var{file}
3808 @cindex @option{-gnatep} (@command{gcc})
3809 Specify a preprocessing data file
3810 @ifclear vms
3811 (the equal sign is optional)
3812 @end ifclear
3813 (@pxref{Integrated Preprocessing}).
3815 @item -gnateP
3816 @cindex @option{-gnateP} (@command{gcc})
3817 Turn categorization dependency errors into warnings.
3818 Ada requires that units that WITH one another have compatible categories, for
3819 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3820 these errors become warnings (which can be ignored, or suppressed in the usual
3821 manner). This can be useful in some specialized circumstances such as the
3822 temporary use of special test software.
3824 @item -gnateS
3825 @cindex @option{-gnateS} (@command{gcc})
3826 Synonym of @option{-fdump-scos}, kept for backards compatibility.
3828 @item -gnatet=@var{path}
3829 @cindex @option{-gnatet=file} (@command{gcc})
3830 Generate target dependent information. The format of the output file is
3831 described in the section about switch @option{-gnateT}.
3833 @item -gnateT=@var{path}
3834 @cindex @option{-gnateT} (@command{gcc})
3835 Read target dependent information, such as endianness or sizes and alignments
3836 of base type. If this switch is passed, the default target dependent
3837 information of the compiler is replaced by the one read from the input file.
3838 This is used by tools other than the compiler, e.g. to do
3839 semantic analysis of programs that will run on some other target than
3840 the machine on which the tool is run.
3842 The following target dependent values should be defined,
3843 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3844 positive integer value, and fields marked with a question mark are
3845 boolean fields, where a value of 0 is False, and a value of 1 is True:
3847 @smallexample
3848 Bits_BE                    : Nat; -- Bits stored big-endian?
3849 Bits_Per_Unit              : Pos; -- Bits in a storage unit
3850 Bits_Per_Word              : Pos; -- Bits in a word
3851 Bytes_BE                   : Nat; -- Bytes stored big-endian?
3852 Char_Size                  : Pos; -- Standard.Character'Size
3853 Double_Float_Alignment     : Nat; -- Alignment of double float
3854 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
3855 Double_Size                : Pos; -- Standard.Long_Float'Size
3856 Float_Size                 : Pos; -- Standard.Float'Size
3857 Float_Words_BE             : Nat; -- Float words stored big-endian?
3858 Int_Size                   : Pos; -- Standard.Integer'Size
3859 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
3860 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
3861 Long_Size                  : Pos; -- Standard.Long_Integer'Size
3862 Maximum_Alignment          : Pos; -- Maximum permitted alignment
3863 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
3864 Pointer_Size               : Pos; -- System.Address'Size
3865 Short_Size                 : Pos; -- Standard.Short_Integer'Size
3866 Strict_Alignment           : Nat; -- Strict alignment?
3867 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3868 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
3869 Words_BE                   : Nat; -- Words stored big-endian?
3870 @end smallexample
3872 The format of the input file is as follows. First come the values of
3873 the variables defined above, with one line per value:
3875 @smallexample
3876 name  value
3877 @end smallexample
3879 where @code{name} is the name of the parameter, spelled out in full,
3880 and cased as in the above list, and @code{value} is an unsigned decimal
3881 integer. Two or more blanks separates the name from the value.
3883 All the variables must be present, in alphabetical order (i.e. the
3884 same order as the list above).
3886 Then there is a blank line to separate the two parts of the file. Then
3887 come the lines showing the floating-point types to be registered, with
3888 one line per registered mode:
3890 @smallexample
3891 name  digs float_rep size alignment
3892 @end smallexample
3894 where @code{name} is the string name of the type (which can have
3895 single spaces embedded in the name (e.g. long double), @code{digs} is
3896 the number of digits for the floating-point type, @code{float_rep} is
3897 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3898 AAMP), @code{size} is the size in bits, @code{alignment} is the
3899 alignment in bits. The name is followed by at least two blanks, fields
3900 are separated by at least one blank, and a LF character immediately
3901 follows the alignment field.
3903 Here is an example of target parametrization file:
3905 @smallexample
3906 Bits_BE                       0
3907 Bits_Per_Unit                 8
3908 Bits_Per_Word                64
3909 Bytes_BE                      0
3910 Char_Size                     8
3911 Double_Float_Alignment        0
3912 Double_Scalar_Alignment       0
3913 Double_Size                  64
3914 Float_Size                   32
3915 Float_Words_BE                0
3916 Int_Size                     64
3917 Long_Double_Size            128
3918 Long_Long_Size               64
3919 Long_Size                    64
3920 Maximum_Alignment            16
3921 Max_Unaligned_Field          64
3922 Pointer_Size                 64
3923 Short_Size                   16
3924 Strict_Alignment              0
3925 System_Allocator_Alignment   16
3926 Wchar_T_Size                 32
3927 Words_BE                      0
3929 float         15  I  64  64
3930 double        15  I  64  64
3931 long double   18  I  80 128
3932 TF            33  I 128 128
3933 @end smallexample
3935 @item -gnateu
3936 @cindex @option{-gnateu} (@command{gcc})
3937 Ignore unrecognized validity, warning, and style switches that
3938 appear after this switch is given. This may be useful when
3939 compiling sources developed on a later version of the compiler
3940 with an earlier version. Of course the earlier version must
3941 support this switch.
3943 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
3944 @cindex @option{-gnateV} (@command{gcc})
3945 Check validity of subprogram parameters.
3947 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
3948 @cindex @option{-gnateY} (@command{gcc})
3949 Ignore all STYLE_CHECKS pragmas. Full legality checks
3950 are still carried out, but the pragmas have no effect
3951 on what style checks are active. This allows all style
3952 checking options to be controlled from the command line.
3954 @item -gnatE
3955 @cindex @option{-gnatE} (@command{gcc})
3956 Full dynamic elaboration checks.
3958 @item -gnatf
3959 @cindex @option{-gnatf} (@command{gcc})
3960 Full errors. Multiple errors per line, all undefined references, do not
3961 attempt to suppress cascaded errors.
3963 @item -gnatF
3964 @cindex @option{-gnatF} (@command{gcc})
3965 Externals names are folded to all uppercase.
3967 @item ^-gnatg^/GNAT_INTERNAL^
3968 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3969 Internal GNAT implementation mode. This should not be used for
3970 applications programs, it is intended only for use by the compiler
3971 and its run-time library. For documentation, see the GNAT sources.
3972 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3973 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3974 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3975 so that all standard warnings and all standard style options are turned on.
3976 All warnings and style messages are treated as errors.
3978 @ifclear vms
3979 @item -gnatG=nn
3980 @cindex @option{-gnatG[nn]} (@command{gcc})
3981 @end ifclear
3982 @ifset vms
3983 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
3984 @end ifset
3985 List generated expanded code in source form.
3987 @item ^-gnath^/HELP^
3988 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3989 Output usage information. The output is written to @file{stdout}.
3991 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3992 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3993 Identifier character set
3994 @ifclear vms
3995 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3996 @end ifclear
3997 For details of the possible selections for @var{c},
3998 see @ref{Character Set Control}.
4000 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4001 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4002 Ignore representation clauses. When this switch is used,
4003 representation clauses are treated as comments. This is useful
4004 when initially porting code where you want to ignore rep clause
4005 problems, and also for compiling foreign code (particularly
4006 for use with ASIS). The representation clauses that are ignored
4007 are: enumeration_representation_clause, record_representation_clause,
4008 and attribute_definition_clause for the following attributes:
4009 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4010 Object_Size, Size, Small, Stream_Size, and Value_Size.
4011 Note that this option should be used only for compiling -- the
4012 code is likely to malfunction at run time.
4014 @item -gnatjnn
4015 @cindex @option{-gnatjnn} (@command{gcc})
4016 Reformat error messages to fit on nn character lines
4018 @item -gnatk=@var{n}
4019 @cindex @option{-gnatk} (@command{gcc})
4020 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4022 @item -gnatl
4023 @cindex @option{-gnatl} (@command{gcc})
4024 Output full source listing with embedded error messages.
4026 @item -gnatL
4027 @cindex @option{-gnatL} (@command{gcc})
4028 Used in conjunction with -gnatG or -gnatD to intersperse original
4029 source lines (as comment lines with line numbers) in the expanded
4030 source output.
4032 @item -gnatm=@var{n}
4033 @cindex @option{-gnatm} (@command{gcc})
4034 Limit number of detected error or warning messages to @var{n}
4035 where @var{n} is in the range 1..999999. The default setting if
4036 no switch is given is 9999. If the number of warnings reaches this
4037 limit, then a message is output and further warnings are suppressed,
4038 but the compilation is continued. If the number of error messages
4039 reaches this limit, then a message is output and the compilation
4040 is abandoned. The equal sign here is optional. A value of zero
4041 means that no limit applies.
4043 @item -gnatn[12]
4044 @cindex @option{-gnatn} (@command{gcc})
4045 Activate inlining for subprograms for which pragma @code{Inline} is
4046 specified. This inlining is performed by the GCC back-end. An optional
4047 digit sets the inlining level: 1 for moderate inlining across modules
4048 or 2 for full inlining across modules. If no inlining level is specified,
4049 the compiler will pick it based on the optimization level.
4051 @item -gnatN
4052 @cindex @option{-gnatN} (@command{gcc})
4053 Activate front end inlining for subprograms for which
4054 pragma @code{Inline} is specified. This inlining is performed
4055 by the front end and will be visible in the
4056 @option{-gnatG} output.
4058 When using a gcc-based back end (in practice this means using any version
4059 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4060 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4061 Historically front end inlining was more extensive than the gcc back end
4062 inlining, but that is no longer the case.
4064 @item -gnato??
4065 @cindex @option{-gnato??} (@command{gcc})
4066 Set default mode for handling generation of code to avoid intermediate
4067 arithmetic overflow. Here `@code{??}' is two digits, a
4068 single digit, or nothing. Each digit is one of the digits `@code{1}'
4069 through `@code{3}':
4071 @itemize @bullet
4072 @item   @code{1}:
4073 all intermediate overflows checked against base type (@code{STRICT})
4074 @item   @code{2}:
4075 minimize intermediate overflows (@code{MINIMIZED})
4076 @item   @code{3}:
4077 eliminate intermediate overflows (@code{ELIMINATED})
4078 @end itemize
4080 If only one digit appears then it applies to all
4081 cases; if two digits are given, then the first applies outside
4082 assertions, and the second within assertions.
4084 If no digits follow the @option{-gnato}, then it is equivalent to
4085 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
4086 causing all intermediate overflows to be handled in strict mode.
4088 This switch also causes arithmetic overflow checking to be performed
4089 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4091 The default if no option @option{-gnato} is given is that overflow handling
4092 is in @code{STRICT} mode (computations done using the base type), and that
4093 overflow checking is suppressed.
4095 Note that division by zero is a separate check that is not
4096 controlled by this switch (division by zero checking is on by default).
4098 See also @ref{Specifying the Desired Mode}.
4100 @item -gnatp
4101 @cindex @option{-gnatp} (@command{gcc})
4102 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4103 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4105 @item -gnat-p
4106 @cindex @option{-gnat-p} (@command{gcc})
4107 Cancel effect of previous @option{-gnatp} switch.
4109 @item -gnatP
4110 @cindex @option{-gnatP} (@command{gcc})
4111 Enable polling. This is required on some systems (notably Windows NT) to
4112 obtain asynchronous abort and asynchronous transfer of control capability.
4113 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4114 details.
4116 @item -gnatq
4117 @cindex @option{-gnatq} (@command{gcc})
4118 Don't quit. Try semantics, even if parse errors.
4120 @item -gnatQ
4121 @cindex @option{-gnatQ} (@command{gcc})
4122 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4124 @item -gnatr
4125 @cindex @option{-gnatr} (@command{gcc})
4126 Treat pragma Restrictions as Restriction_Warnings.
4128 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4129 @cindex @option{-gnatR} (@command{gcc})
4130 Output representation information for declared types and objects.
4131 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4132 been given, since these two switches are not compatible. It is also not allowed
4133 if a previous @code{-gnatc} switch has been given, since we must be generating
4134 code to be able to determine representation information.
4136 @item ^-gnatRm[s]^/REPRESENTATION_INFO^
4137 Output convention and parameter passing mechanisms for all subprograms.
4138 This form is also incompatible with the use of @code{-gnatc}.
4140 @item -gnats
4141 @cindex @option{-gnats} (@command{gcc})
4142 Syntax check only.
4144 @item -gnatS
4145 @cindex @option{-gnatS} (@command{gcc})
4146 Print package Standard.
4148 @item -gnatt
4149 @cindex @option{-gnatt} (@command{gcc})
4150 Generate tree output file.
4152 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4153 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4154 All compiler tables start at @var{nnn} times usual starting size.
4156 @item -gnatu
4157 @cindex @option{-gnatu} (@command{gcc})
4158 List units for this compilation.
4160 @item -gnatU
4161 @cindex @option{-gnatU} (@command{gcc})
4162 Tag all error messages with the unique string ``error:''
4164 @item -gnatv
4165 @cindex @option{-gnatv} (@command{gcc})
4166 Verbose mode. Full error output with source lines to @file{stdout}.
4168 @item -gnatV
4169 @cindex @option{-gnatV} (@command{gcc})
4170 Control level of validity checking (@pxref{Validity Checking}).
4172 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4173 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4174 Warning mode where
4175 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4176 the exact warnings that
4177 are enabled or disabled (@pxref{Warning Message Control}).
4179 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4180 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4181 Wide character encoding method
4182 @ifclear vms
4183 (@var{e}=n/h/u/s/e/8).
4184 @end ifclear
4185 @ifset vms
4186 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4187 @end ifset
4189 @item -gnatx
4190 @cindex @option{-gnatx} (@command{gcc})
4191 Suppress generation of cross-reference information.
4193 @item -gnatX
4194 @cindex @option{-gnatX} (@command{gcc})
4195 Enable GNAT implementation extensions and latest Ada version.
4197 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4198 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4199 Enable built-in style checks (@pxref{Style Checking}).
4201 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4202 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4203 Distribution stub generation and compilation
4204 @ifclear vms
4205 (@var{m}=r/c for receiver/caller stubs).
4206 @end ifclear
4207 @ifset vms
4208 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4209 to be generated and compiled).
4210 @end ifset
4212 @item ^-I^/SEARCH=^@var{dir}
4213 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4214 @cindex RTL
4215 Direct GNAT to search the @var{dir} directory for source files needed by
4216 the current compilation
4217 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4219 @item ^-I-^/NOCURRENT_DIRECTORY^
4220 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4221 @cindex RTL
4222 Except for the source file named in the command line, do not look for source
4223 files in the directory containing the source file named in the command line
4224 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4226 @ifclear vms
4227 @item -mbig-switch
4228 @cindex @option{-mbig-switch} (@command{gcc})
4229 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4230 This standard gcc switch causes the compiler to use larger offsets in its
4231 jump table representation for @code{case} statements.
4232 This may result in less efficient code, but is sometimes necessary
4233 (for example on HP-UX targets)
4234 @cindex HP-UX and @option{-mbig-switch} option
4235 in order to compile large and/or nested @code{case} statements.
4237 @item -o @var{file}
4238 @cindex @option{-o} (@command{gcc})
4239 This switch is used in @command{gcc} to redirect the generated object file
4240 and its associated ALI file. Beware of this switch with GNAT, because it may
4241 cause the object file and ALI file to have different names which in turn
4242 may confuse the binder and the linker.
4243 @end ifclear
4245 @item -nostdinc
4246 @cindex @option{-nostdinc} (@command{gcc})
4247 Inhibit the search of the default location for the GNAT Run Time
4248 Library (RTL) source files.
4250 @item -nostdlib
4251 @cindex @option{-nostdlib} (@command{gcc})
4252 Inhibit the search of the default location for the GNAT Run Time
4253 Library (RTL) ALI files.
4255 @ifclear vms
4256 @c @item -O@ovar{n}
4257 @c Expanding @ovar macro inline (explanation in macro def comments)
4258 @item -O@r{[}@var{n}@r{]}
4259 @cindex @option{-O} (@command{gcc})
4260 @var{n} controls the optimization level.
4262 @table @asis
4263 @item n = 0
4264 No optimization, the default setting if no @option{-O} appears
4266 @item n = 1
4267 Normal optimization, the default if you specify @option{-O} without
4268 an operand. A good compromise between code quality and compilation
4269 time.
4271 @item n = 2
4272 Extensive optimization, may improve execution time, possibly at the cost of
4273 substantially increased compilation time.
4275 @item n = 3
4276 Same as @option{-O2}, and also includes inline expansion for small subprograms
4277 in the same unit.
4279 @item n = s
4280 Optimize space usage
4281 @end table
4283 @noindent
4284 See also @ref{Optimization Levels}.
4285 @end ifclear
4287 @ifset vms
4288 @item  /NOOPTIMIZE
4289 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4290 Equivalent to @option{/OPTIMIZE=NONE}.
4291 This is the default behavior in the absence of an @option{/OPTIMIZE}
4292 qualifier.
4294 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4295 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4296 Selects the level of optimization for your program. The supported
4297 keywords are as follows:
4298 @table @code
4299 @item   ALL
4300 Perform most optimizations, including those that
4301 are expensive.
4302 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4303 without keyword options.
4305 @item   NONE
4306 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4308 @item SOME
4309 Perform some optimizations, but omit ones that are costly.
4311 @item   DEVELOPMENT
4312 Same as @code{SOME}.
4314 @item INLINING
4315 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4316 automatic inlining of small subprograms within a unit
4318 @item   UNROLL_LOOPS
4319 Try to unroll loops. This keyword may be specified together with
4320 any keyword above other than @code{NONE}. Loop unrolling
4321 usually, but not always, improves the performance of programs.
4323 @item SPACE
4324 Optimize space usage
4325 @end table
4327 @noindent
4328 See also @ref{Optimization Levels}.
4329 @end ifset
4331 @ifclear vms
4332 @item -pass-exit-codes
4333 @cindex @option{-pass-exit-codes} (@command{gcc})
4334 Catch exit codes from the compiler and use the most meaningful as
4335 exit status.
4336 @end ifclear
4338 @item --RTS=@var{rts-path}
4339 @cindex @option{--RTS} (@command{gcc})
4340 Specifies the default location of the runtime library. Same meaning as the
4341 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4343 @item ^-S^/ASM^
4344 @cindex @option{^-S^/ASM^} (@command{gcc})
4345 ^Used in place of @option{-c} to^Used to^
4346 cause the assembler source file to be
4347 generated, using @file{^.s^.S^} as the extension,
4348 instead of the object file.
4349 This may be useful if you need to examine the generated assembly code.
4351 @item ^-fverbose-asm^/VERBOSE_ASM^
4352 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4353 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4354 to cause the generated assembly code file to be annotated with variable
4355 names, making it significantly easier to follow.
4357 @item ^-v^/VERBOSE^
4358 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4359 Show commands generated by the @command{gcc} driver. Normally used only for
4360 debugging purposes or if you need to be sure what version of the
4361 compiler you are executing.
4363 @ifclear vms
4364 @item -V @var{ver}
4365 @cindex @option{-V} (@command{gcc})
4366 Execute @var{ver} version of the compiler. This is the @command{gcc}
4367 version, not the GNAT version.
4368 @end ifclear
4370 @item ^-w^/NO_BACK_END_WARNINGS^
4371 @cindex @option{-w} (@command{gcc})
4372 Turn off warnings generated by the back end of the compiler. Use of
4373 this switch also causes the default for front end warnings to be set
4374 to suppress (as though @option{-gnatws} had appeared at the start of
4375 the options).
4377 @end table
4379 @ifclear vms
4380 @c Combining qualifiers does not work on VMS
4381 You may combine a sequence of GNAT switches into a single switch. For
4382 example, the combined switch
4384 @cindex Combining GNAT switches
4385 @smallexample
4386 -gnatofi3
4387 @end smallexample
4389 @noindent
4390 is equivalent to specifying the following sequence of switches:
4392 @smallexample
4393 -gnato -gnatf -gnati3
4394 @end smallexample
4395 @end ifclear
4397 @noindent
4398 The following restrictions apply to the combination of switches
4399 in this manner:
4401 @itemize @bullet
4402 @item
4403 The switch @option{-gnatc} if combined with other switches must come
4404 first in the string.
4406 @item
4407 The switch @option{-gnats} if combined with other switches must come
4408 first in the string.
4410 @item
4411 The switches
4412 ^^@option{/DISTRIBUTION_STUBS=},^
4413 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4414 switches, and only one of them may appear in the command line.
4416 @item
4417 The switch @option{-gnat-p} may not be combined with any other switch.
4419 @ifclear vms
4420 @item
4421 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4422 switch), then all further characters in the switch are interpreted
4423 as style modifiers (see description of @option{-gnaty}).
4425 @item
4426 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4427 switch), then all further characters in the switch are interpreted
4428 as debug flags (see description of @option{-gnatd}).
4430 @item
4431 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4432 switch), then all further characters in the switch are interpreted
4433 as warning mode modifiers (see description of @option{-gnatw}).
4435 @item
4436 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4437 switch), then all further characters in the switch are interpreted
4438 as validity checking options (@pxref{Validity Checking}).
4440 @item
4441 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4442 a combined list of options.
4443 @end ifclear
4444 @end itemize
4446 @node Output and Error Message Control
4447 @subsection Output and Error Message Control
4448 @findex stderr
4450 @noindent
4451 The standard default format for error messages is called ``brief format''.
4452 Brief format messages are written to @file{stderr} (the standard error
4453 file) and have the following form:
4455 @smallexample
4456 e.adb:3:04: Incorrect spelling of keyword "function"
4457 e.adb:4:20: ";" should be "is"
4458 @end smallexample
4460 @noindent
4461 The first integer after the file name is the line number in the file,
4462 and the second integer is the column number within the line.
4463 @ifclear vms
4464 @code{GPS} can parse the error messages
4465 and point to the referenced character.
4466 @end ifclear
4467 The following switches provide control over the error message
4468 format:
4470 @table @option
4471 @c !sort!
4472 @item -gnatv
4473 @cindex @option{-gnatv} (@command{gcc})
4474 @findex stdout
4475 @ifclear vms
4476 The v stands for verbose.
4477 @end ifclear
4478 The effect of this setting is to write long-format error
4479 messages to @file{stdout} (the standard output file.
4480 The same program compiled with the
4481 @option{-gnatv} switch would generate:
4483 @smallexample
4484 @cartouche
4485 3. funcion X (Q : Integer)
4486    |
4487 >>> Incorrect spelling of keyword "function"
4488 4. return Integer;
4489                  |
4490 >>> ";" should be "is"
4491 @end cartouche
4492 @end smallexample
4494 @noindent
4495 The vertical bar indicates the location of the error, and the @samp{>>>}
4496 prefix can be used to search for error messages. When this switch is
4497 used the only source lines output are those with errors.
4499 @item -gnatl
4500 @cindex @option{-gnatl} (@command{gcc})
4501 @ifclear vms
4502 The @code{l} stands for list.
4503 @end ifclear
4504 This switch causes a full listing of
4505 the file to be generated. In the case where a body is
4506 compiled, the corresponding spec is also listed, along
4507 with any subunits. Typical output from compiling a package
4508 body @file{p.adb} might look like:
4510 @smallexample @c ada
4511 @cartouche
4512  Compiling: p.adb
4514      1. package body p is
4515      2.    procedure a;
4516      3.    procedure a is separate;
4517      4. begin
4518      5.    null
4519                |
4520         >>> missing ";"
4522      6. end;
4524 Compiling: p.ads
4526      1. package p is
4527      2.    pragma Elaborate_Body
4528                                 |
4529         >>> missing ";"
4531      3. end p;
4533 Compiling: p-a.adb
4535      1. separate p
4536                 |
4537         >>> missing "("
4539      2. procedure a is
4540      3. begin
4541      4.    null
4542                |
4543         >>> missing ";"
4545      5. end;
4546 @end cartouche
4547 @end smallexample
4549 @noindent
4550 @findex stderr
4551 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4552 standard output is redirected, a brief summary is written to
4553 @file{stderr} (standard error) giving the number of error messages and
4554 warning messages generated.
4556 @item ^-gnatl^/OUTPUT_FILE^=file
4557 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4558 This has the same effect as @option{-gnatl} except that the output is
4559 written to a file instead of to standard output. If the given name
4560 @file{fname} does not start with a period, then it is the full name
4561 of the file to be written. If @file{fname} is an extension, it is
4562 appended to the name of the file being compiled. For example, if
4563 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4564 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4566 @item -gnatU
4567 @cindex @option{-gnatU} (@command{gcc})
4568 This switch forces all error messages to be preceded by the unique
4569 string ``error:''. This means that error messages take a few more
4570 characters in space, but allows easy searching for and identification
4571 of error messages.
4573 @item -gnatb
4574 @cindex @option{-gnatb} (@command{gcc})
4575 @ifclear vms
4576 The @code{b} stands for brief.
4577 @end ifclear
4578 This switch causes GNAT to generate the
4579 brief format error messages to @file{stderr} (the standard error
4580 file) as well as the verbose
4581 format message or full listing (which as usual is written to
4582 @file{stdout} (the standard output file).
4584 @item -gnatm=@var{n}
4585 @cindex @option{-gnatm} (@command{gcc})
4586 @ifclear vms
4587 The @code{m} stands for maximum.
4588 @end ifclear
4589 @var{n} is a decimal integer in the
4590 range of 1 to 999999 and limits the number of error or warning
4591 messages to be generated. For example, using
4592 @option{-gnatm2} might yield
4594 @smallexample
4595 e.adb:3:04: Incorrect spelling of keyword "function"
4596 e.adb:5:35: missing ".."
4597 fatal error: maximum number of errors detected
4598 compilation abandoned
4599 @end smallexample
4601 @noindent
4602 The default setting if
4603 no switch is given is 9999. If the number of warnings reaches this
4604 limit, then a message is output and further warnings are suppressed,
4605 but the compilation is continued. If the number of error messages
4606 reaches this limit, then a message is output and the compilation
4607 is abandoned. A value of zero means that no limit applies.
4609 @noindent
4610 Note that the equal sign is optional, so the switches
4611 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4613 @item -gnatf
4614 @cindex @option{-gnatf} (@command{gcc})
4615 @cindex Error messages, suppressing
4616 @ifclear vms
4617 The @code{f} stands for full.
4618 @end ifclear
4619 Normally, the compiler suppresses error messages that are likely to be
4620 redundant. This switch causes all error
4621 messages to be generated. In particular, in the case of
4622 references to undefined variables. If a given variable is referenced
4623 several times, the normal format of messages is
4624 @smallexample
4625 e.adb:7:07: "V" is undefined (more references follow)
4626 @end smallexample
4628 @noindent
4629 where the parenthetical comment warns that there are additional
4630 references to the variable @code{V}. Compiling the same program with the
4631 @option{-gnatf} switch yields
4633 @smallexample
4634 e.adb:7:07: "V" is undefined
4635 e.adb:8:07: "V" is undefined
4636 e.adb:8:12: "V" is undefined
4637 e.adb:8:16: "V" is undefined
4638 e.adb:9:07: "V" is undefined
4639 e.adb:9:12: "V" is undefined
4640 @end smallexample
4642 @noindent
4643 The @option{-gnatf} switch also generates additional information for
4644 some error messages.  Some examples are:
4646 @itemize @bullet
4647 @item
4648 Details on possibly non-portable unchecked conversion
4649 @item
4650 List possible interpretations for ambiguous calls
4651 @item
4652 Additional details on incorrect parameters
4653 @end itemize
4655 @item -gnatjnn
4656 @cindex @option{-gnatjnn} (@command{gcc})
4657 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4658 with continuation lines are treated as though the continuation lines were
4659 separate messages (and so a warning with two continuation lines counts as
4660 three warnings, and is listed as three separate messages).
4662 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4663 messages are output in a different manner. A message and all its continuation
4664 lines are treated as a unit, and count as only one warning or message in the
4665 statistics totals. Furthermore, the message is reformatted so that no line
4666 is longer than nn characters.
4668 @item -gnatq
4669 @cindex @option{-gnatq} (@command{gcc})
4670 @ifclear vms
4671 The @code{q} stands for quit (really ``don't quit'').
4672 @end ifclear
4673 In normal operation mode, the compiler first parses the program and
4674 determines if there are any syntax errors. If there are, appropriate
4675 error messages are generated and compilation is immediately terminated.
4676 This switch tells
4677 GNAT to continue with semantic analysis even if syntax errors have been
4678 found. This may enable the detection of more errors in a single run. On
4679 the other hand, the semantic analyzer is more likely to encounter some
4680 internal fatal error when given a syntactically invalid tree.
4682 @item -gnatQ
4683 @cindex @option{-gnatQ} (@command{gcc})
4684 In normal operation mode, the @file{ALI} file is not generated if any
4685 illegalities are detected in the program. The use of @option{-gnatQ} forces
4686 generation of the @file{ALI} file. This file is marked as being in
4687 error, so it cannot be used for binding purposes, but it does contain
4688 reasonably complete cross-reference information, and thus may be useful
4689 for use by tools (e.g., semantic browsing tools or integrated development
4690 environments) that are driven from the @file{ALI} file. This switch
4691 implies @option{-gnatq}, since the semantic phase must be run to get a
4692 meaningful ALI file.
4694 In addition, if @option{-gnatt} is also specified, then the tree file is
4695 generated even if there are illegalities. It may be useful in this case
4696 to also specify @option{-gnatq} to ensure that full semantic processing
4697 occurs. The resulting tree file can be processed by ASIS, for the purpose
4698 of providing partial information about illegal units, but if the error
4699 causes the tree to be badly malformed, then ASIS may crash during the
4700 analysis.
4702 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4703 being in error, @command{gnatmake} will attempt to recompile the source when it
4704 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4706 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4707 since ALI files are never generated if @option{-gnats} is set.
4709 @end table
4711 @node Warning Message Control
4712 @subsection Warning Message Control
4713 @cindex Warning messages
4714 @noindent
4715 In addition to error messages, which correspond to illegalities as defined
4716 in the Ada Reference Manual, the compiler detects two kinds of warning
4717 situations.
4719 First, the compiler considers some constructs suspicious and generates a
4720 warning message to alert you to a possible error. Second, if the
4721 compiler detects a situation that is sure to raise an exception at
4722 run time, it generates a warning message. The following shows an example
4723 of warning messages:
4724 @smallexample
4725 e.adb:4:24: warning: creation of object may raise Storage_Error
4726 e.adb:10:17: warning: static value out of range
4727 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4728 @end smallexample
4730 @noindent
4731 GNAT considers a large number of situations as appropriate
4732 for the generation of warning messages. As always, warnings are not
4733 definite indications of errors. For example, if you do an out-of-range
4734 assignment with the deliberate intention of raising a
4735 @code{Constraint_Error} exception, then the warning that may be
4736 issued does not indicate an error. Some of the situations for which GNAT
4737 issues warnings (at least some of the time) are given in the following
4738 list. This list is not complete, and new warnings are often added to
4739 subsequent versions of GNAT. The list is intended to give a general idea
4740 of the kinds of warnings that are generated.
4742 @itemize @bullet
4743 @item
4744 Possible infinitely recursive calls
4746 @item
4747 Out-of-range values being assigned
4749 @item
4750 Possible order of elaboration problems
4752 @item
4753 Assertions (pragma Assert) that are sure to fail
4755 @item
4756 Unreachable code
4758 @item
4759 Address clauses with possibly unaligned values, or where an attempt is
4760 made to overlay a smaller variable with a larger one.
4762 @item
4763 Fixed-point type declarations with a null range
4765 @item
4766 Direct_IO or Sequential_IO instantiated with a type that has access values
4768 @item
4769 Variables that are never assigned a value
4771 @item
4772 Variables that are referenced before being initialized
4774 @item
4775 Task entries with no corresponding @code{accept} statement
4777 @item
4778 Duplicate accepts for the same task entry in a @code{select}
4780 @item
4781 Objects that take too much storage
4783 @item
4784 Unchecked conversion between types of differing sizes
4786 @item
4787 Missing @code{return} statement along some execution path in a function
4789 @item
4790 Incorrect (unrecognized) pragmas
4792 @item
4793 Incorrect external names
4795 @item
4796 Allocation from empty storage pool
4798 @item
4799 Potentially blocking operation in protected type
4801 @item
4802 Suspicious parenthesization of expressions
4804 @item
4805 Mismatching bounds in an aggregate
4807 @item
4808 Attempt to return local value by reference
4810 @item
4811 Premature instantiation of a generic body
4813 @item
4814 Attempt to pack aliased components
4816 @item
4817 Out of bounds array subscripts
4819 @item
4820 Wrong length on string assignment
4822 @item
4823 Violations of style rules if style checking is enabled
4825 @item
4826 Unused @code{with} clauses
4828 @item
4829 @code{Bit_Order} usage that does not have any effect
4831 @item
4832 @code{Standard.Duration} used to resolve universal fixed expression
4834 @item
4835 Dereference of possibly null value
4837 @item
4838 Declaration that is likely to cause storage error
4840 @item
4841 Internal GNAT unit @code{with}'ed by application unit
4843 @item
4844 Values known to be out of range at compile time
4846 @item
4847 Unreferenced labels and variables
4849 @item
4850 Address overlays that could clobber memory
4852 @item
4853 Unexpected initialization when address clause present
4855 @item
4856 Bad alignment for address clause
4858 @item
4859 Useless type conversions
4861 @item
4862 Redundant assignment statements and other redundant constructs
4864 @item
4865 Useless exception handlers
4867 @item
4868 Accidental hiding of name by child unit
4870 @item
4871 Access before elaboration detected at compile time
4873 @item
4874 A range in a @code{for} loop that is known to be null or might be null
4876 @end itemize
4878 @noindent
4879 The following section lists compiler switches that are available
4880 to control the handling of warning messages. It is also possible
4881 to exercise much finer control over what warnings are issued and
4882 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4883 gnat_rm, GNAT Reference manual}.
4885 @table @option
4886 @c !sort!
4887 @item -gnatwa
4888 @emph{Activate most optional warnings.}
4889 @cindex @option{-gnatwa} (@command{gcc})
4890 This switch activates most optional warning messages.  See the remaining list
4891 in this section for details on optional warning messages that can be
4892 individually controlled.  The warnings that are not turned on by this
4893 switch are
4894 @option{-gnatwd} (implicit dereferencing),
4895 @option{-gnatwh} (hiding),
4896 @option{-gnatw.d} (tag warnings with -gnatw switch)
4897 @option{-gnatw.h} (holes (gaps) in record layouts)
4898 @option{-gnatw.i} (overlapping actuals),
4899 @option{-gnatw.k} (redefinition of names in standard),
4900 @option{-gnatwl} (elaboration warnings),
4901 @option{-gnatw.l} (inherited aspects),
4902 @option{-gnatw.o} (warn on values set by out parameters ignored),
4903 @option{-gnatwt} (tracking of deleted conditional code)
4904 and @option{-gnatw.u} (unordered enumeration),
4905 All other optional warnings are turned on.
4907 @item -gnatwA
4908 @emph{Suppress all optional errors.}
4909 @cindex @option{-gnatwA} (@command{gcc})
4910 This switch suppresses all optional warning messages, see remaining list
4911 in this section for details on optional warning messages that can be
4912 individually controlled. Note that unlike switch @option{-gnatws}, the
4913 use of switch @option{-gnatwA} does not suppress warnings that are
4914 normally given unconditionally and cannot be individually controlled
4915 (for example, the warning about a missing exit path in a function).
4916 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4917 the use of switch @option{-gnatwA} can be individually turned back
4918 on. For example the use of switch @option{-gnatwA} followed by
4919 switch @option{-gnatwd} will suppress all optional warnings except
4920 the warnings for implicit dereferencing.
4922 @item -gnatw.a
4923 @emph{Activate warnings on failing assertions.}
4924 @cindex @option{-gnatw.a} (@command{gcc})
4925 @cindex Assert failures
4926 This switch activates warnings for assertions where the compiler can tell at
4927 compile time that the assertion will fail. Note that this warning is given
4928 even if assertions are disabled. The default is that such warnings are
4929 generated.
4931 @item -gnatw.A
4932 @emph{Suppress warnings on failing assertions.}
4933 @cindex @option{-gnatw.A} (@command{gcc})
4934 @cindex Assert failures
4935 This switch suppresses warnings for assertions where the compiler can tell at
4936 compile time that the assertion will fail.
4938 @item -gnatwb
4939 @emph{Activate warnings on bad fixed values.}
4940 @cindex @option{-gnatwb} (@command{gcc})
4941 @cindex Bad fixed values
4942 @cindex Fixed-point Small value
4943 @cindex Small value
4944 This switch activates warnings for static fixed-point expressions whose
4945 value is not an exact multiple of Small. Such values are implementation
4946 dependent, since an implementation is free to choose either of the multiples
4947 that surround the value. GNAT always chooses the closer one, but this is not
4948 required behavior, and it is better to specify a value that is an exact
4949 multiple, ensuring predictable execution. The default is that such warnings
4950 are not generated.
4952 @item -gnatwB
4953 @emph{Suppress warnings on bad fixed values.}
4954 @cindex @option{-gnatwB} (@command{gcc})
4955 This switch suppresses warnings for static fixed-point expressions whose
4956 value is not an exact multiple of Small.
4958 @item -gnatw.b
4959 @emph{Activate warnings on biased representation.}
4960 @cindex @option{-gnatw.b} (@command{gcc})
4961 @cindex Biased representation
4962 This switch activates warnings when a size clause, value size clause, component
4963 clause, or component size clause forces the use of biased representation for an
4964 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4965 to represent 10/11). The default is that such warnings are generated.
4967 @item -gnatw.B
4968 @emph{Suppress warnings on biased representation.}
4969 @cindex @option{-gnatwB} (@command{gcc})
4970 This switch suppresses warnings for representation clauses that force the use
4971 of biased representation.
4973 @item -gnatwc
4974 @emph{Activate warnings on conditionals.}
4975 @cindex @option{-gnatwc} (@command{gcc})
4976 @cindex Conditionals, constant
4977 This switch activates warnings for conditional expressions used in
4978 tests that are known to be True or False at compile time. The default
4979 is that such warnings are not generated.
4980 Note that this warning does
4981 not get issued for the use of boolean variables or constants whose
4982 values are known at compile time, since this is a standard technique
4983 for conditional compilation in Ada, and this would generate too many
4984 false positive warnings.
4986 This warning option also activates a special test for comparisons using
4987 the operators ``>='' and`` <=''.
4988 If the compiler can tell that only the equality condition is possible,
4989 then it will warn that the ``>'' or ``<'' part of the test
4990 is useless and that the operator could be replaced by ``=''.
4991 An example would be comparing a @code{Natural} variable <= 0.
4993 This warning option also generates warnings if
4994 one or both tests is optimized away in a membership test for integer
4995 values if the result can be determined at compile time. Range tests on
4996 enumeration types are not included, since it is common for such tests
4997 to include an end point.
4999 This warning can also be turned on using @option{-gnatwa}.
5001 @item -gnatwC
5002 @emph{Suppress warnings on conditionals.}
5003 @cindex @option{-gnatwC} (@command{gcc})
5004 This switch suppresses warnings for conditional expressions used in
5005 tests that are known to be True or False at compile time.
5007 @item -gnatw.c
5008 @emph{Activate warnings on missing component clauses.}
5009 @cindex @option{-gnatw.c} (@command{gcc})
5010 @cindex Component clause, missing
5011 This switch activates warnings for record components where a record
5012 representation clause is present and has component clauses for the
5013 majority, but not all, of the components. A warning is given for each
5014 component for which no component clause is present.
5016 This warning can also be turned on using @option{-gnatwa}.
5018 @item -gnatw.C
5019 @emph{Suppress warnings on missing component clauses.}
5020 @cindex @option{-gnatwC} (@command{gcc})
5021 This switch suppresses warnings for record components that are
5022 missing a component clause in the situation described above.
5024 @item -gnatwd
5025 @emph{Activate warnings on implicit dereferencing.}
5026 @cindex @option{-gnatwd} (@command{gcc})
5027 If this switch is set, then the use of a prefix of an access type
5028 in an indexed component, slice, or selected component without an
5029 explicit @code{.all} will generate a warning. With this warning
5030 enabled, access checks occur only at points where an explicit
5031 @code{.all} appears in the source code (assuming no warnings are
5032 generated as a result of this switch). The default is that such
5033 warnings are not generated.
5034 Note that @option{-gnatwa} does not affect the setting of
5035 this warning option.
5037 @item -gnatwD
5038 @emph{Suppress warnings on implicit dereferencing.}
5039 @cindex @option{-gnatwD} (@command{gcc})
5040 @cindex Implicit dereferencing
5041 @cindex Dereferencing, implicit
5042 This switch suppresses warnings for implicit dereferences in
5043 indexed components, slices, and selected components.
5045 @item -gnatw.d
5046 @emph{Activate tagging of warning messages.}
5047 @cindex @option{-gnatw.d} (@command{gcc})
5048 If this switch is set, then warning messages are tagged, either with
5049 the string ``@option{-gnatw?}'' showing which switch controls the warning,
5050 or with ``[enabled by default]'' if the warning is not under control of a
5051 specific @option{-gnatw?} switch. This mode is off by default, and is not
5052 affected by the use of @code{-gnatwa}.
5054 @item -gnatw.D
5055 @emph{Deactivate tagging of warning messages.}
5056 @cindex @option{-gnatw.d} (@command{gcc})
5057 If this switch is set, then warning messages return to the default
5058 mode in which warnings are not tagged as described above for
5059 @code{-gnatw.d}.
5061 @item -gnatwe
5062 @emph{Treat warnings and style checks as errors.}
5063 @cindex @option{-gnatwe} (@command{gcc})
5064 @cindex Warnings, treat as error
5065 This switch causes warning messages and style check messages to be
5066 treated as errors.
5067 The warning string still appears, but the warning messages are counted
5068 as errors, and prevent the generation of an object file. Note that this
5069 is the only -gnatw switch that affects the handling of style check messages.
5071 @item -gnatw.e
5072 @emph{Activate every optional warning}
5073 @cindex @option{-gnatw.e} (@command{gcc})
5074 @cindex Warnings, activate every optional warning
5075 This switch activates all optional warnings, including those which
5076 are not activated by @code{-gnatwa}. The use of this switch is not
5077 recommended for normal use. If you turn this switch on, it is almost
5078 certain that you will get large numbers of useless warnings. The
5079 warnings that are excluded from @code{-gnatwa} are typically highly
5080 specialized warnings that are suitable for use only in code that has
5081 been specifically designed according to specialized coding rules.
5083 @item -gnatwf
5084 @emph{Activate warnings on unreferenced formals.}
5085 @cindex @option{-gnatwf} (@command{gcc})
5086 @cindex Formals, unreferenced
5087 This switch causes a warning to be generated if a formal parameter
5088 is not referenced in the body of the subprogram. This warning can
5089 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5090 default is that these warnings are not generated.
5092 @item -gnatwF
5093 @emph{Suppress warnings on unreferenced formals.}
5094 @cindex @option{-gnatwF} (@command{gcc})
5095 This switch suppresses warnings for unreferenced formal
5096 parameters. Note that the
5097 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5098 effect of warning on unreferenced entities other than subprogram
5099 formals.
5101 @item -gnatwg
5102 @emph{Activate warnings on unrecognized pragmas.}
5103 @cindex @option{-gnatwg} (@command{gcc})
5104 @cindex Pragmas, unrecognized
5105 This switch causes a warning to be generated if an unrecognized
5106 pragma is encountered. Apart from issuing this warning, the
5107 pragma is ignored and has no effect. This warning can
5108 also be turned on using @option{-gnatwa}. The default
5109 is that such warnings are issued (satisfying the Ada Reference
5110 Manual requirement that such warnings appear).
5112 @item -gnatwG
5113 @emph{Suppress warnings on unrecognized pragmas.}
5114 @cindex @option{-gnatwG} (@command{gcc})
5115 This switch suppresses warnings for unrecognized pragmas.
5117 @item -gnatwh
5118 @emph{Activate warnings on hiding.}
5119 @cindex @option{-gnatwh} (@command{gcc})
5120 @cindex Hiding of Declarations
5121 This switch activates warnings on hiding declarations.
5122 A declaration is considered hiding
5123 if it is for a non-overloadable entity, and it declares an entity with the
5124 same name as some other entity that is directly or use-visible. The default
5125 is that such warnings are not generated.
5126 Note that @option{-gnatwa} does not affect the setting of this warning option.
5128 @item -gnatwH
5129 @emph{Suppress warnings on hiding.}
5130 @cindex @option{-gnatwH} (@command{gcc})
5131 This switch suppresses warnings on hiding declarations.
5133 @item -gnatw.h
5134 @emph{Activate warnings on holes/gaps in records.}
5135 @cindex @option{-gnatw.h} (@command{gcc})
5136 @cindex Record Representation (gaps)
5137 This switch activates warnings on component clauses in record
5138 representation clauses that leave holes (gaps) in the record layout.
5139 If this warning option is active, then record representation clauses
5140 should specify a contiguous layout, adding unused fill fields if needed.
5141 Note that @option{-gnatwa} does not affect the setting of this warning option.
5143 @item -gnatw.H
5144 @emph{Suppress warnings on holes/gaps in records.}
5145 @cindex @option{-gnatw.H} (@command{gcc})
5146 This switch suppresses warnings on component clauses in record
5147 representation clauses that leave holes (haps) in the record layout.
5149 @item -gnatwi
5150 @emph{Activate warnings on implementation units.}
5151 @cindex @option{-gnatwi} (@command{gcc})
5152 This switch activates warnings for a @code{with} of an internal GNAT
5153 implementation unit, defined as any unit from the @code{Ada},
5154 @code{Interfaces}, @code{GNAT},
5155 ^^@code{DEC},^ or @code{System}
5156 hierarchies that is not
5157 documented in either the Ada Reference Manual or the GNAT
5158 Programmer's Reference Manual. Such units are intended only
5159 for internal implementation purposes and should not be @code{with}'ed
5160 by user programs. The default is that such warnings are generated
5161 This warning can also be turned on using @option{-gnatwa}.
5163 @item -gnatwI
5164 @emph{Disable warnings on implementation units.}
5165 @cindex @option{-gnatwI} (@command{gcc})
5166 This switch disables warnings for a @code{with} of an internal GNAT
5167 implementation unit.
5169 @item -gnatw.i
5170 @emph{Activate warnings on overlapping actuals.}
5171 @cindex @option{-gnatw.i} (@command{gcc})
5172 This switch enables a warning on statically detectable overlapping actuals in
5173 a subprogram call, when one of the actuals is an in-out parameter, and the
5174 types of the actuals are not by-copy types. The warning is off by default,
5175 and is not included under -gnatwa.
5177 @item -gnatw.I
5178 @emph{Disable warnings on overlapping actuals.}
5179 @cindex @option{-gnatw.I} (@command{gcc})
5180 This switch disables warnings on overlapping actuals in a call..
5182 @item -gnatwj
5183 @emph{Activate warnings on obsolescent features (Annex J).}
5184 @cindex @option{-gnatwj} (@command{gcc})
5185 @cindex Features, obsolescent
5186 @cindex Obsolescent features
5187 If this warning option is activated, then warnings are generated for
5188 calls to subprograms marked with @code{pragma Obsolescent} and
5189 for use of features in Annex J of the Ada Reference Manual. In the
5190 case of Annex J, not all features are flagged. In particular use
5191 of the renamed packages (like @code{Text_IO}) and use of package
5192 @code{ASCII} are not flagged, since these are very common and
5193 would generate many annoying positive warnings. The default is that
5194 such warnings are not generated. This warning is also turned on by
5195 the use of @option{-gnatwa}.
5197 In addition to the above cases, warnings are also generated for
5198 GNAT features that have been provided in past versions but which
5199 have been superseded (typically by features in the new Ada standard).
5200 For example, @code{pragma Ravenscar} will be flagged since its
5201 function is replaced by @code{pragma Profile(Ravenscar)}, and
5202 @code{pragma Interface_Name} will be flagged since its function
5203 is replaced by @code{pragma Import}.
5205 Note that this warning option functions differently from the
5206 restriction @code{No_Obsolescent_Features} in two respects.
5207 First, the restriction applies only to annex J features.
5208 Second, the restriction does flag uses of package @code{ASCII}.
5210 @item -gnatwJ
5211 @emph{Suppress warnings on obsolescent features (Annex J).}
5212 @cindex @option{-gnatwJ} (@command{gcc})
5213 This switch disables warnings on use of obsolescent features.
5215 @item -gnatwk
5216 @emph{Activate warnings on variables that could be constants.}
5217 @cindex @option{-gnatwk} (@command{gcc})
5218 This switch activates warnings for variables that are initialized but
5219 never modified, and then could be declared constants. The default is that
5220 such warnings are not given.
5221 This warning can also be turned on using @option{-gnatwa}.
5223 @item -gnatwK
5224 @emph{Suppress warnings on variables that could be constants.}
5225 @cindex @option{-gnatwK} (@command{gcc})
5226 This switch disables warnings on variables that could be declared constants.
5228 @item -gnatw.k
5229 @emph{Activate warnings on redefinition of names in standard.}
5230 @cindex @option{-gnatw.k} (@command{gcc})
5231 This switch activates warnings for declarations that declare a name that
5232 is defined in package Standard. Such declarations can be confusing,
5233 especially since the names in package Standard continue to be directly
5234 visible, meaning that use visibiliy on such redeclared names does not
5235 work as expected. Names of discriminants and components in records are
5236 not included in this check.
5237 This warning is not part of the warnings activated by @option{-gnatwa}.
5238 It must be explicitly activated.
5240 @item -gnatw.K
5241 @emph{Suppress warnings on variables that could be constants.}
5242 @cindex @option{-gnatwK} (@command{gcc})
5243 This switch activates warnings for declarations that declare a name that
5244 is defined in package Standard.
5246 @item -gnatwl
5247 @emph{Activate warnings for elaboration pragmas.}
5248 @cindex @option{-gnatwl} (@command{gcc})
5249 @cindex Elaboration, warnings
5250 This switch activates warnings on missing
5251 @code{Elaborate_All} and @code{Elaborate} pragmas.
5252 See the section in this guide on elaboration checking for details on
5253 when such pragmas should be used. In dynamic elaboration mode, this switch
5254 generations warnings about the need to add elaboration pragmas. Note however,
5255 that if you blindly follow these warnings, and add @code{Elaborate_All}
5256 warnings wherever they are recommended, you basically end up with the
5257 equivalent of the static elaboration model, which may not be what you want for
5258 legacy code for which the static model does not work.
5260 For the static model, the messages generated are labeled "info:" (for
5261 information messages). They are not warnings to add elaboration pragmas,
5262 merely informational messages showing what implicit elaboration pragmas
5263 have been added, for use in analyzing elaboration circularity problems.
5265 Warnings are also generated if you
5266 are using the static mode of elaboration, and a @code{pragma Elaborate}
5267 is encountered. The default is that such warnings
5268 are not generated.
5269 This warning is not automatically turned on by the use of @option{-gnatwa}.
5271 @item -gnatwL
5272 @emph{Suppress warnings for elaboration pragmas.}
5273 @cindex @option{-gnatwL} (@command{gcc})
5274 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5275 See the section in this guide on elaboration checking for details on
5276 when such pragmas should be used.
5278 @item -gnatw.l
5279 @emph{List inherited aspects.}
5280 @cindex @option{-gnatw.l} (@command{gcc})
5281 This switch causes the compiler to list inherited invariants,
5282 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5283 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5284 These messages are not automatically turned on by the use of @option{-gnatwa}.
5286 @item -gnatw.L
5287 @emph{Suppress listing of inherited aspects.}
5288 @cindex @option{-gnatw.L} (@command{gcc})
5289 This switch suppresses listing of inherited aspects.
5291 @item -gnatwm
5292 @emph{Activate warnings on modified but unreferenced variables.}
5293 @cindex @option{-gnatwm} (@command{gcc})
5294 This switch activates warnings for variables that are assigned (using
5295 an initialization value or with one or more assignment statements) but
5296 whose value is never read. The warning is suppressed for volatile
5297 variables and also for variables that are renamings of other variables
5298 or for which an address clause is given.
5299 This warning can also be turned on using @option{-gnatwa}.
5300 The default is that these warnings are not given.
5302 @item -gnatwM
5303 @emph{Disable warnings on modified but unreferenced variables.}
5304 @cindex @option{-gnatwM} (@command{gcc})
5305 This switch disables warnings for variables that are assigned or
5306 initialized, but never read.
5308 @item -gnatw.m
5309 @emph{Activate warnings on suspicious modulus values.}
5310 @cindex @option{-gnatw.m} (@command{gcc})
5311 This switch activates warnings for modulus values that seem suspicious.
5312 The cases caught are where the size is the same as the modulus (e.g.
5313 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5314 with no size clause. The guess in both cases is that 2**x was intended
5315 rather than x. In addition expressions of the form 2*x for small x
5316 generate a warning (the almost certainly accurate guess being that
5317 2**x was intended). The default is that these warnings are given.
5319 @item -gnatw.M
5320 @emph{Disable warnings on suspicious modulus values.}
5321 @cindex @option{-gnatw.M} (@command{gcc})
5322 This switch disables warnings for suspicious modulus values.
5324 @item -gnatwn
5325 @emph{Set normal warnings mode.}
5326 @cindex @option{-gnatwn} (@command{gcc})
5327 This switch sets normal warning mode, in which enabled warnings are
5328 issued and treated as warnings rather than errors. This is the default
5329 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5330 an explicit @option{-gnatws} or
5331 @option{-gnatwe}. It also cancels the effect of the
5332 implicit @option{-gnatwe} that is activated by the
5333 use of @option{-gnatg}.
5335 @item -gnatwo
5336 @emph{Activate warnings on address clause overlays.}
5337 @cindex @option{-gnatwo} (@command{gcc})
5338 @cindex Address Clauses, warnings
5339 This switch activates warnings for possibly unintended initialization
5340 effects of defining address clauses that cause one variable to overlap
5341 another. The default is that such warnings are generated.
5342 This warning can also be turned on using @option{-gnatwa}.
5344 @item -gnatwO
5345 @emph{Suppress warnings on address clause overlays.}
5346 @cindex @option{-gnatwO} (@command{gcc})
5347 This switch suppresses warnings on possibly unintended initialization
5348 effects of defining address clauses that cause one variable to overlap
5349 another.
5351 @item -gnatw.o
5352 @emph{Activate warnings on modified but unreferenced out parameters.}
5353 @cindex @option{-gnatw.o} (@command{gcc})
5354 This switch activates warnings for variables that are modified by using
5355 them as actuals for a call to a procedure with an out mode formal, where
5356 the resulting assigned value is never read. It is applicable in the case
5357 where there is more than one out mode formal. If there is only one out
5358 mode formal, the warning is issued by default (controlled by -gnatwu).
5359 The warning is suppressed for volatile
5360 variables and also for variables that are renamings of other variables
5361 or for which an address clause is given.
5362 The default is that these warnings are not given. Note that this warning
5363 is not included in -gnatwa, it must be activated explicitly.
5365 @item -gnatw.O
5366 @emph{Disable warnings on modified but unreferenced out parameters.}
5367 @cindex @option{-gnatw.O} (@command{gcc})
5368 This switch suppresses warnings for variables that are modified by using
5369 them as actuals for a call to a procedure with an out mode formal, where
5370 the resulting assigned value is never read.
5372 @item -gnatwp
5373 @emph{Activate warnings on ineffective pragma Inlines.}
5374 @cindex @option{-gnatwp} (@command{gcc})
5375 @cindex Inlining, warnings
5376 This switch activates warnings for failure of front end inlining
5377 (activated by @option{-gnatN}) to inline a particular call. There are
5378 many reasons for not being able to inline a call, including most
5379 commonly that the call is too complex to inline. The default is
5380 that such warnings are not given.
5381 This warning can also be turned on using @option{-gnatwa}.
5382 Warnings on ineffective inlining by the gcc back-end can be activated
5383 separately, using the gcc switch -Winline.
5385 @item -gnatwP
5386 @emph{Suppress warnings on ineffective pragma Inlines.}
5387 @cindex @option{-gnatwP} (@command{gcc})
5388 This switch suppresses warnings on ineffective pragma Inlines. If the
5389 inlining mechanism cannot inline a call, it will simply ignore the
5390 request silently.
5392 @item -gnatw.p
5393 @emph{Activate warnings on parameter ordering.}
5394 @cindex @option{-gnatw.p} (@command{gcc})
5395 @cindex Parameter order, warnings
5396 This switch activates warnings for cases of suspicious parameter
5397 ordering when the list of arguments are all simple identifiers that
5398 match the names of the formals, but are in a different order. The
5399 warning is suppressed if any use of named parameter notation is used,
5400 so this is the appropriate way to suppress a false positive (and
5401 serves to emphasize that the "misordering" is deliberate). The
5402 default is
5403 that such warnings are not given.
5404 This warning can also be turned on using @option{-gnatwa}.
5406 @item -gnatw.P
5407 @emph{Suppress warnings on parameter ordering.}
5408 @cindex @option{-gnatw.P} (@command{gcc})
5409 This switch suppresses warnings on cases of suspicious parameter
5410 ordering.
5412 @item -gnatwq
5413 @emph{Activate warnings on questionable missing parentheses.}
5414 @cindex @option{-gnatwq} (@command{gcc})
5415 @cindex Parentheses, warnings
5416 This switch activates warnings for cases where parentheses are not used and
5417 the result is potential ambiguity from a readers point of view. For example
5418 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5419 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5420 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5421 follow the rule of always parenthesizing to make the association clear, and
5422 this warning switch warns if such parentheses are not present. The default
5423 is that these warnings are given.
5424 This warning can also be turned on using @option{-gnatwa}.
5426 @item -gnatwQ
5427 @emph{Suppress warnings on questionable missing parentheses.}
5428 @cindex @option{-gnatwQ} (@command{gcc})
5429 This switch suppresses warnings for cases where the association is not
5430 clear and the use of parentheses is preferred.
5432 @item -gnatwr
5433 @emph{Activate warnings on redundant constructs.}
5434 @cindex @option{-gnatwr} (@command{gcc})
5435 This switch activates warnings for redundant constructs. The following
5436 is the current list of constructs regarded as redundant:
5438 @itemize @bullet
5439 @item
5440 Assignment of an item to itself.
5441 @item
5442 Type conversion that converts an expression to its own type.
5443 @item
5444 Use of the attribute @code{Base} where @code{typ'Base} is the same
5445 as @code{typ}.
5446 @item
5447 Use of pragma @code{Pack} when all components are placed by a record
5448 representation clause.
5449 @item
5450 Exception handler containing only a reraise statement (raise with no
5451 operand) which has no effect.
5452 @item
5453 Use of the operator abs on an operand that is known at compile time
5454 to be non-negative
5455 @item
5456 Comparison of boolean expressions to an explicit True value.
5457 @end itemize
5459 This warning can also be turned on using @option{-gnatwa}.
5460 The default is that warnings for redundant constructs are not given.
5462 @item -gnatwR
5463 @emph{Suppress warnings on redundant constructs.}
5464 @cindex @option{-gnatwR} (@command{gcc})
5465 This switch suppresses warnings for redundant constructs.
5467 @item -gnatw.r
5468 @emph{Activate warnings for object renaming function.}
5469 @cindex @option{-gnatw.r} (@command{gcc})
5470 This switch activates warnings for an object renaming that renames a
5471 function call, which is equivalent to a constant declaration (as
5472 opposed to renaming the function itself).  The default is that these
5473 warnings are given.  This warning can also be turned on using
5474 @option{-gnatwa}.
5476 @item -gnatw.R
5477 @emph{Suppress warnings for object renaming function.}
5478 @cindex @option{-gnatwT} (@command{gcc})
5479 This switch suppresses warnings for object renaming function.
5481 @item -gnatws
5482 @emph{Suppress all warnings.}
5483 @cindex @option{-gnatws} (@command{gcc})
5484 This switch completely suppresses the
5485 output of all warning messages from the GNAT front end, including
5486 both warnings that can be controlled by switches described in this
5487 section, and those that are normally given unconditionally. The
5488 effect of this suppress action can only be cancelled by a subsequent
5489 use of the switch @option{-gnatwn}.
5491 Note that switch @option{-gnatws} does not suppress
5492 warnings from the @command{gcc} back end.
5493 To suppress these back end warnings as well, use the switch @option{-w}
5494 in addition to @option{-gnatws}. Also this switch has no effect on the
5495 handling of style check messages.
5497 @item -gnatw.s
5498 @emph{Activate warnings on overridden size clauses.}
5499 @cindex @option{-gnatw.s} (@command{gcc})
5500 @cindex Record Representation (component sizes)
5501 This switch activates warnings on component clauses in record
5502 representation clauses where the length given overrides that
5503 specified by an explicit size clause for the component type. A
5504 warning is similarly given in the array case if a specified
5505 component size overrides an explicit size clause for the array
5506 component type.
5507 Note that @option{-gnatwa} does not affect the setting of this warning option.
5509 @item -gnatw.S
5510 @emph{Suppress warnings on overridden size clauses.}
5511 @cindex @option{-gnatw.S} (@command{gcc})
5512 This switch suppresses warnings on component clauses in record
5513 representation clauses that override size clauses, and similar
5514 warnings when an array component size overrides a size clause.
5516 @item -gnatwt
5517 @emph{Activate warnings for tracking of deleted conditional code.}
5518 @cindex @option{-gnatwt} (@command{gcc})
5519 @cindex Deactivated code, warnings
5520 @cindex Deleted code, warnings
5521 This switch activates warnings for tracking of code in conditionals (IF and
5522 CASE statements) that is detected to be dead code which cannot be executed, and
5523 which is removed by the front end. This warning is off by default, and is not
5524 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5525 useful for detecting deactivated code in certified applications.
5527 @item -gnatwT
5528 @emph{Suppress warnings for tracking of deleted conditional code.}
5529 @cindex @option{-gnatwT} (@command{gcc})
5530 This switch suppresses warnings for tracking of deleted conditional code.
5532 @item -gnatw.t
5533 @emph{Activate warnings on suspicious contracts.}
5534 @cindex @option{-gnatw.t} (@command{gcc})
5535 This switch activates warnings on suspicious postconditions (whether a
5536 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5537 and suspicious contract cases (pragma @code{Contract_Cases}). A
5538 function postcondition or contract case is suspicious when no postcondition
5539 or contract case for this function mentions the result of the function.
5540 A procedure postcondition or contract case is suspicious when it only
5541 refers to the pre-state of the procedure, because in that case it should
5542 rather be expressed as a precondition. The default is that such warnings
5543 are not generated. This warning can also be turned on using @option{-gnatwa}.
5545 @item -gnatw.T
5546 @emph{Suppress warnings on suspicious contracts.}
5547 @cindex @option{-gnatw.T} (@command{gcc})
5548 This switch suppresses warnings on suspicious postconditions.
5550 @item -gnatwu
5551 @emph{Activate warnings on unused entities.}
5552 @cindex @option{-gnatwu} (@command{gcc})
5553 This switch activates warnings to be generated for entities that
5554 are declared but not referenced, and for units that are @code{with}'ed
5555 and not
5556 referenced. In the case of packages, a warning is also generated if
5557 no entities in the package are referenced. This means that if a with'ed
5558 package is referenced but the only references are in @code{use}
5559 clauses or @code{renames}
5560 declarations, a warning is still generated. A warning is also generated
5561 for a generic package that is @code{with}'ed but never instantiated.
5562 In the case where a package or subprogram body is compiled, and there
5563 is a @code{with} on the corresponding spec
5564 that is only referenced in the body,
5565 a warning is also generated, noting that the
5566 @code{with} can be moved to the body. The default is that
5567 such warnings are not generated.
5568 This switch also activates warnings on unreferenced formals
5569 (it includes the effect of @option{-gnatwf}).
5570 This warning can also be turned on using @option{-gnatwa}.
5572 @item -gnatwU
5573 @emph{Suppress warnings on unused entities.}
5574 @cindex @option{-gnatwU} (@command{gcc})
5575 This switch suppresses warnings for unused entities and packages.
5576 It also turns off warnings on unreferenced formals (and thus includes
5577 the effect of @option{-gnatwF}).
5579 @item -gnatw.u
5580 @emph{Activate warnings on unordered enumeration types.}
5581 @cindex @option{-gnatw.u} (@command{gcc})
5582 This switch causes enumeration types to be considered as conceptually
5583 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5584 The effect is to generate warnings in clients that use explicit comparisons
5585 or subranges, since these constructs both treat objects of the type as
5586 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5587 which the type is declared, or its body or subunits.) Please refer to
5588 the description of pragma @code{Ordered} in the
5589 @cite{@value{EDITION} Reference Manual} for further details.
5590 The default is that such warnings are not generated.
5591 This warning is not automatically turned on by the use of @option{-gnatwa}.
5593 @item -gnatw.U
5594 @emph{Deactivate warnings on unordered enumeration types.}
5595 @cindex @option{-gnatw.U} (@command{gcc})
5596 This switch causes all enumeration types to be considered as ordered, so
5597 that no warnings are given for comparisons or subranges for any type.
5599 @item -gnatwv
5600 @emph{Activate warnings on unassigned variables.}
5601 @cindex @option{-gnatwv} (@command{gcc})
5602 @cindex Unassigned variable warnings
5603 This switch activates warnings for access to variables which
5604 may not be properly initialized. The default is that
5605 such warnings are generated.
5606 This warning can also be turned on using @option{-gnatwa}.
5608 @item -gnatwV
5609 @emph{Suppress warnings on unassigned variables.}
5610 @cindex @option{-gnatwV} (@command{gcc})
5611 This switch suppresses warnings for access to variables which
5612 may not be properly initialized.
5613 For variables of a composite type, the warning can also be suppressed in
5614 Ada 2005 by using a default initialization with a box. For example, if
5615 Table is an array of records whose components are only partially uninitialized,
5616 then the following code:
5618 @smallexample @c ada
5619    Tab : Table := (others => <>);
5620 @end smallexample
5622 will suppress warnings on subsequent statements that access components
5623 of variable Tab.
5625 @item -gnatw.v
5626 @emph{Activate info messages for non-default bit order.}
5627 @cindex @option{-gnatw.v} (@command{gcc})
5628 @cindex bit order warnings
5629 This switch activates messages (labeled "info", they are not warnings,
5630 just informational messages) about the effects of non-default bit-order
5631 on records to which a component clause is applied. The effect of specifying
5632 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5633 these messages, which are given by default, are useful in understanding the
5634 exact consequences of using this feature. These messages
5635 can also be turned on using @option{-gnatwa}
5637 @item -gnatw.V
5638 @emph{Suppress info messages for non-default bit order.}
5639 @cindex @option{-gnatw.V} (@command{gcc})
5640 This switch suppresses information messages for the effects of specifying
5641 non-default bit order on record components with component clauses.
5643 @item -gnatww
5644 @emph{Activate warnings on wrong low bound assumption.}
5645 @cindex @option{-gnatww} (@command{gcc})
5646 @cindex String indexing warnings
5647 This switch activates warnings for indexing an unconstrained string parameter
5648 with a literal or S'Length. This is a case where the code is assuming that the
5649 low bound is one, which is in general not true (for example when a slice is
5650 passed). The default is that such warnings are generated.
5651 This warning can also be turned on using @option{-gnatwa}.
5653 @item -gnatwW
5654 @emph{Suppress warnings on wrong low bound assumption.}
5655 @cindex @option{-gnatwW} (@command{gcc})
5656 This switch suppresses warnings for indexing an unconstrained string parameter
5657 with a literal or S'Length. Note that this warning can also be suppressed
5658 in a particular case by adding an
5659 assertion that the lower bound is 1,
5660 as shown in the following example.
5662 @smallexample @c ada
5663    procedure K (S : String) is
5664       pragma Assert (S'First = 1);
5665       @dots{}
5666 @end smallexample
5668 @item -gnatw.w
5669 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5670 @cindex @option{-gnatw.w} (@command{gcc})
5671 @cindex Warnings Off control
5672 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5673 where either the pragma is entirely useless (because it suppresses no
5674 warnings), or it could be replaced by @code{pragma Unreferenced} or
5675 @code{pragma Unmodified}. The default is that these warnings are not given.
5676 Note that this warning is not included in -gnatwa, it must be
5677 activated explicitly.
5679 @item -gnatw.W
5680 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5681 @cindex @option{-gnatw.W} (@command{gcc})
5682 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5684 @item -gnatwx
5685 @emph{Activate warnings on Export/Import pragmas.}
5686 @cindex @option{-gnatwx} (@command{gcc})
5687 @cindex Export/Import pragma warnings
5688 This switch activates warnings on Export/Import pragmas when
5689 the compiler detects a possible conflict between the Ada and
5690 foreign language calling sequences. For example, the use of
5691 default parameters in a convention C procedure is dubious
5692 because the C compiler cannot supply the proper default, so
5693 a warning is issued. The default is that such warnings are
5694 generated.
5695 This warning can also be turned on using @option{-gnatwa}.
5697 @item -gnatwX
5698 @emph{Suppress warnings on Export/Import pragmas.}
5699 @cindex @option{-gnatwX} (@command{gcc})
5700 This switch suppresses warnings on Export/Import pragmas.
5701 The sense of this is that you are telling the compiler that
5702 you know what you are doing in writing the pragma, and it
5703 should not complain at you.
5705 @item -gnatw.x
5706 @emph{Activate warnings for No_Exception_Propagation mode.}
5707 @cindex @option{-gnatwm} (@command{gcc})
5708 This switch activates warnings for exception usage when pragma Restrictions
5709 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5710 explicit exception raises which are not covered by a local handler, and for
5711 exception handlers which do not cover a local raise. The default is that these
5712 warnings are not given.
5714 @item -gnatw.X
5715 @emph{Disable warnings for No_Exception_Propagation mode.}
5716 This switch disables warnings for exception usage when pragma Restrictions
5717 (No_Exception_Propagation) is in effect.
5719 @item -gnatwy
5720 @emph{Activate warnings for Ada compatibility issues.}
5721 @cindex @option{-gnatwy} (@command{gcc})
5722 @cindex Ada compatibility issues warnings
5723 For the most part, newer versions of Ada are upwards compatible
5724 with older versions. For example, Ada 2005 programs will almost
5725 always work when compiled as Ada 2012.
5726 However there are some exceptions (for example the fact that
5727 @code{some} is now a reserved word in Ada 2012). This
5728 switch activates several warnings to help in identifying
5729 and correcting such incompatibilities. The default is that
5730 these warnings are generated. Note that at one point Ada 2005
5731 was called Ada 0Y, hence the choice of character.
5732 This warning can also be turned on using @option{-gnatwa}.
5734 @item -gnatwY
5735 @emph{Disable warnings for Ada compatibility issues.}
5736 @cindex @option{-gnatwY} (@command{gcc})
5737 @cindex Ada compatibility issues warnings
5738 This switch suppresses the warnings intended to help in identifying
5739 incompatibilities between Ada language versions.
5741 @item -gnatw.y
5742 @emph{Activate information messages for why package spec needs body}
5743 @cindex @option{-gnatw.y} (@command{gcc})
5744 @cindex Package spec needing body
5745 There are a number of cases in which a package spec needs a body.
5746 For example, the use of pragma Elaborate_Body, or the declaration
5747 of a procedure specification requiring a completion. This switch
5748 causes information messages to be output showing why a package
5749 specification requires a body. This can be useful in the case of
5750 a large package specification which is unexpectedly requiring a
5751 body. The default is that such information messages are not output.
5753 @item -gnatw.Y
5754 @emph{Disable information messages for why package spec needs body}
5755 @cindex @option{-gnatw.Y} (@command{gcc})
5756 @cindex No information messages for why package spec needs body
5757 This switch suppresses the output of information messages showing why
5758 a package specification needs a body.
5760 @item -gnatwz
5761 @emph{Activate warnings on unchecked conversions.}
5762 @cindex @option{-gnatwz} (@command{gcc})
5763 @cindex Unchecked_Conversion warnings
5764 This switch activates warnings for unchecked conversions
5765 where the types are known at compile time to have different
5766 sizes. The default
5767 is that such warnings are generated. Warnings are also
5768 generated for subprogram pointers with different conventions,
5769 and, on VMS only, for data pointers with different conventions.
5770 This warning can also be turned on using @option{-gnatwa}.
5772 @item -gnatwZ
5773 @emph{Suppress warnings on unchecked conversions.}
5774 @cindex @option{-gnatwZ} (@command{gcc})
5775 This switch suppresses warnings for unchecked conversions
5776 where the types are known at compile time to have different
5777 sizes or conventions.
5779 @item ^-Wunused^WARNINGS=UNUSED^
5780 @cindex @option{-Wunused}
5781 The warnings controlled by the @option{-gnatw} switch are generated by
5782 the front end of the compiler. The @option{GCC} back end can provide
5783 additional warnings and they are controlled by the @option{-W} switch.
5784 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5785 warnings for entities that are declared but not referenced.
5787 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5788 @cindex @option{-Wuninitialized}
5789 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5790 the back end warning for uninitialized variables. This switch must be
5791 used in conjunction with an optimization level greater than zero.
5793 @item -Wstack-usage=@var{len}
5794 @cindex @option{-Wstack-usage}
5795 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5796 See @ref{Static Stack Usage Analysis} for details.
5798 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5799 @cindex @option{-Wall}
5800 This switch enables most warnings from the @option{GCC} back end.
5801 The code generator detects a number of warning situations that are missed
5802 by the @option{GNAT} front end, and this switch can be used to activate them.
5803 The use of this switch also sets the default front end warning mode to
5804 @option{-gnatwa}, that is, most front end warnings activated as well.
5806 @item ^-w^/NO_BACK_END_WARNINGS^
5807 @cindex @option{-w}
5808 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5809 The use of this switch also sets the default front end warning mode to
5810 @option{-gnatws}, that is, front end warnings suppressed as well.
5812 @end table
5814 @noindent
5815 @ifclear vms
5816 A string of warning parameters can be used in the same parameter. For example:
5818 @smallexample
5819 -gnatwaGe
5820 @end smallexample
5822 @noindent
5823 will turn on all optional warnings except for unrecognized pragma warnings,
5824 and also specify that warnings should be treated as errors.
5825 @end ifclear
5827 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5829 @table @option
5830 @c !sort!
5831 @item -gnatw.a
5832 @item -gnatwB
5833 @item -gnatw.b
5834 @item -gnatwC
5835 @item -gnatw.C
5836 @item -gnatwD
5837 @item -gnatwF
5838 @item -gnatwg
5839 @item -gnatwH
5840 @item -gnatwi
5841 @item -gnatw.I
5842 @item -gnatwJ
5843 @item -gnatwK
5844 @item -gnatwL
5845 @item -gnatw.L
5846 @item -gnatwM
5847 @item -gnatw.m
5848 @item -gnatwn
5849 @item -gnatwo
5850 @item -gnatw.O
5851 @item -gnatwP
5852 @item -gnatw.P
5853 @item -gnatwq
5854 @item -gnatwR
5855 @item -gnatw.R
5856 @item -gnatw.S
5857 @item -gnatwT
5858 @item -gnatw.T
5859 @item -gnatwU
5860 @item -gnatwv
5861 @item -gnatww
5862 @item -gnatw.W
5863 @item -gnatwx
5864 @item -gnatw.X
5865 @item -gnatwy
5866 @item -gnatwz
5868 @end table
5870 @node Debugging and Assertion Control
5871 @subsection Debugging and Assertion Control
5873 @table @option
5874 @item -gnata
5875 @cindex @option{-gnata} (@command{gcc})
5876 @findex Assert
5877 @findex Debug
5878 @cindex Assertions
5880 @noindent
5881 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5882 are ignored. This switch, where @samp{a} stands for assert, causes
5883 @code{Assert} and @code{Debug} pragmas to be activated.
5885 The pragmas have the form:
5887 @smallexample
5888 @cartouche
5889    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5890                       @var{static-string-expression}@r{]})
5891    @b{pragma} Debug (@var{procedure call})
5892 @end cartouche
5893 @end smallexample
5895 @noindent
5896 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5897 If the result is @code{True}, the pragma has no effect (other than
5898 possible side effects from evaluating the expression). If the result is
5899 @code{False}, the exception @code{Assert_Failure} declared in the package
5900 @code{System.Assertions} is
5901 raised (passing @var{static-string-expression}, if present, as the
5902 message associated with the exception). If no string expression is
5903 given the default is a string giving the file name and line number
5904 of the pragma.
5906 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5907 @code{pragma Debug} may appear within a declaration sequence, allowing
5908 debugging procedures to be called between declarations.
5910 @ifset vms
5911 @item /DEBUG@r{[}=debug-level@r{]}
5912 @itemx  /NODEBUG
5913 Specifies how much debugging information is to be included in
5914 the resulting object file where 'debug-level' is one of the following:
5915 @table @code
5916 @item   TRACEBACK
5917 Include both debugger symbol records and traceback
5918 the object file.
5919 This is the default setting.
5920 @item   ALL
5921 Include both debugger symbol records and traceback in
5922 object file.
5923 @item   NONE
5924 Excludes both debugger symbol records and traceback
5925 the object file. Same as /NODEBUG.
5926 @item   SYMBOLS
5927 Includes only debugger symbol records in the object
5928 file. Note that this doesn't include traceback information.
5929 @end table
5930 @end ifset
5931 @end table
5933 @node Validity Checking
5934 @subsection Validity Checking
5935 @findex Validity Checking
5937 @noindent
5938 The Ada Reference Manual defines the concept of invalid values (see
5939 RM 13.9.1). The primary source of invalid values is uninitialized
5940 variables. A scalar variable that is left uninitialized may contain
5941 an invalid value; the concept of invalid does not apply to access or
5942 composite types.
5944 It is an error to read an invalid value, but the RM does not require
5945 run-time checks to detect such errors, except for some minimal
5946 checking to prevent erroneous execution (i.e. unpredictable
5947 behavior). This corresponds to the @option{-gnatVd} switch below,
5948 which is the default. For example, by default, if the expression of a
5949 case statement is invalid, it will raise Constraint_Error rather than
5950 causing a wild jump, and if an array index on the left-hand side of an
5951 assignment is invalid, it will raise Constraint_Error rather than
5952 overwriting an arbitrary memory location.
5954 The @option{-gnatVa} may be used to enable additional validity checks,
5955 which are not required by the RM. These checks are often very
5956 expensive (which is why the RM does not require them). These checks
5957 are useful in tracking down uninitialized variables, but they are
5958 not usually recommended for production builds.
5960 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5961 control; you can enable whichever validity checks you desire. However,
5962 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5963 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5964 sufficient for non-debugging use.
5966 The @option{-gnatB} switch tells the compiler to assume that all
5967 values are valid (that is, within their declared subtype range)
5968 except in the context of a use of the Valid attribute. This means
5969 the compiler can generate more efficient code, since the range
5970 of values is better known at compile time. However, an uninitialized
5971 variable can cause wild jumps and memory corruption in this mode.
5973 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5974 checking mode as described below.
5975 @ifclear vms
5976 The @code{x} argument is a string of letters that
5977 indicate validity checks that are performed or not performed in addition
5978 to the default checks required by Ada as described above.
5979 @end ifclear
5980 @ifset vms
5981 The options allowed for this qualifier
5982 indicate validity checks that are performed or not performed in addition
5983 to the default checks required by Ada as described above.
5984 @end ifset
5986 @table @option
5987 @c !sort!
5988 @item -gnatVa
5989 @emph{All validity checks.}
5990 @cindex @option{-gnatVa} (@command{gcc})
5991 All validity checks are turned on.
5992 @ifclear vms
5993 That is, @option{-gnatVa} is
5994 equivalent to @option{gnatVcdfimorst}.
5995 @end ifclear
5997 @item -gnatVc
5998 @emph{Validity checks for copies.}
5999 @cindex @option{-gnatVc} (@command{gcc})
6000 The right hand side of assignments, and the initializing values of
6001 object declarations are validity checked.
6003 @item -gnatVd
6004 @emph{Default (RM) validity checks.}
6005 @cindex @option{-gnatVd} (@command{gcc})
6006 Some validity checks are done by default following normal Ada semantics
6007 (RM 13.9.1 (9-11)).
6008 A check is done in case statements that the expression is within the range
6009 of the subtype. If it is not, Constraint_Error is raised.
6010 For assignments to array components, a check is done that the expression used
6011 as index is within the range. If it is not, Constraint_Error is raised.
6012 Both these validity checks may be turned off using switch @option{-gnatVD}.
6013 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6014 switch @option{-gnatVd} will leave the checks turned on.
6015 Switch @option{-gnatVD} should be used only if you are sure that all such
6016 expressions have valid values. If you use this switch and invalid values
6017 are present, then the program is erroneous, and wild jumps or memory
6018 overwriting may occur.
6020 @item -gnatVe
6021 @emph{Validity checks for elementary components.}
6022 @cindex @option{-gnatVe} (@command{gcc})
6023 In the absence of this switch, assignments to record or array components are
6024 not validity checked, even if validity checks for assignments generally
6025 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6026 require valid data, but assignment of individual components does. So for
6027 example, there is a difference between copying the elements of an array with a
6028 slice assignment, compared to assigning element by element in a loop. This
6029 switch allows you to turn off validity checking for components, even when they
6030 are assigned component by component.
6032 @item -gnatVf
6033 @emph{Validity checks for floating-point values.}
6034 @cindex @option{-gnatVf} (@command{gcc})
6035 In the absence of this switch, validity checking occurs only for discrete
6036 values. If @option{-gnatVf} is specified, then validity checking also applies
6037 for floating-point values, and NaNs and infinities are considered invalid,
6038 as well as out of range values for constrained types. Note that this means
6039 that standard IEEE infinity mode is not allowed. The exact contexts
6040 in which floating-point values are checked depends on the setting of other
6041 options. For example,
6042 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6043 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6044 (the order does not matter) specifies that floating-point parameters of mode
6045 @code{in} should be validity checked.
6047 @item -gnatVi
6048 @emph{Validity checks for @code{in} mode parameters}
6049 @cindex @option{-gnatVi} (@command{gcc})
6050 Arguments for parameters of mode @code{in} are validity checked in function
6051 and procedure calls at the point of call.
6053 @item -gnatVm
6054 @emph{Validity checks for @code{in out} mode parameters.}
6055 @cindex @option{-gnatVm} (@command{gcc})
6056 Arguments for parameters of mode @code{in out} are validity checked in
6057 procedure calls at the point of call. The @code{'m'} here stands for
6058 modify, since this concerns parameters that can be modified by the call.
6059 Note that there is no specific option to test @code{out} parameters,
6060 but any reference within the subprogram will be tested in the usual
6061 manner, and if an invalid value is copied back, any reference to it
6062 will be subject to validity checking.
6064 @item -gnatVn
6065 @emph{No validity checks.}
6066 @cindex @option{-gnatVn} (@command{gcc})
6067 This switch turns off all validity checking, including the default checking
6068 for case statements and left hand side subscripts. Note that the use of
6069 the switch @option{-gnatp} suppresses all run-time checks, including
6070 validity checks, and thus implies @option{-gnatVn}. When this switch
6071 is used, it cancels any other @option{-gnatV} previously issued.
6073 @item -gnatVo
6074 @emph{Validity checks for operator and attribute operands.}
6075 @cindex @option{-gnatVo} (@command{gcc})
6076 Arguments for predefined operators and attributes are validity checked.
6077 This includes all operators in package @code{Standard},
6078 the shift operators defined as intrinsic in package @code{Interfaces}
6079 and operands for attributes such as @code{Pos}. Checks are also made
6080 on individual component values for composite comparisons, and on the
6081 expressions in type conversions and qualified expressions. Checks are
6082 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6084 @item -gnatVp
6085 @emph{Validity checks for parameters.}
6086 @cindex @option{-gnatVp} (@command{gcc})
6087 This controls the treatment of parameters within a subprogram (as opposed
6088 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6089 of parameters on a call. If either of these call options is used, then
6090 normally an assumption is made within a subprogram that the input arguments
6091 have been validity checking at the point of call, and do not need checking
6092 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6093 is not made, and parameters are not assumed to be valid, so their validity
6094 will be checked (or rechecked) within the subprogram.
6096 @item -gnatVr
6097 @emph{Validity checks for function returns.}
6098 @cindex @option{-gnatVr} (@command{gcc})
6099 The expression in @code{return} statements in functions is validity
6100 checked.
6102 @item -gnatVs
6103 @emph{Validity checks for subscripts.}
6104 @cindex @option{-gnatVs} (@command{gcc})
6105 All subscripts expressions are checked for validity, whether they appear
6106 on the right side or left side (in default mode only left side subscripts
6107 are validity checked).
6109 @item -gnatVt
6110 @emph{Validity checks for tests.}
6111 @cindex @option{-gnatVt} (@command{gcc})
6112 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6113 statements are checked, as well as guard expressions in entry calls.
6115 @end table
6117 @noindent
6118 The @option{-gnatV} switch may be followed by
6119 ^a string of letters^a list of options^
6120 to turn on a series of validity checking options.
6121 For example,
6122 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6123 specifies that in addition to the default validity checking, copies and
6124 function return expressions are to be validity checked.
6125 In order to make it easier
6126 to specify the desired combination of effects,
6127 @ifclear vms
6128 the upper case letters @code{CDFIMORST} may
6129 be used to turn off the corresponding lower case option.
6130 @end ifclear
6131 @ifset vms
6132 the prefix @code{NO} on an option turns off the corresponding validity
6133 checking:
6134 @itemize @bullet
6135 @item @code{NOCOPIES}
6136 @item @code{NODEFAULT}
6137 @item @code{NOFLOATS}
6138 @item @code{NOIN_PARAMS}
6139 @item @code{NOMOD_PARAMS}
6140 @item @code{NOOPERANDS}
6141 @item @code{NORETURNS}
6142 @item @code{NOSUBSCRIPTS}
6143 @item @code{NOTESTS}
6144 @end itemize
6145 @end ifset
6146 Thus
6147 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6148 turns on all validity checking options except for
6149 checking of @code{@b{in out}} procedure arguments.
6151 The specification of additional validity checking generates extra code (and
6152 in the case of @option{-gnatVa} the code expansion can be substantial).
6153 However, these additional checks can be very useful in detecting
6154 uninitialized variables, incorrect use of unchecked conversion, and other
6155 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6156 is useful in conjunction with the extra validity checking, since this
6157 ensures that wherever possible uninitialized variables have invalid values.
6159 See also the pragma @code{Validity_Checks} which allows modification of
6160 the validity checking mode at the program source level, and also allows for
6161 temporary disabling of validity checks.
6163 @node Style Checking
6164 @subsection Style Checking
6165 @findex Style checking
6167 @noindent
6168 The @option{-gnaty^x^(option,option,@dots{})^} switch
6169 @cindex @option{-gnaty} (@command{gcc})
6170 causes the compiler to
6171 enforce specified style rules. A limited set of style rules has been used
6172 in writing the GNAT sources themselves. This switch allows user programs
6173 to activate all or some of these checks. If the source program fails a
6174 specified style check, an appropriate message is given, preceded by
6175 the character sequence ``(style)''. This message does not prevent
6176 successful compilation (unless the @option{-gnatwe} switch is used).
6178 Note that this is by no means intended to be a general facility for
6179 checking arbitrary coding standards. It is simply an embedding of the
6180 style rules we have chosen for the GNAT sources. If you are starting
6181 a project which does not have established style standards, you may
6182 find it useful to adopt the entire set of GNAT coding standards, or
6183 some subset of them. If you already have an established set of coding
6184 standards, then it may be that selected style checking options do
6185 indeed correspond to choices you have made, but for general checking
6186 of an existing set of coding rules, you should look to the gnatcheck
6187 tool, which is designed for that purpose.
6189 @ifset vms
6190 @code{(option,option,@dots{})} is a sequence of keywords
6191 @end ifset
6192 @ifclear vms
6193 The string @var{x} is a sequence of letters or digits
6194 @end ifclear
6195 indicating the particular style
6196 checks to be performed. The following checks are defined:
6198 @table @option
6199 @c !sort!
6200 @item 0-9
6201 @emph{Specify indentation level.}
6202 If a digit from 1-9 appears
6203 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6204 then proper indentation is checked, with the digit indicating the
6205 indentation level required. A value of zero turns off this style check.
6206 The general style of required indentation is as specified by
6207 the examples in the Ada Reference Manual. Full line comments must be
6208 aligned with the @code{--} starting on a column that is a multiple of
6209 the alignment level, or they may be aligned the same way as the following
6210 non-blank line (this is useful when full line comments appear in the middle
6211 of a statement, or they may be aligned with the source line on the previous
6212 non-blank line.
6214 @item ^a^ATTRIBUTE^
6215 @emph{Check attribute casing.}
6216 Attribute names, including the case of keywords such as @code{digits}
6217 used as attributes names, must be written in mixed case, that is, the
6218 initial letter and any letter following an underscore must be uppercase.
6219 All other letters must be lowercase.
6221 @item ^A^ARRAY_INDEXES^
6222 @emph{Use of array index numbers in array attributes.}
6223 When using the array attributes First, Last, Range,
6224 or Length, the index number must be omitted for one-dimensional arrays
6225 and is required for multi-dimensional arrays.
6227 @item ^b^BLANKS^
6228 @emph{Blanks not allowed at statement end.}
6229 Trailing blanks are not allowed at the end of statements. The purpose of this
6230 rule, together with h (no horizontal tabs), is to enforce a canonical format
6231 for the use of blanks to separate source tokens.
6233 @item ^B^BOOLEAN_OPERATORS^
6234 @emph{Check Boolean operators.}
6235 The use of AND/OR operators is not permitted except in the cases of modular
6236 operands, array operands, and simple stand-alone boolean variables or
6237 boolean constants. In all other cases @code{and then}/@code{or else} are
6238 required.
6240 @item ^c^COMMENTS^
6241 @emph{Check comments, double space.}
6242 Comments must meet the following set of rules:
6244 @itemize @bullet
6246 @item
6247 The ``@code{--}'' that starts the column must either start in column one,
6248 or else at least one blank must precede this sequence.
6250 @item
6251 Comments that follow other tokens on a line must have at least one blank
6252 following the ``@code{--}'' at the start of the comment.
6254 @item
6255 Full line comments must have at least two blanks following the
6256 ``@code{--}'' that starts the comment, with the following exceptions.
6258 @item
6259 A line consisting only of the ``@code{--}'' characters, possibly preceded
6260 by blanks is permitted.
6262 @item
6263 A comment starting with ``@code{--x}'' where @code{x} is a special character
6264 is permitted.
6265 This allows proper processing of the output generated by specialized tools
6266 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6267 annotation
6268 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6269 special character is defined as being in one of the ASCII ranges
6270 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6271 Note that this usage is not permitted
6272 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6274 @item
6275 A line consisting entirely of minus signs, possibly preceded by blanks, is
6276 permitted. This allows the construction of box comments where lines of minus
6277 signs are used to form the top and bottom of the box.
6279 @item
6280 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6281 least one blank follows the initial ``@code{--}''. Together with the preceding
6282 rule, this allows the construction of box comments, as shown in the following
6283 example:
6284 @smallexample
6285 ---------------------------
6286 -- This is a box comment --
6287 -- with two text lines.  --
6288 ---------------------------
6289 @end smallexample
6290 @end itemize
6292 @item ^C^COMMENTS1^
6293 @emph{Check comments, single space.}
6294 This is identical to @code{^c^COMMENTS^} except that only one space
6295 is required following the @code{--} of a comment instead of two.
6297 @item ^d^DOS_LINE_ENDINGS^
6298 @emph{Check no DOS line terminators present.}
6299 All lines must be terminated by a single ASCII.LF
6300 character (in particular the DOS line terminator sequence CR/LF is not
6301 allowed).
6303 @item ^e^END^
6304 @emph{Check end/exit labels.}
6305 Optional labels on @code{end} statements ending subprograms and on
6306 @code{exit} statements exiting named loops, are required to be present.
6308 @item ^f^VTABS^
6309 @emph{No form feeds or vertical tabs.}
6310 Neither form feeds nor vertical tab characters are permitted
6311 in the source text.
6313 @item ^g^GNAT^
6314 @emph{GNAT style mode.}
6315 The set of style check switches is set to match that used by the GNAT sources.
6316 This may be useful when developing code that is eventually intended to be
6317 incorporated into GNAT. For further details, see GNAT sources.
6319 @item ^h^HTABS^
6320 @emph{No horizontal tabs.}
6321 Horizontal tab characters are not permitted in the source text.
6322 Together with the b (no blanks at end of line) check, this
6323 enforces a canonical form for the use of blanks to separate
6324 source tokens.
6326 @item ^i^IF_THEN^
6327 @emph{Check if-then layout.}
6328 The keyword @code{then} must appear either on the same
6329 line as corresponding @code{if}, or on a line on its own, lined
6330 up under the @code{if} with at least one non-blank line in between
6331 containing all or part of the condition to be tested.
6333 @item ^I^IN_MODE^
6334 @emph{check mode IN keywords.}
6335 Mode @code{in} (the default mode) is not
6336 allowed to be given explicitly. @code{in out} is fine,
6337 but not @code{in} on its own.
6339 @item ^k^KEYWORD^
6340 @emph{Check keyword casing.}
6341 All keywords must be in lower case (with the exception of keywords
6342 such as @code{digits} used as attribute names to which this check
6343 does not apply).
6345 @item ^l^LAYOUT^
6346 @emph{Check layout.}
6347 Layout of statement and declaration constructs must follow the
6348 recommendations in the Ada Reference Manual, as indicated by the
6349 form of the syntax rules. For example an @code{else} keyword must
6350 be lined up with the corresponding @code{if} keyword.
6352 There are two respects in which the style rule enforced by this check
6353 option are more liberal than those in the Ada Reference Manual. First
6354 in the case of record declarations, it is permissible to put the
6355 @code{record} keyword on the same line as the @code{type} keyword, and
6356 then the @code{end} in @code{end record} must line up under @code{type}.
6357 This is also permitted when the type declaration is split on two lines.
6358 For example, any of the following three layouts is acceptable:
6360 @smallexample @c ada
6361 @cartouche
6362 type q is record
6363    a : integer;
6364    b : integer;
6365 end record;
6367 type q is
6368    record
6369       a : integer;
6370       b : integer;
6371    end record;
6373 type q is
6374    record
6375       a : integer;
6376       b : integer;
6377 end record;
6379 @end cartouche
6380 @end smallexample
6382 @noindent
6383 Second, in the case of a block statement, a permitted alternative
6384 is to put the block label on the same line as the @code{declare} or
6385 @code{begin} keyword, and then line the @code{end} keyword up under
6386 the block label. For example both the following are permitted:
6388 @smallexample @c ada
6389 @cartouche
6390 Block : declare
6391    A : Integer := 3;
6392 begin
6393    Proc (A, A);
6394 end Block;
6396 Block :
6397    declare
6398       A : Integer := 3;
6399    begin
6400       Proc (A, A);
6401    end Block;
6402 @end cartouche
6403 @end smallexample
6405 @noindent
6406 The same alternative format is allowed for loops. For example, both of
6407 the following are permitted:
6409 @smallexample @c ada
6410 @cartouche
6411 Clear : while J < 10 loop
6412    A (J) := 0;
6413 end loop Clear;
6415 Clear :
6416    while J < 10 loop
6417       A (J) := 0;
6418    end loop Clear;
6419 @end cartouche
6420 @end smallexample
6422 @item ^Lnnn^MAX_NESTING=nnn^
6423 @emph{Set maximum nesting level.}
6424 The maximum level of nesting of constructs (including subprograms, loops,
6425 blocks, packages, and conditionals) may not exceed the given value
6426 @option{nnn}. A value of zero disconnects this style check.
6428 @item ^m^LINE_LENGTH^
6429 @emph{Check maximum line length.}
6430 The length of source lines must not exceed 79 characters, including
6431 any trailing blanks. The value of 79 allows convenient display on an
6432 80 character wide device or window, allowing for possible special
6433 treatment of 80 character lines. Note that this count is of
6434 characters in the source text. This means that a tab character counts
6435 as one character in this count and a wide character sequence counts as
6436 a single character (however many bytes are needed in the encoding).
6438 @item ^Mnnn^MAX_LENGTH=nnn^
6439 @emph{Set maximum line length.}
6440 The length of lines must not exceed the
6441 given value @option{nnn}. The maximum value that can be specified is 32767.
6442 If neither style option for setting the line length is used, then the
6443 default is 255. This also controls the maximum length of lexical elements,
6444 where the only restriction is that they must fit on a single line.
6446 @item ^n^STANDARD_CASING^
6447 @emph{Check casing of entities in Standard.}
6448 Any identifier from Standard must be cased
6449 to match the presentation in the Ada Reference Manual (for example,
6450 @code{Integer} and @code{ASCII.NUL}).
6452 @item ^N^NONE^
6453 @emph{Turn off all style checks.}
6454 All style check options are turned off.
6456 @item ^o^ORDERED_SUBPROGRAMS^
6457 @emph{Check order of subprogram bodies.}
6458 All subprogram bodies in a given scope
6459 (e.g.@: a package body) must be in alphabetical order. The ordering
6460 rule uses normal Ada rules for comparing strings, ignoring casing
6461 of letters, except that if there is a trailing numeric suffix, then
6462 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6463 before Junk10).
6465 @item ^O^OVERRIDING_INDICATORS^
6466 @emph{Check that overriding subprograms are explicitly marked as such.}
6467 The declaration of a primitive operation of a type extension that overrides
6468 an inherited operation must carry an overriding indicator.
6470 @item ^p^PRAGMA^
6471 @emph{Check pragma casing.}
6472 Pragma names must be written in mixed case, that is, the
6473 initial letter and any letter following an underscore must be uppercase.
6474 All other letters must be lowercase.
6476 @item ^r^REFERENCES^
6477 @emph{Check references.}
6478 All identifier references must be cased in the same way as the
6479 corresponding declaration. No specific casing style is imposed on
6480 identifiers. The only requirement is for consistency of references
6481 with declarations.
6483 @item ^s^SPECS^
6484 @emph{Check separate specs.}
6485 Separate declarations (``specs'') are required for subprograms (a
6486 body is not allowed to serve as its own declaration). The only
6487 exception is that parameterless library level procedures are
6488 not required to have a separate declaration. This exception covers
6489 the most frequent form of main program procedures.
6491 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6492 @emph{Check no statements after @code{then}/@code{else}.}
6493 No statements are allowed
6494 on the same line as a @code{then} or @code{else} keyword following the
6495 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6496 affected, and a special exception allows a pragma to appear after @code{else}.
6498 @item ^t^TOKEN^
6499 @emph{Check token spacing.}
6500 The following token spacing rules are enforced:
6502 @itemize @bullet
6504 @item
6505 The keywords @code{abs} and @code{not} must be followed by a space.
6507 @item
6508 The token @code{=>} must be surrounded by spaces.
6510 @item
6511 The token @code{<>} must be preceded by a space or a left parenthesis.
6513 @item
6514 Binary operators other than @code{**} must be surrounded by spaces.
6515 There is no restriction on the layout of the @code{**} binary operator.
6517 @item
6518 Colon must be surrounded by spaces.
6520 @item
6521 Colon-equal (assignment, initialization) must be surrounded by spaces.
6523 @item
6524 Comma must be the first non-blank character on the line, or be
6525 immediately preceded by a non-blank character, and must be followed
6526 by a space.
6528 @item
6529 If the token preceding a left parenthesis ends with a letter or digit, then
6530 a space must separate the two tokens.
6532 @item
6533 if the token following a right parenthesis starts with a letter or digit, then
6534 a space must separate the two tokens.
6536 @item
6537 A right parenthesis must either be the first non-blank character on
6538 a line, or it must be preceded by a non-blank character.
6540 @item
6541 A semicolon must not be preceded by a space, and must not be followed by
6542 a non-blank character.
6544 @item
6545 A unary plus or minus may not be followed by a space.
6547 @item
6548 A vertical bar must be surrounded by spaces.
6549 @end itemize
6551 @item
6552 Exactly one blank (and no other white space) must appear between
6553 a @code{not} token and a following @code{in} token.
6555 @item ^u^UNNECESSARY_BLANK_LINES^
6556 @emph{Check unnecessary blank lines.}
6557 Unnecessary blank lines are not allowed. A blank line is considered
6558 unnecessary if it appears at the end of the file, or if more than
6559 one blank line occurs in sequence.
6561 @item ^x^XTRA_PARENS^
6562 @emph{Check extra parentheses.}
6563 Unnecessary extra level of parentheses (C-style) are not allowed
6564 around conditions in @code{if} statements, @code{while} statements and
6565 @code{exit} statements.
6567 @item ^y^ALL_BUILTIN^
6568 @emph{Set all standard style check options}
6569 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6570 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6571 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6572 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6574 @ifclear vms
6575 @item -
6576 @emph{Remove style check options}
6577 This causes any subsequent options in the string to act as canceling the
6578 corresponding style check option. To cancel maximum nesting level control,
6579 use @option{L} parameter witout any integer value after that, because any
6580 digit following @option{-} in the parameter string of the @option{-gnaty}
6581 option will be threated as canceling indentation check. The same is true
6582 for @option{M} parameter. @option{y} and @option{N} parameters are not
6583 allowed after @option{-}.
6585 @item +
6586 This causes any subsequent options in the string to enable the corresponding
6587 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6588 if any.
6589 @end ifclear
6591 @ifset vms
6592 @item NOxxx
6593 @emph{Removing style check options}
6594 If the name of a style check is preceded by @option{NO} then the corresponding
6595 style check is turned off. For example @option{NOCOMMENTS} turns off style
6596 checking for comments.
6597 @end ifset
6598 @end table
6600 @noindent
6601 In the above rules, appearing in column one is always permitted, that is,
6602 counts as meeting either a requirement for a required preceding space,
6603 or as meeting a requirement for no preceding space.
6605 Appearing at the end of a line is also always permitted, that is, counts
6606 as meeting either a requirement for a following space, or as meeting
6607 a requirement for no following space.
6609 @noindent
6610 If any of these style rules is violated, a message is generated giving
6611 details on the violation. The initial characters of such messages are
6612 always ``@code{(style)}''. Note that these messages are treated as warning
6613 messages, so they normally do not prevent the generation of an object
6614 file. The @option{-gnatwe} switch can be used to treat warning messages,
6615 including style messages, as fatal errors.
6617 The switch
6618 @ifclear vms
6619 @option{-gnaty} on its own (that is not
6620 followed by any letters or digits) is equivalent
6621 to the use of @option{-gnatyy} as described above, that is all
6622 built-in standard style check options are enabled.
6624 @end ifclear
6625 @ifset vms
6626 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6627 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6628 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6629 @end ifset
6631 The switch
6632 @ifclear vms
6633 @option{-gnatyN}
6634 @end ifclear
6635 @ifset vms
6636 /STYLE_CHECKS=NONE
6637 @end ifset
6638 clears any previously set style checks.
6640 @node Run-Time Checks
6641 @subsection Run-Time Checks
6642 @cindex Division by zero
6643 @cindex Access before elaboration
6644 @cindex Checks, division by zero
6645 @cindex Checks, access before elaboration
6646 @cindex Checks, stack overflow checking
6648 @noindent
6649 By default, the following checks are suppressed: integer overflow
6650 checks, stack overflow checks, and checks for access before
6651 elaboration on subprogram calls. All other checks, including range
6652 checks and array bounds checks, are turned on by default. The
6653 following @command{gcc} switches refine this default behavior.
6655 @table @option
6656 @c !sort!
6657 @item -gnatp
6658 @cindex @option{-gnatp} (@command{gcc})
6659 @cindex Suppressing checks
6660 @cindex Checks, suppressing
6661 @findex Suppress
6662 This switch causes the unit to be compiled
6663 as though @code{pragma Suppress (All_checks)}
6664 had been present in the source. Validity checks are also eliminated (in
6665 other words @option{-gnatp} also implies @option{-gnatVn}.
6666 Use this switch to improve the performance
6667 of the code at the expense of safety in the presence of invalid data or
6668 program bugs.
6670 Note that when checks are suppressed, the compiler is allowed, but not
6671 required, to omit the checking code. If the run-time cost of the
6672 checking code is zero or near-zero, the compiler will generate it even
6673 if checks are suppressed. In particular, if the compiler can prove
6674 that a certain check will necessarily fail, it will generate code to
6675 do an unconditional ``raise'', even if checks are suppressed. The
6676 compiler warns in this case. Another case in which checks may not be
6677 eliminated is when they are embedded in certain run time routines such
6678 as math library routines.
6680 Of course, run-time checks are omitted whenever the compiler can prove
6681 that they will not fail, whether or not checks are suppressed.
6683 Note that if you suppress a check that would have failed, program
6684 execution is erroneous, which means the behavior is totally
6685 unpredictable. The program might crash, or print wrong answers, or
6686 do anything else. It might even do exactly what you wanted it to do
6687 (and then it might start failing mysteriously next week or next
6688 year). The compiler will generate code based on the assumption that
6689 the condition being checked is true, which can result in disaster if
6690 that assumption is wrong.
6692 The checks subject to suppression include all the checks defined by
6693 the Ada standard, the additional implementation defined checks
6694 @code{Alignment_Check}, @code{Atomic_Synchronization}, and
6695 @code{Validity_Check}, as well as any checks introduced using
6696 @code{pragma Check_Name}.
6698 The @option{-gnatp} switch has no effect if a subsequent
6699 @option{-gnat-p} switch appears.
6701 @item -gnat-p
6702 @cindex @option{-gnat-p} (@command{gcc})
6703 @cindex Suppressing checks
6704 @cindex Checks, suppressing
6705 @findex Suppress
6706 This switch cancels the effect of a previous @option{gnatp} switch.
6708 @item -gnato??
6709 @cindex @option{-gnato??} (@command{gcc})
6710 @cindex Overflow checks
6711 @cindex Overflow mode
6712 @cindex Check, overflow
6713 This switch controls the mode used for computing intermediate
6714 arithmetic integer operations, and also enables overflow checking.
6715 For a full description of overflow mode and checking control, see
6716 the ``Overflow Check Handling in GNAT'' appendix in this
6717 User's Guide.
6719 Overflow checks are always enabled by this switch. The argument
6720 controls the mode, using the codes
6722 @itemize
6723 @item 1 = STRICT
6724 In STRICT mode, intermediate operations are always done using the
6725 base type, and overflow checking ensures that the result is within
6726 the base type range.
6728 @item 2 = MINIMIZED
6729 In MINIMIZED mode, overflows in intermediate operations are avoided
6730 where possible by using a larger integer type for the computation
6731 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6732 the result fits in this larger integer type.
6734 @item 3 = ELIMINATED
6735 In ELIMINATED mode, overflows in intermediate operations are avoided
6736 by using multi-precision arithmetic. In this case, overflow checking
6737 has no effect on intermediate operations (since overflow is impossible).
6738 @end itemize
6740 If two digits are present after @option{-gnato} then the first digit
6741 sets the mode for expressions outside assertions, and the second digit
6742 sets the mode for expressions within assertions. Here assertions is used
6743 in the technical sense (which includes for example precondition and
6744 postcondition expressions).
6746 If one digit is present, the corresponding mode is applicable to both
6747 expressions within and outside assertion expressions.
6749 If no digits are present, the default is to enable overflow checks
6750 and set STRICT mode for both kinds of expressions. This is compatible
6751 with the use of @option{-gnato} in previous versions of GNAT.
6753 @findex Machine_Overflows
6754 Note that the @option{-gnato??} switch does not affect the code generated
6755 for any floating-point operations; it applies only to integer semantics.
6756 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6757 attribute set to @code{False} and the normal mode of operation is to
6758 generate IEEE NaN and infinite values on overflow or invalid operations
6759 (such as dividing 0.0 by 0.0).
6761 The reason that we distinguish overflow checking from other kinds of
6762 range constraint checking is that a failure of an overflow check, unlike
6763 for example the failure of a range check, can result in an incorrect
6764 value, but cannot cause random memory destruction (like an out of range
6765 subscript), or a wild jump (from an out of range case value). Overflow
6766 checking is also quite expensive in time and space, since in general it
6767 requires the use of double length arithmetic.
6769 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6770 so overflow checking is not performed in default mode. This means that out of
6771 the box, with the default settings, @value{EDITION} does not do all the checks
6772 expected from the language description in the Ada Reference Manual.
6773 If you want all constraint checks to be performed, as described in this Manual,
6774 then you must explicitly use the @option{-gnato??}
6775 switch either on the @command{gnatmake} or @command{gcc} command.
6777 @item -gnatE
6778 @cindex @option{-gnatE} (@command{gcc})
6779 @cindex Elaboration checks
6780 @cindex Check, elaboration
6781 Enables dynamic checks for access-before-elaboration
6782 on subprogram calls and generic instantiations.
6783 Note that @option{-gnatE} is not necessary for safety, because in the
6784 default mode, GNAT ensures statically that the checks would not fail.
6785 For full details of the effect and use of this switch,
6786 @xref{Compiling with gcc}.
6788 @item -fstack-check
6789 @cindex @option{-fstack-check} (@command{gcc})
6790 @cindex Stack Overflow Checking
6791 @cindex Checks, stack overflow checking
6792 Activates stack overflow checking. For full details of the effect and use of
6793 this switch see @ref{Stack Overflow Checking}.
6794 @end table
6796 @findex Unsuppress
6797 @noindent
6798 The setting of these switches only controls the default setting of the
6799 checks. You may modify them using either @code{Suppress} (to remove
6800 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6801 the program source.
6803 @node Using gcc for Syntax Checking
6804 @subsection Using @command{gcc} for Syntax Checking
6805 @table @option
6806 @item -gnats
6807 @cindex @option{-gnats} (@command{gcc})
6808 @ifclear vms
6810 @noindent
6811 The @code{s} stands for ``syntax''.
6812 @end ifclear
6814 Run GNAT in syntax checking only mode. For
6815 example, the command
6817 @smallexample
6818 $ gcc -c -gnats x.adb
6819 @end smallexample
6821 @noindent
6822 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6823 series of files in a single command
6824 @ifclear vms
6825 , and can use wild cards to specify such a group of files.
6826 Note that you must specify the @option{-c} (compile
6827 only) flag in addition to the @option{-gnats} flag.
6828 @end ifclear
6830 You may use other switches in conjunction with @option{-gnats}. In
6831 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6832 format of any generated error messages.
6834 When the source file is empty or contains only empty lines and/or comments,
6835 the output is a warning:
6837 @smallexample
6838 $ gcc -c -gnats -x ada toto.txt
6839 toto.txt:1:01: warning: empty file, contains no compilation units
6841 @end smallexample
6843 Otherwise, the output is simply the error messages, if any. No object file or
6844 ALI file is generated by a syntax-only compilation. Also, no units other
6845 than the one specified are accessed. For example, if a unit @code{X}
6846 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6847 check only mode does not access the source file containing unit
6848 @code{Y}.
6850 @cindex Multiple units, syntax checking
6851 Normally, GNAT allows only a single unit in a source file. However, this
6852 restriction does not apply in syntax-check-only mode, and it is possible
6853 to check a file containing multiple compilation units concatenated
6854 together. This is primarily used by the @code{gnatchop} utility
6855 (@pxref{Renaming Files with gnatchop}).
6856 @end table
6858 @node Using gcc for Semantic Checking
6859 @subsection Using @command{gcc} for Semantic Checking
6860 @table @option
6861 @item -gnatc
6862 @cindex @option{-gnatc} (@command{gcc})
6864 @ifclear vms
6865 @noindent
6866 The @code{c} stands for ``check''.
6867 @end ifclear
6868 Causes the compiler to operate in semantic check mode,
6869 with full checking for all illegalities specified in the
6870 Ada Reference Manual, but without generation of any object code
6871 (no object file is generated).
6873 Because dependent files must be accessed, you must follow the GNAT
6874 semantic restrictions on file structuring to operate in this mode:
6876 @itemize @bullet
6877 @item
6878 The needed source files must be accessible
6879 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6881 @item
6882 Each file must contain only one compilation unit.
6884 @item
6885 The file name and unit name must match (@pxref{File Naming Rules}).
6886 @end itemize
6888 The output consists of error messages as appropriate. No object file is
6889 generated. An @file{ALI} file is generated for use in the context of
6890 cross-reference tools, but this file is marked as not being suitable
6891 for binding (since no object file is generated).
6892 The checking corresponds exactly to the notion of
6893 legality in the Ada Reference Manual.
6895 Any unit can be compiled in semantics-checking-only mode, including
6896 units that would not normally be compiled (subunits,
6897 and specifications where a separate body is present).
6898 @end table
6900 @node Compiling Different Versions of Ada
6901 @subsection Compiling Different Versions of Ada
6903 @noindent
6904 The switches described in this section allow you to explicitly specify
6905 the version of the Ada language that your programs are written in.
6906 The default mode is Ada 2012,
6907 but you can also specify Ada 95, Ada 2005 mode, or
6908 indicate Ada 83 compatibility mode.
6910 @table @option
6911 @cindex Compatibility with Ada 83
6913 @item -gnat83 (Ada 83 Compatibility Mode)
6914 @cindex @option{-gnat83} (@command{gcc})
6915 @cindex ACVC, Ada 83 tests
6916 @cindex Ada 83 mode
6918 @noindent
6919 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6920 specifies that the program is to be compiled in Ada 83 mode. With
6921 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6922 semantics where this can be done easily.
6923 It is not possible to guarantee this switch does a perfect
6924 job; some subtle tests, such as are
6925 found in earlier ACVC tests (and that have been removed from the ACATS suite
6926 for Ada 95), might not compile correctly.
6927 Nevertheless, this switch may be useful in some circumstances, for example
6928 where, due to contractual reasons, existing code needs to be maintained
6929 using only Ada 83 features.
6931 With few exceptions (most notably the need to use @code{<>} on
6932 @cindex Generic formal parameters
6933 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6934 reserved words, and the use of packages
6935 with optional bodies), it is not necessary to specify the
6936 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6937 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6938 a correct Ada 83 program is usually also a correct program
6939 in these later versions of the language standard.
6940 For further information, please refer to @ref{Compatibility and Porting Guide}.
6942 @item -gnat95 (Ada 95 mode)
6943 @cindex @option{-gnat95} (@command{gcc})
6944 @cindex Ada 95 mode
6946 @noindent
6947 This switch directs the compiler to implement the Ada 95 version of the
6948 language.
6949 Since Ada 95 is almost completely upwards
6950 compatible with Ada 83, Ada 83 programs may generally be compiled using
6951 this switch (see the description of the @option{-gnat83} switch for further
6952 information about Ada 83 mode).
6953 If an Ada 2005 program is compiled in Ada 95 mode,
6954 uses of the new Ada 2005 features will cause error
6955 messages or warnings.
6957 This switch also can be used to cancel the effect of a previous
6958 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6959 switch earlier in the command line.
6961 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6962 @cindex @option{-gnat05} (@command{gcc})
6963 @cindex @option{-gnat2005} (@command{gcc})
6964 @cindex Ada 2005 mode
6966 @noindent
6967 This switch directs the compiler to implement the Ada 2005 version of the
6968 language, as documented in the official Ada standards document.
6969 Since Ada 2005 is almost completely upwards
6970 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6971 may generally be compiled using this switch (see the description of the
6972 @option{-gnat83} and @option{-gnat95} switches for further
6973 information).
6975 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6976 @cindex @option{-gnat12} (@command{gcc})
6977 @cindex @option{-gnat2012} (@command{gcc})
6978 @cindex Ada 2012 mode
6980 @noindent
6981 This switch directs the compiler to implement the Ada 2012 version of the
6982 language (also the default).
6983 Since Ada 2012 is almost completely upwards
6984 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6985 Ada 83 and Ada 95 programs
6986 may generally be compiled using this switch (see the description of the
6987 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6988 for further information).
6990 @item -gnatX (Enable GNAT Extensions)
6991 @cindex @option{-gnatX} (@command{gcc})
6992 @cindex Ada language extensions
6993 @cindex GNAT extensions
6995 @noindent
6996 This switch directs the compiler to implement the latest version of the
6997 language (currently Ada 2012) and also to enable certain GNAT implementation
6998 extensions that are not part of any Ada standard. For a full list of these
6999 extensions, see the GNAT reference manual.
7001 @end table
7003 @node Character Set Control
7004 @subsection Character Set Control
7005 @table @option
7006 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7007 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7009 @noindent
7010 Normally GNAT recognizes the Latin-1 character set in source program
7011 identifiers, as described in the Ada Reference Manual.
7012 This switch causes
7013 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7014 single character ^^or word^ indicating the character set, as follows:
7016 @table @code
7017 @item 1
7018 ISO 8859-1 (Latin-1) identifiers
7020 @item 2
7021 ISO 8859-2 (Latin-2) letters allowed in identifiers
7023 @item 3
7024 ISO 8859-3 (Latin-3) letters allowed in identifiers
7026 @item 4
7027 ISO 8859-4 (Latin-4) letters allowed in identifiers
7029 @item 5
7030 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7032 @item 9
7033 ISO 8859-15 (Latin-9) letters allowed in identifiers
7035 @item ^p^PC^
7036 IBM PC letters (code page 437) allowed in identifiers
7038 @item ^8^PC850^
7039 IBM PC letters (code page 850) allowed in identifiers
7041 @item ^f^FULL_UPPER^
7042 Full upper-half codes allowed in identifiers
7044 @item ^n^NO_UPPER^
7045 No upper-half codes allowed in identifiers
7047 @item ^w^WIDE^
7048 Wide-character codes (that is, codes greater than 255)
7049 allowed in identifiers
7050 @end table
7052 @xref{Foreign Language Representation}, for full details on the
7053 implementation of these character sets.
7055 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7056 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7057 Specify the method of encoding for wide characters.
7058 @var{e} is one of the following:
7060 @table @code
7062 @item ^h^HEX^
7063 Hex encoding (brackets coding also recognized)
7065 @item ^u^UPPER^
7066 Upper half encoding (brackets encoding also recognized)
7068 @item ^s^SHIFT_JIS^
7069 Shift/JIS encoding (brackets encoding also recognized)
7071 @item ^e^EUC^
7072 EUC encoding (brackets encoding also recognized)
7074 @item ^8^UTF8^
7075 UTF-8 encoding (brackets encoding also recognized)
7077 @item ^b^BRACKETS^
7078 Brackets encoding only (default value)
7079 @end table
7080 For full details on these encoding
7081 methods see @ref{Wide Character Encodings}.
7082 Note that brackets coding is always accepted, even if one of the other
7083 options is specified, so for example @option{-gnatW8} specifies that both
7084 brackets and UTF-8 encodings will be recognized. The units that are
7085 with'ed directly or indirectly will be scanned using the specified
7086 representation scheme, and so if one of the non-brackets scheme is
7087 used, it must be used consistently throughout the program. However,
7088 since brackets encoding is always recognized, it may be conveniently
7089 used in standard libraries, allowing these libraries to be used with
7090 any of the available coding schemes.
7092 Note that brackets encoding only applies to program text. Within comments,
7093 brackets are considered to be normal graphic characters, and bracket sequences
7094 are never recognized as wide characters.
7096 If no @option{-gnatW?} parameter is present, then the default
7097 representation is normally Brackets encoding only. However, if the
7098 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7099 byte order mark or BOM for UTF-8), then these three characters are
7100 skipped and the default representation for the file is set to UTF-8.
7102 Note that the wide character representation that is specified (explicitly
7103 or by default) for the main program also acts as the default encoding used
7104 for Wide_Text_IO files if not specifically overridden by a WCEM form
7105 parameter.
7107 @end table
7109 When no @option{-gnatW?} is specified, then characters (other than wide
7110 characters represented using brackets notation) are treated as 8-bit
7111 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7112 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7113 characters in the range 16#00#..16#1F# are not accepted in program text
7114 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7115 in program text, but allowed and ignored in comments. Note in particular
7116 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7117 as an end of line in this default mode. If your source program contains
7118 instances of the NEL character used as a line terminator,
7119 you must use UTF-8 encoding for the whole
7120 source program. In default mode, all lines must be ended by a standard
7121 end of line sequence (CR, CR/LF, or LF).
7123 Note that the convention of simply accepting all upper half characters in
7124 comments means that programs that use standard ASCII for program text, but
7125 UTF-8 encoding for comments are accepted in default mode, providing that the
7126 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7127 This is a common mode for many programs with foreign language comments.
7129 @node File Naming Control
7130 @subsection File Naming Control
7132 @table @option
7133 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7134 @cindex @option{-gnatk} (@command{gcc})
7135 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7136 1-999, indicates the maximum allowable length of a file name (not
7137 including the @file{.ads} or @file{.adb} extension). The default is not
7138 to enable file name krunching.
7140 For the source file naming rules, @xref{File Naming Rules}.
7141 @end table
7143 @node Subprogram Inlining Control
7144 @subsection Subprogram Inlining Control
7146 @table @option
7147 @c !sort!
7148 @item -gnatn[12]
7149 @cindex @option{-gnatn} (@command{gcc})
7150 @ifclear vms
7151 The @code{n} here is intended to suggest the first syllable of the
7152 word ``inline''.
7153 @end ifclear
7154 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7155 inlining to actually occur, optimization must be enabled and, in order
7156 to enable inlining of subprograms specified by pragma @code{Inline},
7157 you must also specify this switch.
7158 In the absence of this switch, GNAT does not attempt
7159 inlining and does not need to access the bodies of
7160 subprograms for which @code{pragma Inline} is specified if they are not
7161 in the current unit.
7163 You can optionally specify the inlining level: 1 for moderate inlining across
7164 modules, which is a good compromise between compilation times and performances
7165 at run time, or 2 for full inlining across modules, which may bring about
7166 longer compilation times. If no inlining level is specified, the compiler will
7167 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7168 @option{-Os} and 2 for @option{-O3}.
7170 If you specify this switch the compiler will access these bodies,
7171 creating an extra source dependency for the resulting object file, and
7172 where possible, the call will be inlined.
7173 For further details on when inlining is possible
7174 see @ref{Inlining of Subprograms}.
7176 @item -gnatN
7177 @cindex @option{-gnatN} (@command{gcc})
7178 This switch activates front-end inlining which also
7179 generates additional dependencies.
7181 When using a gcc-based back end (in practice this means using any version
7182 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7183 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7184 Historically front end inlining was more extensive than the gcc back end
7185 inlining, but that is no longer the case.
7186 @end table
7188 @node Auxiliary Output Control
7189 @subsection Auxiliary Output Control
7191 @table @option
7192 @item -gnatt
7193 @cindex @option{-gnatt} (@command{gcc})
7194 @cindex Writing internal trees
7195 @cindex Internal trees, writing to file
7196 Causes GNAT to write the internal tree for a unit to a file (with the
7197 extension @file{.adt}.
7198 This not normally required, but is used by separate analysis tools.
7199 Typically
7200 these tools do the necessary compilations automatically, so you should
7201 not have to specify this switch in normal operation.
7202 Note that the combination of switches @option{-gnatct}
7203 generates a tree in the form required by ASIS applications.
7205 @item -gnatu
7206 @cindex @option{-gnatu} (@command{gcc})
7207 Print a list of units required by this compilation on @file{stdout}.
7208 The listing includes all units on which the unit being compiled depends
7209 either directly or indirectly.
7211 @ifclear vms
7212 @item -pass-exit-codes
7213 @cindex @option{-pass-exit-codes} (@command{gcc})
7214 If this switch is not used, the exit code returned by @command{gcc} when
7215 compiling multiple files indicates whether all source files have
7216 been successfully used to generate object files or not.
7218 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7219 exit status and allows an integrated development environment to better
7220 react to a compilation failure. Those exit status are:
7222 @table @asis
7223 @item 5
7224 There was an error in at least one source file.
7225 @item 3
7226 At least one source file did not generate an object file.
7227 @item 2
7228 The compiler died unexpectedly (internal error for example).
7229 @item 0
7230 An object file has been generated for every source file.
7231 @end table
7232 @end ifclear
7233 @end table
7235 @node Debugging Control
7236 @subsection Debugging Control
7238 @table @option
7239 @c !sort!
7240 @cindex Debugging options
7241 @ifclear vms
7242 @item -gnatd@var{x}
7243 @cindex @option{-gnatd} (@command{gcc})
7244 Activate internal debugging switches. @var{x} is a letter or digit, or
7245 string of letters or digits, which specifies the type of debugging
7246 outputs desired. Normally these are used only for internal development
7247 or system debugging purposes. You can find full documentation for these
7248 switches in the body of the @code{Debug} unit in the compiler source
7249 file @file{debug.adb}.
7250 @end ifclear
7252 @item -gnatG[=nn]
7253 @cindex @option{-gnatG} (@command{gcc})
7254 This switch causes the compiler to generate auxiliary output containing
7255 a pseudo-source listing of the generated expanded code. Like most Ada
7256 compilers, GNAT works by first transforming the high level Ada code into
7257 lower level constructs. For example, tasking operations are transformed
7258 into calls to the tasking run-time routines. A unique capability of GNAT
7259 is to list this expanded code in a form very close to normal Ada source.
7260 This is very useful in understanding the implications of various Ada
7261 usage on the efficiency of the generated code. There are many cases in
7262 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7263 generate a lot of run-time code. By using @option{-gnatG} you can identify
7264 these cases, and consider whether it may be desirable to modify the coding
7265 approach to improve efficiency.
7267 The optional parameter @code{nn} if present after -gnatG specifies an
7268 alternative maximum line length that overrides the normal default of 72.
7269 This value is in the range 40-999999, values less than 40 being silently
7270 reset to 40. The equal sign is optional.
7272 The format of the output is very similar to standard Ada source, and is
7273 easily understood by an Ada programmer. The following special syntactic
7274 additions correspond to low level features used in the generated code that
7275 do not have any exact analogies in pure Ada source form. The following
7276 is a partial list of these special constructions. See the spec
7277 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7279 If the switch @option{-gnatL} is used in conjunction with
7280 @cindex @option{-gnatL} (@command{gcc})
7281 @option{-gnatG}, then the original source lines are interspersed
7282 in the expanded source (as comment lines with the original line number).
7284 @table @code
7285 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7286 Shows the storage pool being used for an allocator.
7288 @item at end @var{procedure-name};
7289 Shows the finalization (cleanup) procedure for a scope.
7291 @item (if @var{expr} then @var{expr} else @var{expr})
7292 Conditional expression equivalent to the @code{x?y:z} construction in C.
7294 @item @var{target}^^^(@var{source})
7295 A conversion with floating-point truncation instead of rounding.
7297 @item @var{target}?(@var{source})
7298 A conversion that bypasses normal Ada semantic checking. In particular
7299 enumeration types and fixed-point types are treated simply as integers.
7301 @item @var{target}?^^^(@var{source})
7302 Combines the above two cases.
7304 @item @var{x} #/ @var{y}
7305 @itemx @var{x} #mod @var{y}
7306 @itemx @var{x} #* @var{y}
7307 @itemx @var{x} #rem @var{y}
7308 A division or multiplication of fixed-point values which are treated as
7309 integers without any kind of scaling.
7311 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7312 Shows the storage pool associated with a @code{free} statement.
7314 @item [subtype or type declaration]
7315 Used to list an equivalent declaration for an internally generated
7316 type that is referenced elsewhere in the listing.
7318 @c @item freeze @var{type-name} @ovar{actions}
7319 @c Expanding @ovar macro inline (explanation in macro def comments)
7320 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7321 Shows the point at which @var{type-name} is frozen, with possible
7322 associated actions to be performed at the freeze point.
7324 @item reference @var{itype}
7325 Reference (and hence definition) to internal type @var{itype}.
7327 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7328 Intrinsic function call.
7330 @item @var{label-name} : label
7331 Declaration of label @var{labelname}.
7333 @item #$ @var{subprogram-name}
7334 An implicit call to a run-time support routine
7335 (to meet the requirement of H.3.1(9) in a
7336 convenient manner).
7338 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7339 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7340 @var{expr}, but handled more efficiently).
7342 @item [constraint_error]
7343 Raise the @code{Constraint_Error} exception.
7345 @item @var{expression}'reference
7346 A pointer to the result of evaluating @var{expression}.
7348 @item @var{target-type}!(@var{source-expression})
7349 An unchecked conversion of @var{source-expression} to @var{target-type}.
7351 @item [@var{numerator}/@var{denominator}]
7352 Used to represent internal real literals (that) have no exact
7353 representation in base 2-16 (for example, the result of compile time
7354 evaluation of the expression 1.0/27.0).
7355 @end table
7357 @item -gnatD[=nn]
7358 @cindex @option{-gnatD} (@command{gcc})
7359 When used in conjunction with @option{-gnatG}, this switch causes
7360 the expanded source, as described above for
7361 @option{-gnatG} to be written to files with names
7362 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7363 instead of to the standard output file. For
7364 example, if the source file name is @file{hello.adb}, then a file
7365 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7366 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7367 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7368 you to do source level debugging using the generated code which is
7369 sometimes useful for complex code, for example to find out exactly
7370 which part of a complex construction raised an exception. This switch
7371 also suppress generation of cross-reference information (see
7372 @option{-gnatx}) since otherwise the cross-reference information
7373 would refer to the @file{^.dg^.DG^} file, which would cause
7374 confusion since this is not the original source file.
7376 Note that @option{-gnatD} actually implies @option{-gnatG}
7377 automatically, so it is not necessary to give both options.
7378 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7380 If the switch @option{-gnatL} is used in conjunction with
7381 @cindex @option{-gnatL} (@command{gcc})
7382 @option{-gnatDG}, then the original source lines are interspersed
7383 in the expanded source (as comment lines with the original line number).
7385 The optional parameter @code{nn} if present after -gnatD specifies an
7386 alternative maximum line length that overrides the normal default of 72.
7387 This value is in the range 40-999999, values less than 40 being silently
7388 reset to 40. The equal sign is optional.
7390 @item -gnatr
7391 @cindex @option{-gnatr} (@command{gcc})
7392 @cindex pragma Restrictions
7393 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7394 so that violation of restrictions causes warnings rather than illegalities.
7395 This is useful during the development process when new restrictions are added
7396 or investigated. The switch also causes pragma Profile to be treated as
7397 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7398 restriction warnings rather than restrictions.
7400 @ifclear vms
7401 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7402 @cindex @option{-gnatR} (@command{gcc})
7403 This switch controls output from the compiler of a listing showing
7404 representation information for declared types and objects. For
7405 @option{-gnatR0}, no information is output (equivalent to omitting
7406 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7407 so @option{-gnatR} with no parameter has the same effect), size and alignment
7408 information is listed for declared array and record types. For
7409 @option{-gnatR2}, size and alignment information is listed for all
7410 declared types and objects. Finally @option{-gnatR3} includes symbolic
7411 expressions for values that are computed at run time for
7412 variant records. These symbolic expressions have a mostly obvious
7413 format with #n being used to represent the value of the n'th
7414 discriminant. See source files @file{repinfo.ads/adb} in the
7415 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7416 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7417 the output is to a file with the name @file{^file.rep^file_REP^} where
7418 file is the name of the corresponding source file.
7420 @item -gnatRm[s]
7421 This form of the switch controls output of subprogram conventions
7422 and parameter passing mechanisms for all subprograms. A following
7423 @code{s} means output to a file as described above.
7424 @end ifclear
7425 @ifset vms
7426 @item /REPRESENTATION_INFO
7427 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7428 This qualifier controls output from the compiler of a listing showing
7429 representation information for declared types and objects. For
7430 @option{/REPRESENTATION_INFO=NONE}, no information is output
7431 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7432 @option{/REPRESENTATION_INFO} without option is equivalent to
7433 @option{/REPRESENTATION_INFO=ARRAYS}.
7434 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7435 information is listed for declared array and record types. For
7436 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7437 is listed for all expression information for values that are computed
7438 at run time for variant records. These symbolic expressions have a mostly
7439 obvious format with #n being used to represent the value of the n'th
7440 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7441 @code{GNAT} sources for full details on the format of
7442 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7443 If _FILE is added at the end of an option
7444 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7445 then the output is to a file with the name @file{file_REP} where
7446 file is the name of the corresponding source file.
7448 @item /REPRESENTATION_INFO=MECHANISMS
7449 This qualifier form controls output of subprogram conventions
7450 and parameter passing mechanisms for all subprograms. It is
7451 possible to append _FILE as described above to cause information
7452 to be written to a file.
7453 @end ifset
7455 Note that it is possible for record components to have zero size. In
7456 this case, the component clause uses an obvious extension of permitted
7457 Ada syntax, for example @code{at 0 range 0 .. -1}.
7459 Representation information requires that code be generated (since it is the
7460 code generator that lays out complex data structures). If an attempt is made
7461 to output representation information when no code is generated, for example
7462 when a subunit is compiled on its own, then no information can be generated
7463 and the compiler outputs a message to this effect.
7465 @item -gnatS
7466 @cindex @option{-gnatS} (@command{gcc})
7467 The use of the switch @option{-gnatS} for an
7468 Ada compilation will cause the compiler to output a
7469 representation of package Standard in a form very
7470 close to standard Ada. It is not quite possible to
7471 do this entirely in standard Ada (since new
7472 numeric base types cannot be created in standard
7473 Ada), but the output is easily
7474 readable to any Ada programmer, and is useful to
7475 determine the characteristics of target dependent
7476 types in package Standard.
7478 @item -gnatx
7479 @cindex @option{-gnatx} (@command{gcc})
7480 Normally the compiler generates full cross-referencing information in
7481 the @file{ALI} file. This information is used by a number of tools,
7482 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7483 suppresses this information. This saves some space and may slightly
7484 speed up compilation, but means that these tools cannot be used.
7485 @end table
7487 @node Exception Handling Control
7488 @subsection Exception Handling Control
7490 @noindent
7491 GNAT uses two methods for handling exceptions at run-time. The
7492 @code{setjmp/longjmp} method saves the context when entering
7493 a frame with an exception handler. Then when an exception is
7494 raised, the context can be restored immediately, without the
7495 need for tracing stack frames. This method provides very fast
7496 exception propagation, but introduces significant overhead for
7497 the use of exception handlers, even if no exception is raised.
7499 The other approach is called ``zero cost'' exception handling.
7500 With this method, the compiler builds static tables to describe
7501 the exception ranges. No dynamic code is required when entering
7502 a frame containing an exception handler. When an exception is
7503 raised, the tables are used to control a back trace of the
7504 subprogram invocation stack to locate the required exception
7505 handler. This method has considerably poorer performance for
7506 the propagation of exceptions, but there is no overhead for
7507 exception handlers if no exception is raised. Note that in this
7508 mode and in the context of mixed Ada and C/C++ programming,
7509 to propagate an exception through a C/C++ code, the C/C++ code
7510 must be compiled with the @option{-funwind-tables} GCC's
7511 option.
7513 The following switches may be used to control which of the
7514 two exception handling methods is used.
7516 @table @option
7517 @c !sort!
7519 @item --RTS=sjlj
7520 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7521 This switch causes the setjmp/longjmp run-time (when available) to be used
7522 for exception handling. If the default
7523 mechanism for the target is zero cost exceptions, then
7524 this switch can be used to modify this default, and must be
7525 used for all units in the partition.
7526 This option is rarely used. One case in which it may be
7527 advantageous is if you have an application where exception
7528 raising is common and the overall performance of the
7529 application is improved by favoring exception propagation.
7531 @item --RTS=zcx
7532 @cindex @option{--RTS=zcx} (@command{gnatmake})
7533 @cindex Zero Cost Exceptions
7534 This switch causes the zero cost approach to be used
7535 for exception handling. If this is the default mechanism for the
7536 target (see below), then this switch is unneeded. If the default
7537 mechanism for the target is setjmp/longjmp exceptions, then
7538 this switch can be used to modify this default, and must be
7539 used for all units in the partition.
7540 This option can only be used if the zero cost approach
7541 is available for the target in use, otherwise it will generate an error.
7542 @end table
7544 @noindent
7545 The same option @option{--RTS} must be used both for @command{gcc}
7546 and @command{gnatbind}. Passing this option to @command{gnatmake}
7547 (@pxref{Switches for gnatmake}) will ensure the required consistency
7548 through the compilation and binding steps.
7550 @node Units to Sources Mapping Files
7551 @subsection Units to Sources Mapping Files
7553 @table @option
7555 @item -gnatem=@var{path}
7556 @cindex @option{-gnatem} (@command{gcc})
7557 A mapping file is a way to communicate to the compiler two mappings:
7558 from unit names to file names (without any directory information) and from
7559 file names to path names (with full directory information). These mappings
7560 are used by the compiler to short-circuit the path search.
7562 The use of mapping files is not required for correct operation of the
7563 compiler, but mapping files can improve efficiency, particularly when
7564 sources are read over a slow network connection. In normal operation,
7565 you need not be concerned with the format or use of mapping files,
7566 and the @option{-gnatem} switch is not a switch that you would use
7567 explicitly. It is intended primarily for use by automatic tools such as
7568 @command{gnatmake} running under the project file facility. The
7569 description here of the format of mapping files is provided
7570 for completeness and for possible use by other tools.
7572 A mapping file is a sequence of sets of three lines. In each set, the
7573 first line is the unit name, in lower case, with @code{%s} appended
7574 for specs and @code{%b} appended for bodies; the second line is the
7575 file name; and the third line is the path name.
7577 Example:
7578 @smallexample
7579    main%b
7580    main.2.ada
7581    /gnat/project1/sources/main.2.ada
7582 @end smallexample
7584 When the switch @option{-gnatem} is specified, the compiler will
7585 create in memory the two mappings from the specified file. If there is
7586 any problem (nonexistent file, truncated file or duplicate entries),
7587 no mapping will be created.
7589 Several @option{-gnatem} switches may be specified; however, only the
7590 last one on the command line will be taken into account.
7592 When using a project file, @command{gnatmake} creates a temporary
7593 mapping file and communicates it to the compiler using this switch.
7595 @end table
7597 @node Integrated Preprocessing
7598 @subsection Integrated Preprocessing
7600 @noindent
7601 GNAT sources may be preprocessed immediately before compilation.
7602 In this case, the actual
7603 text of the source is not the text of the source file, but is derived from it
7604 through a process called preprocessing. Integrated preprocessing is specified
7605 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7606 indicates, through a text file, the preprocessing data to be used.
7607 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7609 @noindent
7610 Note that when integrated preprocessing is used, the output from the
7611 preprocessor is not written to any external file. Instead it is passed
7612 internally to the compiler. If you need to preserve the result of
7613 preprocessing in a file, then you should use @command{gnatprep}
7614 to perform the desired preprocessing in stand-alone mode.
7616 @noindent
7617 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7618 used when Integrated Preprocessing is used. The reason is that preprocessing
7619 with another Preprocessing Data file without changing the sources will
7620 not trigger recompilation without this switch.
7622 @noindent
7623 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7624 always trigger recompilation for sources that are preprocessed,
7625 because @command{gnatmake} cannot compute the checksum of the source after
7626 preprocessing.
7628 @noindent
7629 The actual preprocessing function is described in details in section
7630 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7631 preprocessing is triggered and parameterized.
7633 @table @code
7635 @item -gnatep=@var{file}
7636 @cindex @option{-gnatep} (@command{gcc})
7637 This switch indicates to the compiler the file name (without directory
7638 information) of the preprocessor data file to use. The preprocessor data file
7639 should be found in the source directories. Note that when the compiler is
7640 called by a builder such as (@command{gnatmake} with a project
7641 file, if the object directory is not also a source directory, the builder needs
7642 to be called with @option{-x}.
7644 @noindent
7645 A preprocessing data file is a text file with significant lines indicating
7646 how should be preprocessed either a specific source or all sources not
7647 mentioned in other lines. A significant line is a nonempty, non-comment line.
7648 Comments are similar to Ada comments.
7650 @noindent
7651 Each significant line starts with either a literal string or the character '*'.
7652 A literal string is the file name (without directory information) of the source
7653 to preprocess. A character '*' indicates the preprocessing for all the sources
7654 that are not specified explicitly on other lines (order of the lines is not
7655 significant). It is an error to have two lines with the same file name or two
7656 lines starting with the character '*'.
7658 @noindent
7659 After the file name or the character '*', another optional literal string
7660 indicating the file name of the definition file to be used for preprocessing
7661 (@pxref{Form of Definitions File}). The definition files are found by the
7662 compiler in one of the source directories. In some cases, when compiling
7663 a source in a directory other than the current directory, if the definition
7664 file is in the current directory, it may be necessary to add the current
7665 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7666 the compiler would not find the definition file.
7668 @noindent
7669 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7670 be found. Those ^switches^switches^ are:
7672 @table @code
7674 @item -b
7675 Causes both preprocessor lines and the lines deleted by
7676 preprocessing to be replaced by blank lines, preserving the line number.
7677 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7678 it cancels the effect of @option{-c}.
7680 @item -c
7681 Causes both preprocessor lines and the lines deleted
7682 by preprocessing to be retained as comments marked
7683 with the special string ``@code{--! }''.
7685 @item -Dsymbol=value
7686 Define or redefine a symbol, associated with value. A symbol is an Ada
7687 identifier, or an Ada reserved word, with the exception of @code{if},
7688 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7689 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7690 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7691 same name defined in a definition file.
7693 @item -s
7694 Causes a sorted list of symbol names and values to be
7695 listed on the standard output file.
7697 @item -u
7698 Causes undefined symbols to be treated as having the value @code{FALSE}
7699 in the context
7700 of a preprocessor test. In the absence of this option, an undefined symbol in
7701 a @code{#if} or @code{#elsif} test will be treated as an error.
7703 @end table
7705 @noindent
7706 Examples of valid lines in a preprocessor data file:
7708 @smallexample
7709   "toto.adb"  "prep.def" -u
7710   --  preprocess "toto.adb", using definition file "prep.def",
7711   --  undefined symbol are False.
7713   * -c -DVERSION=V101
7714   --  preprocess all other sources without a definition file;
7715   --  suppressed lined are commented; symbol VERSION has the value V101.
7717   "titi.adb" "prep2.def" -s
7718   --  preprocess "titi.adb", using definition file "prep2.def";
7719   --  list all symbols with their values.
7720 @end smallexample
7722 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7723 @cindex @option{-gnateD} (@command{gcc})
7724 Define or redefine a preprocessing symbol, associated with value. If no value
7725 is given on the command line, then the value of the symbol is @code{True}.
7726 A symbol is an identifier, following normal Ada (case-insensitive)
7727 rules for its syntax, and value is either an arbitrary string between double
7728 quotes or any sequence (including an empty sequence) of characters from the
7729 set (letters, digits, period, underline).
7730 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7731 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7733 @ifclear vms
7734 @noindent
7735 Examples:
7737 @smallexample
7738    -gnateDToto=Titi
7739    -gnateDFoo
7740    -gnateDFoo=\"Foo-Bar\"
7741 @end smallexample
7742 @end ifclear
7744 @noindent
7745 A symbol declared with this ^switch^switch^ on the command line replaces a
7746 symbol with the same name either in a definition file or specified with a
7747 ^switch^switch^ -D in the preprocessor data file.
7749 @noindent
7750 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7752 @item -gnateG
7753 When integrated preprocessing is performed and the preprocessor modifies
7754 the source text, write the result of this preprocessing into a file
7755 <source>^.prep^_prep^.
7757 @end table
7759 @node Code Generation Control
7760 @subsection Code Generation Control
7762 @noindent
7764 The GCC technology provides a wide range of target dependent
7765 @option{-m} switches for controlling
7766 details of code generation with respect to different versions of
7767 architectures. This includes variations in instruction sets (e.g.@:
7768 different members of the power pc family), and different requirements
7769 for optimal arrangement of instructions (e.g.@: different members of
7770 the x86 family). The list of available @option{-m} switches may be
7771 found in the GCC documentation.
7773 Use of these @option{-m} switches may in some cases result in improved
7774 code performance.
7776 The @value{EDITION} technology is tested and qualified without any
7777 @option{-m} switches,
7778 so generally the most reliable approach is to avoid the use of these
7779 switches. However, we generally expect most of these switches to work
7780 successfully with @value{EDITION}, and many customers have reported successful
7781 use of these options.
7783 Our general advice is to avoid the use of @option{-m} switches unless
7784 special needs lead to requirements in this area. In particular,
7785 there is no point in using @option{-m} switches to improve performance
7786 unless you actually see a performance improvement.
7788 @ifset vms
7789 @node Return Codes
7790 @subsection Return Codes
7791 @cindex Return Codes
7792 @cindex @option{/RETURN_CODES=VMS}
7794 @noindent
7795 On VMS, GNAT compiled programs return POSIX-style codes by default,
7796 e.g.@: @option{/RETURN_CODES=POSIX}.
7798 To enable VMS style return codes, use GNAT BIND and LINK with the option
7799 @option{/RETURN_CODES=VMS}. For example:
7801 @smallexample
7802 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7803 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7804 @end smallexample
7806 @noindent
7807 Programs built with /RETURN_CODES=VMS are suitable to be called in
7808 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7809 are suitable for spawning with appropriate GNAT RTL routines.
7811 @end ifset
7813 @node Search Paths and the Run-Time Library (RTL)
7814 @section Search Paths and the Run-Time Library (RTL)
7816 @noindent
7817 With the GNAT source-based library system, the compiler must be able to
7818 find source files for units that are needed by the unit being compiled.
7819 Search paths are used to guide this process.
7821 The compiler compiles one source file whose name must be given
7822 explicitly on the command line. In other words, no searching is done
7823 for this file. To find all other source files that are needed (the most
7824 common being the specs of units), the compiler examines the following
7825 directories, in the following order:
7827 @enumerate
7828 @item
7829 The directory containing the source file of the main unit being compiled
7830 (the file name on the command line).
7832 @item
7833 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7834 @command{gcc} command line, in the order given.
7836 @item
7837 @findex ADA_PRJ_INCLUDE_FILE
7838 Each of the directories listed in the text file whose name is given
7839 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7841 @noindent
7842 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7843 driver when project files are used. It should not normally be set
7844 by other means.
7846 @item
7847 @findex ADA_INCLUDE_PATH
7848 Each of the directories listed in the value of the
7849 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7850 @ifclear vms
7851 Construct this value
7852 exactly as the @env{PATH} environment variable: a list of directory
7853 names separated by colons (semicolons when working with the NT version).
7854 @end ifclear
7855 @ifset vms
7856 Normally, define this value as a logical name containing a comma separated
7857 list of directory names.
7859 This variable can also be defined by means of an environment string
7860 (an argument to the HP C exec* set of functions).
7862 Logical Name:
7863 @smallexample
7864 DEFINE ANOTHER_PATH FOO:[BAG]
7865 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7866 @end smallexample
7868 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7869 first, followed by the standard Ada
7870 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7871 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7872 (Text_IO, Sequential_IO, etc)
7873 instead of the standard Ada packages. Thus, in order to get the standard Ada
7874 packages by default, ADA_INCLUDE_PATH must be redefined.
7875 @end ifset
7877 @item
7878 The content of the @file{ada_source_path} file which is part of the GNAT
7879 installation tree and is used to store standard libraries such as the
7880 GNAT Run Time Library (RTL) source files.
7881 @ifclear vms
7882 @ref{Installing a library}
7883 @end ifclear
7884 @end enumerate
7886 @noindent
7887 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7888 inhibits the use of the directory
7889 containing the source file named in the command line. You can still
7890 have this directory on your search path, but in this case it must be
7891 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7893 Specifying the switch @option{-nostdinc}
7894 inhibits the search of the default location for the GNAT Run Time
7895 Library (RTL) source files.
7897 The compiler outputs its object files and ALI files in the current
7898 working directory.
7899 @ifclear vms
7900 Caution: The object file can be redirected with the @option{-o} switch;
7901 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7902 so the @file{ALI} file will not go to the right place. Therefore, you should
7903 avoid using the @option{-o} switch.
7904 @end ifclear
7906 @findex System.IO
7907 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7908 children make up the GNAT RTL, together with the simple @code{System.IO}
7909 package used in the @code{"Hello World"} example. The sources for these units
7910 are needed by the compiler and are kept together in one directory. Not
7911 all of the bodies are needed, but all of the sources are kept together
7912 anyway. In a normal installation, you need not specify these directory
7913 names when compiling or binding. Either the environment variables or
7914 the built-in defaults cause these files to be found.
7916 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7917 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7918 consisting of child units of @code{GNAT}. This is a collection of generally
7919 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7920 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7922 Besides simplifying access to the RTL, a major use of search paths is
7923 in compiling sources from multiple directories. This can make
7924 development environments much more flexible.
7926 @node Order of Compilation Issues
7927 @section Order of Compilation Issues
7929 @noindent
7930 If, in our earlier example, there was a spec for the @code{hello}
7931 procedure, it would be contained in the file @file{hello.ads}; yet this
7932 file would not have to be explicitly compiled. This is the result of the
7933 model we chose to implement library management. Some of the consequences
7934 of this model are as follows:
7936 @itemize @bullet
7937 @item
7938 There is no point in compiling specs (except for package
7939 specs with no bodies) because these are compiled as needed by clients. If
7940 you attempt a useless compilation, you will receive an error message.
7941 It is also useless to compile subunits because they are compiled as needed
7942 by the parent.
7944 @item
7945 There are no order of compilation requirements: performing a
7946 compilation never obsoletes anything. The only way you can obsolete
7947 something and require recompilations is to modify one of the
7948 source files on which it depends.
7950 @item
7951 There is no library as such, apart from the ALI files
7952 (@pxref{The Ada Library Information Files}, for information on the format
7953 of these files). For now we find it convenient to create separate ALI files,
7954 but eventually the information therein may be incorporated into the object
7955 file directly.
7957 @item
7958 When you compile a unit, the source files for the specs of all units
7959 that it @code{with}'s, all its subunits, and the bodies of any generics it
7960 instantiates must be available (reachable by the search-paths mechanism
7961 described above), or you will receive a fatal error message.
7962 @end itemize
7964 @node Examples
7965 @section Examples
7967 @noindent
7968 The following are some typical Ada compilation command line examples:
7970 @table @code
7971 @item $ gcc -c xyz.adb
7972 Compile body in file @file{xyz.adb} with all default options.
7974 @ifclear vms
7975 @item $ gcc -c -O2 -gnata xyz-def.adb
7976 @end ifclear
7977 @ifset vms
7978 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7979 @end ifset
7981 Compile the child unit package in file @file{xyz-def.adb} with extensive
7982 optimizations, and pragma @code{Assert}/@code{Debug} statements
7983 enabled.
7985 @item $ gcc -c -gnatc abc-def.adb
7986 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7987 mode.
7988 @end table
7990 @node Binding with gnatbind
7991 @chapter Binding with @code{gnatbind}
7992 @findex gnatbind
7994 @menu
7995 * Running gnatbind::
7996 * Switches for gnatbind::
7997 * Command-Line Access::
7998 * Search Paths for gnatbind::
7999 * Examples of gnatbind Usage::
8000 @end menu
8002 @noindent
8003 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8004 to bind compiled GNAT objects.
8006 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8007 driver (see @ref{The GNAT Driver and Project Files}).
8009 The @code{gnatbind} program performs four separate functions:
8011 @enumerate
8012 @item
8013 Checks that a program is consistent, in accordance with the rules in
8014 Chapter 10 of the Ada Reference Manual. In particular, error
8015 messages are generated if a program uses inconsistent versions of a
8016 given unit.
8018 @item
8019 Checks that an acceptable order of elaboration exists for the program
8020 and issues an error message if it cannot find an order of elaboration
8021 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8023 @item
8024 Generates a main program incorporating the given elaboration order.
8025 This program is a small Ada package (body and spec) that
8026 must be subsequently compiled
8027 using the GNAT compiler. The necessary compilation step is usually
8028 performed automatically by @command{gnatlink}. The two most important
8029 functions of this program
8030 are to call the elaboration routines of units in an appropriate order
8031 and to call the main program.
8033 @item
8034 Determines the set of object files required by the given main program.
8035 This information is output in the forms of comments in the generated program,
8036 to be read by the @command{gnatlink} utility used to link the Ada application.
8037 @end enumerate
8039 @node Running gnatbind
8040 @section Running @code{gnatbind}
8042 @noindent
8043 The form of the @code{gnatbind} command is
8045 @smallexample
8046 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8047 @c Expanding @ovar macro inline (explanation in macro def comments)
8048 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8049 @end smallexample
8051 @noindent
8052 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8053 unit body. @code{gnatbind} constructs an Ada
8054 package in two files whose names are
8055 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8056 For example, if given the
8057 parameter @file{hello.ali}, for a main program contained in file
8058 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8059 and @file{b~hello.adb}.
8061 When doing consistency checking, the binder takes into consideration
8062 any source files it can locate. For example, if the binder determines
8063 that the given main program requires the package @code{Pack}, whose
8064 @file{.ALI}
8065 file is @file{pack.ali} and whose corresponding source spec file is
8066 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8067 (using the same search path conventions as previously described for the
8068 @command{gcc} command). If it can locate this source file, it checks that
8069 the time stamps
8070 or source checksums of the source and its references to in @file{ALI} files
8071 match. In other words, any @file{ALI} files that mentions this spec must have
8072 resulted from compiling this version of the source file (or in the case
8073 where the source checksums match, a version close enough that the
8074 difference does not matter).
8076 @cindex Source files, use by binder
8077 The effect of this consistency checking, which includes source files, is
8078 that the binder ensures that the program is consistent with the latest
8079 version of the source files that can be located at bind time. Editing a
8080 source file without compiling files that depend on the source file cause
8081 error messages to be generated by the binder.
8083 For example, suppose you have a main program @file{hello.adb} and a
8084 package @code{P}, from file @file{p.ads} and you perform the following
8085 steps:
8087 @enumerate
8088 @item
8089 Enter @code{gcc -c hello.adb} to compile the main program.
8091 @item
8092 Enter @code{gcc -c p.ads} to compile package @code{P}.
8094 @item
8095 Edit file @file{p.ads}.
8097 @item
8098 Enter @code{gnatbind hello}.
8099 @end enumerate
8101 @noindent
8102 At this point, the file @file{p.ali} contains an out-of-date time stamp
8103 because the file @file{p.ads} has been edited. The attempt at binding
8104 fails, and the binder generates the following error messages:
8106 @smallexample
8107 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8108 error: "p.ads" has been modified and must be recompiled
8109 @end smallexample
8111 @noindent
8112 Now both files must be recompiled as indicated, and then the bind can
8113 succeed, generating a main program. You need not normally be concerned
8114 with the contents of this file, but for reference purposes a sample
8115 binder output file is given in @ref{Example of Binder Output File}.
8117 In most normal usage, the default mode of @command{gnatbind} which is to
8118 generate the main package in Ada, as described in the previous section.
8119 In particular, this means that any Ada programmer can read and understand
8120 the generated main program. It can also be debugged just like any other
8121 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8122 @command{gnatbind} and @command{gnatlink}.
8124 @node Switches for gnatbind
8125 @section Switches for @command{gnatbind}
8127 @noindent
8128 The following switches are available with @code{gnatbind}; details will
8129 be presented in subsequent sections.
8131 @menu
8132 * Consistency-Checking Modes::
8133 * Binder Error Message Control::
8134 * Elaboration Control::
8135 * Output Control::
8136 * Dynamic Allocation Control::
8137 * Binding with Non-Ada Main Programs::
8138 * Binding Programs with No Main Subprogram::
8139 @end menu
8141 @table @option
8142 @c !sort!
8144 @item --version
8145 @cindex @option{--version} @command{gnatbind}
8146 Display Copyright and version, then exit disregarding all other options.
8148 @item --help
8149 @cindex @option{--help} @command{gnatbind}
8150 If @option{--version} was not used, display usage, then exit disregarding
8151 all other options.
8153 @item -a
8154 @cindex @option{-a} @command{gnatbind}
8155 Indicates that, if supported by the platform, the adainit procedure should
8156 be treated as an initialisation routine by the linker (a constructor). This
8157 is intended to be used by the Project Manager to automatically initialize
8158 shared Stand-Alone Libraries.
8160 @item ^-aO^/OBJECT_SEARCH^
8161 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8162 Specify directory to be searched for ALI files.
8164 @item ^-aI^/SOURCE_SEARCH^
8165 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8166 Specify directory to be searched for source file.
8168 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8169 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8170 Output ALI list (to standard output or to the named file).
8172 @item ^-b^/REPORT_ERRORS=BRIEF^
8173 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8174 Generate brief messages to @file{stderr} even if verbose mode set.
8176 @item ^-c^/NOOUTPUT^
8177 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8178 Check only, no generation of binder output file.
8180 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8181 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8182 This switch can be used to change the default task stack size value
8183 to a specified size @var{nn}, which is expressed in bytes by default, or
8184 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8185 with @var{m}.
8186 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8187 in effect, to completing all task specs with
8188 @smallexample @c ada
8189    pragma Storage_Size (nn);
8190 @end smallexample
8191 When they do not already have such a pragma.
8193 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8194 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8195 This switch can be used to change the default secondary stack size value
8196 to a specified size @var{nn}, which is expressed in bytes by default, or
8197 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8198 with @var{m}.
8200 The secondary stack is used to deal with functions that return a variable
8201 sized result, for example a function returning an unconstrained
8202 String. There are two ways in which this secondary stack is allocated.
8204 For most targets, the secondary stack is growing on demand and is allocated
8205 as a chain of blocks in the heap. The -D option is not very
8206 relevant. It only give some control over the size of the allocated
8207 blocks (whose size is the minimum of the default secondary stack size value,
8208 and the actual size needed for the current allocation request).
8210 For certain targets, notably VxWorks 653,
8211 the secondary stack is allocated by carving off a fixed ratio chunk of the
8212 primary task stack. The -D option is used to define the
8213 size of the environment task's secondary stack.
8215 @item ^-e^/ELABORATION_DEPENDENCIES^
8216 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8217 Output complete list of elaboration-order dependencies.
8219 @item ^-E^/STORE_TRACEBACKS^
8220 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8221 Store tracebacks in exception occurrences when the target supports it.
8222 @ignore
8223 @c The following may get moved to an appendix
8224 This option is currently supported on the following targets:
8225 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8226 @end ignore
8227 See also the packages @code{GNAT.Traceback} and
8228 @code{GNAT.Traceback.Symbolic} for more information.
8229 @ifclear vms
8230 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8231 @command{gcc} option.
8232 @end ifclear
8234 @item ^-F^/FORCE_ELABS_FLAGS^
8235 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8236 Force the checks of elaboration flags. @command{gnatbind} does not normally
8237 generate checks of elaboration flags for the main executable, except when
8238 a Stand-Alone Library is used. However, there are cases when this cannot be
8239 detected by gnatbind. An example is importing an interface of a Stand-Alone
8240 Library through a pragma Import and only specifying through a linker switch
8241 this Stand-Alone Library. This switch is used to guarantee that elaboration
8242 flag checks are generated.
8244 @item ^-h^/HELP^
8245 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8246 Output usage (help) information
8248 @item ^-H32^/32_MALLOC^
8249 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8250 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8251 For further details see @ref{Dynamic Allocation Control}.
8253 @item ^-H64^/64_MALLOC^
8254 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8255 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8256 @cindex @code{__gnat_malloc}
8257 For further details see @ref{Dynamic Allocation Control}.
8259 @item ^-I^/SEARCH^
8260 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8261 Specify directory to be searched for source and ALI files.
8263 @item ^-I-^/NOCURRENT_DIRECTORY^
8264 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8265 Do not look for sources in the current directory where @code{gnatbind} was
8266 invoked, and do not look for ALI files in the directory containing the
8267 ALI file named in the @code{gnatbind} command line.
8269 @item ^-l^/ORDER_OF_ELABORATION^
8270 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8271 Output chosen elaboration order.
8273 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8274 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8275 Bind the units for library building. In this case the adainit and
8276 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8277 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8278 ^@var{xxx}final^@var{XXX}FINAL^.
8279 Implies ^-n^/NOCOMPILE^.
8280 @ifclear vms
8281 (@xref{GNAT and Libraries}, for more details.)
8282 @end ifclear
8283 @ifset vms
8284 On OpenVMS, these init and final procedures are exported in uppercase
8285 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8286 the init procedure will be "TOTOINIT" and the exported name of the final
8287 procedure will be "TOTOFINAL".
8288 @end ifset
8290 @item ^-Mxyz^/RENAME_MAIN=xyz^
8291 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8292 Rename generated main program from main to xyz. This option is
8293 supported on cross environments only.
8295 @item ^-m^/ERROR_LIMIT=^@var{n}
8296 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8297 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8298 in the range 1..999999. The default value if no switch is
8299 given is 9999. If the number of warnings reaches this limit, then a
8300 message is output and further warnings are suppressed, the bind
8301 continues in this case. If the number of errors reaches this
8302 limit, then a message is output and the bind is abandoned.
8303 A value of zero means that no limit is enforced. The equal
8304 sign is optional.
8306 @ifset unw
8307 Furthermore, under Windows, the sources pointed to by the libraries path
8308 set in the registry are not searched for.
8309 @end ifset
8311 @item ^-n^/NOMAIN^
8312 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8313 No main program.
8315 @item -nostdinc
8316 @cindex @option{-nostdinc} (@command{gnatbind})
8317 Do not look for sources in the system default directory.
8319 @item -nostdlib
8320 @cindex @option{-nostdlib} (@command{gnatbind})
8321 Do not look for library files in the system default directory.
8323 @item --RTS=@var{rts-path}
8324 @cindex @option{--RTS} (@code{gnatbind})
8325 Specifies the default location of the runtime library. Same meaning as the
8326 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8328 @item ^-o ^/OUTPUT=^@var{file}
8329 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8330 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8331 Note that if this option is used, then linking must be done manually,
8332 gnatlink cannot be used.
8334 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8335 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8336 Output object list (to standard output or to the named file).
8338 @item ^-p^/PESSIMISTIC_ELABORATION^
8339 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8340 Pessimistic (worst-case) elaboration order
8342 @item ^-P^-P^
8343 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8344 Generate binder file suitable for CodePeer.
8346 @item ^-R^-R^
8347 @cindex @option{^-R^-R^} (@command{gnatbind})
8348 Output closure source list.
8350 @item ^-s^/READ_SOURCES=ALL^
8351 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8352 Require all source files to be present.
8354 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8355 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8356 Specifies the value to be used when detecting uninitialized scalar
8357 objects with pragma Initialize_Scalars.
8358 The @var{xxx} ^string specified with the switch^option^ may be either
8359 @itemize @bullet
8360 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8361 @item ``@option{^lo^LOW^}'' for the lowest possible value
8362 @item ``@option{^hi^HIGH^}'' for the highest possible value
8363 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8364 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8365 @end itemize
8367 In addition, you can specify @option{-Sev} to indicate that the value is
8368 to be set at run time. In this case, the program will look for an environment
8369 @cindex GNAT_INIT_SCALARS
8370 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8371 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8372 If no environment variable is found, or if it does not have a valid value,
8373 then the default is @option{in} (invalid values).
8375 @ifclear vms
8376 @item -static
8377 @cindex @option{-static} (@code{gnatbind})
8378 Link against a static GNAT run time.
8380 @item -shared
8381 @cindex @option{-shared} (@code{gnatbind})
8382 Link against a shared GNAT run time when available.
8383 @end ifclear
8385 @item ^-t^/NOTIME_STAMP_CHECK^
8386 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8387 Tolerate time stamp and other consistency errors
8389 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8390 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8391 Set the time slice value to @var{n} milliseconds. If the system supports
8392 the specification of a specific time slice value, then the indicated value
8393 is used. If the system does not support specific time slice values, but
8394 does support some general notion of round-robin scheduling, then any
8395 nonzero value will activate round-robin scheduling.
8397 A value of zero is treated specially. It turns off time
8398 slicing, and in addition, indicates to the tasking run time that the
8399 semantics should match as closely as possible the Annex D
8400 requirements of the Ada RM, and in particular sets the default
8401 scheduling policy to @code{FIFO_Within_Priorities}.
8403 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8404 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8405 Enable dynamic stack usage, with @var{n} results stored and displayed
8406 at program termination. A result is generated when a task
8407 terminates. Results that can't be stored are displayed on the fly, at
8408 task termination. This option is currently not supported on Itanium
8409 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8411 @item ^-v^/REPORT_ERRORS=VERBOSE^
8412 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8413 Verbose mode. Write error messages, header, summary output to
8414 @file{stdout}.
8416 @ifclear vms
8417 @item -w@var{x}
8418 @cindex @option{-w} (@code{gnatbind})
8419 Warning mode (@var{x}=s/e for suppress/treat as error)
8420 @end ifclear
8422 @ifset vms
8423 @item /WARNINGS=NORMAL
8424 @cindex @option{/WARNINGS} (@code{gnatbind})
8425 Normal warnings mode. Warnings are issued but ignored
8427 @item /WARNINGS=SUPPRESS
8428 @cindex @option{/WARNINGS} (@code{gnatbind})
8429 All warning messages are suppressed
8431 @item /WARNINGS=ERROR
8432 @cindex @option{/WARNINGS} (@code{gnatbind})
8433 Warning messages are treated as fatal errors
8434 @end ifset
8436 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8437 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8438 Override default wide character encoding for standard Text_IO files.
8440 @item ^-x^/READ_SOURCES=NONE^
8441 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8442 Exclude source files (check object consistency only).
8444 @ifset vms
8445 @item /READ_SOURCES=AVAILABLE
8446 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8447 Default mode, in which sources are checked for consistency only if
8448 they are available.
8449 @end ifset
8451 @item ^-y^/ENABLE_LEAP_SECONDS^
8452 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8453 Enable leap seconds support in @code{Ada.Calendar} and its children.
8455 @item ^-z^/ZERO_MAIN^
8456 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8457 No main subprogram.
8458 @end table
8460 @ifclear vms
8461 @noindent
8462 You may obtain this listing of switches by running @code{gnatbind} with
8463 no arguments.
8464 @end ifclear
8466 @node Consistency-Checking Modes
8467 @subsection Consistency-Checking Modes
8469 @noindent
8470 As described earlier, by default @code{gnatbind} checks
8471 that object files are consistent with one another and are consistent
8472 with any source files it can locate. The following switches control binder
8473 access to sources.
8475 @table @option
8476 @c !sort!
8477 @item ^-s^/READ_SOURCES=ALL^
8478 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8479 Require source files to be present. In this mode, the binder must be
8480 able to locate all source files that are referenced, in order to check
8481 their consistency. In normal mode, if a source file cannot be located it
8482 is simply ignored. If you specify this switch, a missing source
8483 file is an error.
8485 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8486 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8487 Override default wide character encoding for standard Text_IO files.
8488 Normally the default wide character encoding method used for standard
8489 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8490 the main source input (see description of switch
8491 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8492 use of this switch for the binder (which has the same set of
8493 possible arguments) overrides this default as specified.
8495 @item ^-x^/READ_SOURCES=NONE^
8496 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8497 Exclude source files. In this mode, the binder only checks that ALI
8498 files are consistent with one another. Source files are not accessed.
8499 The binder runs faster in this mode, and there is still a guarantee that
8500 the resulting program is self-consistent.
8501 If a source file has been edited since it was last compiled, and you
8502 specify this switch, the binder will not detect that the object
8503 file is out of date with respect to the source file. Note that this is the
8504 mode that is automatically used by @command{gnatmake} because in this
8505 case the checking against sources has already been performed by
8506 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8508 @ifset vms
8509 @item /READ_SOURCES=AVAILABLE
8510 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8511 This is the default mode in which source files are checked if they are
8512 available, and ignored if they are not available.
8513 @end ifset
8514 @end table
8516 @node Binder Error Message Control
8517 @subsection Binder Error Message Control
8519 @noindent
8520 The following switches provide control over the generation of error
8521 messages from the binder:
8523 @table @option
8524 @c !sort!
8525 @item ^-v^/REPORT_ERRORS=VERBOSE^
8526 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8527 Verbose mode. In the normal mode, brief error messages are generated to
8528 @file{stderr}. If this switch is present, a header is written
8529 to @file{stdout} and any error messages are directed to @file{stdout}.
8530 All that is written to @file{stderr} is a brief summary message.
8532 @item ^-b^/REPORT_ERRORS=BRIEF^
8533 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8534 Generate brief error messages to @file{stderr} even if verbose mode is
8535 specified. This is relevant only when used with the
8536 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8538 @ifclear vms
8539 @item -m@var{n}
8540 @cindex @option{-m} (@code{gnatbind})
8541 Limits the number of error messages to @var{n}, a decimal integer in the
8542 range 1-999. The binder terminates immediately if this limit is reached.
8544 @item -M@var{xxx}
8545 @cindex @option{-M} (@code{gnatbind})
8546 Renames the generated main program from @code{main} to @code{xxx}.
8547 This is useful in the case of some cross-building environments, where
8548 the actual main program is separate from the one generated
8549 by @code{gnatbind}.
8550 @end ifclear
8552 @item ^-ws^/WARNINGS=SUPPRESS^
8553 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8554 @cindex Warnings
8555 Suppress all warning messages.
8557 @item ^-we^/WARNINGS=ERROR^
8558 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8559 Treat any warning messages as fatal errors.
8561 @ifset vms
8562 @item /WARNINGS=NORMAL
8563 Standard mode with warnings generated, but warnings do not get treated
8564 as errors.
8565 @end ifset
8567 @item ^-t^/NOTIME_STAMP_CHECK^
8568 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8569 @cindex Time stamp checks, in binder
8570 @cindex Binder consistency checks
8571 @cindex Consistency checks, in binder
8572 The binder performs a number of consistency checks including:
8574 @itemize @bullet
8575 @item
8576 Check that time stamps of a given source unit are consistent
8577 @item
8578 Check that checksums of a given source unit are consistent
8579 @item
8580 Check that consistent versions of @code{GNAT} were used for compilation
8581 @item
8582 Check consistency of configuration pragmas as required
8583 @end itemize
8585 @noindent
8586 Normally failure of such checks, in accordance with the consistency
8587 requirements of the Ada Reference Manual, causes error messages to be
8588 generated which abort the binder and prevent the output of a binder
8589 file and subsequent link to obtain an executable.
8591 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8592 into warnings, so that
8593 binding and linking can continue to completion even in the presence of such
8594 errors. The result may be a failed link (due to missing symbols), or a
8595 non-functional executable which has undefined semantics.
8596 @emph{This means that
8597 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8598 with extreme care.}
8599 @end table
8601 @node Elaboration Control
8602 @subsection Elaboration Control
8604 @noindent
8605 The following switches provide additional control over the elaboration
8606 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8608 @table @option
8609 @item ^-p^/PESSIMISTIC_ELABORATION^
8610 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8611 Normally the binder attempts to choose an elaboration order that is
8612 likely to minimize the likelihood of an elaboration order error resulting
8613 in raising a @code{Program_Error} exception. This switch reverses the
8614 action of the binder, and requests that it deliberately choose an order
8615 that is likely to maximize the likelihood of an elaboration error.
8616 This is useful in ensuring portability and avoiding dependence on
8617 accidental fortuitous elaboration ordering.
8619 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8620 switch if dynamic
8621 elaboration checking is used (@option{-gnatE} switch used for compilation).
8622 This is because in the default static elaboration mode, all necessary
8623 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8624 These implicit pragmas are still respected by the binder in
8625 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8626 safe elaboration order is assured.
8628 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8629 production use; it is more for debugging/experimental use.
8630 @end table
8632 @node Output Control
8633 @subsection Output Control
8635 @noindent
8636 The following switches allow additional control over the output
8637 generated by the binder.
8639 @table @option
8640 @c !sort!
8642 @item ^-c^/NOOUTPUT^
8643 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8644 Check only. Do not generate the binder output file. In this mode the
8645 binder performs all error checks but does not generate an output file.
8647 @item ^-e^/ELABORATION_DEPENDENCIES^
8648 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8649 Output complete list of elaboration-order dependencies, showing the
8650 reason for each dependency. This output can be rather extensive but may
8651 be useful in diagnosing problems with elaboration order. The output is
8652 written to @file{stdout}.
8654 @item ^-h^/HELP^
8655 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8656 Output usage information. The output is written to @file{stdout}.
8658 @item ^-K^/LINKER_OPTION_LIST^
8659 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8660 Output linker options to @file{stdout}. Includes library search paths,
8661 contents of pragmas Ident and Linker_Options, and libraries added
8662 by @code{gnatbind}.
8664 @item ^-l^/ORDER_OF_ELABORATION^
8665 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8666 Output chosen elaboration order. The output is written to @file{stdout}.
8668 @item ^-O^/OBJECT_LIST^
8669 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8670 Output full names of all the object files that must be linked to provide
8671 the Ada component of the program. The output is written to @file{stdout}.
8672 This list includes the files explicitly supplied and referenced by the user
8673 as well as implicitly referenced run-time unit files. The latter are
8674 omitted if the corresponding units reside in shared libraries. The
8675 directory names for the run-time units depend on the system configuration.
8677 @item ^-o ^/OUTPUT=^@var{file}
8678 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8679 Set name of output file to @var{file} instead of the normal
8680 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8681 binder generated body filename.
8682 Note that if this option is used, then linking must be done manually.
8683 It is not possible to use gnatlink in this case, since it cannot locate
8684 the binder file.
8686 @item ^-r^/RESTRICTION_LIST^
8687 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8688 Generate list of @code{pragma Restrictions} that could be applied to
8689 the current unit. This is useful for code audit purposes, and also may
8690 be used to improve code generation in some cases.
8692 @end table
8694 @node Dynamic Allocation Control
8695 @subsection Dynamic Allocation Control
8697 @noindent
8698 The heap control switches -- @option{-H32} and @option{-H64} --
8699 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8700 They only affect compiler-generated allocations via @code{__gnat_malloc};
8701 explicit calls to @code{malloc} and related functions from the C
8702 run-time library are unaffected.
8704 @table @option
8705 @item -H32
8706 Allocate memory on 32-bit heap
8708 @item -H64
8709 Allocate memory on 64-bit heap.  This is the default
8710 unless explicitly overridden by a @code{'Size} clause on the access type.
8711 @end table
8713 @ifset vms
8714 @noindent
8715 See also @ref{Access types and 32/64-bit allocation}.
8716 @end ifset
8717 @ifclear vms
8718 @noindent
8719 These switches are only effective on VMS platforms.
8720 @end ifclear
8723 @node Binding with Non-Ada Main Programs
8724 @subsection Binding with Non-Ada Main Programs
8726 @noindent
8727 In our description so far we have assumed that the main
8728 program is in Ada, and that the task of the binder is to generate a
8729 corresponding function @code{main} that invokes this Ada main
8730 program. GNAT also supports the building of executable programs where
8731 the main program is not in Ada, but some of the called routines are
8732 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8733 The following switch is used in this situation:
8735 @table @option
8736 @item ^-n^/NOMAIN^
8737 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8738 No main program. The main program is not in Ada.
8739 @end table
8741 @noindent
8742 In this case, most of the functions of the binder are still required,
8743 but instead of generating a main program, the binder generates a file
8744 containing the following callable routines:
8746 @table @code
8747 @item adainit
8748 @findex adainit
8749 You must call this routine to initialize the Ada part of the program by
8750 calling the necessary elaboration routines. A call to @code{adainit} is
8751 required before the first call to an Ada subprogram.
8753 Note that it is assumed that the basic execution environment must be setup
8754 to be appropriate for Ada execution at the point where the first Ada
8755 subprogram is called. In particular, if the Ada code will do any
8756 floating-point operations, then the FPU must be setup in an appropriate
8757 manner. For the case of the x86, for example, full precision mode is
8758 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8759 that the FPU is in the right state.
8761 @item adafinal
8762 @findex adafinal
8763 You must call this routine to perform any library-level finalization
8764 required by the Ada subprograms. A call to @code{adafinal} is required
8765 after the last call to an Ada subprogram, and before the program
8766 terminates.
8767 @end table
8769 @noindent
8770 If the @option{^-n^/NOMAIN^} switch
8771 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8772 @cindex Binder, multiple input files
8773 is given, more than one ALI file may appear on
8774 the command line for @code{gnatbind}. The normal @dfn{closure}
8775 calculation is performed for each of the specified units. Calculating
8776 the closure means finding out the set of units involved by tracing
8777 @code{with} references. The reason it is necessary to be able to
8778 specify more than one ALI file is that a given program may invoke two or
8779 more quite separate groups of Ada units.
8781 The binder takes the name of its output file from the last specified ALI
8782 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8783 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8784 The output is an Ada unit in source form that can be compiled with GNAT.
8785 This compilation occurs automatically as part of the @command{gnatlink}
8786 processing.
8788 Currently the GNAT run time requires a FPU using 80 bits mode
8789 precision. Under targets where this is not the default it is required to
8790 call GNAT.Float_Control.Reset before using floating point numbers (this
8791 include float computation, float input and output) in the Ada code. A
8792 side effect is that this could be the wrong mode for the foreign code
8793 where floating point computation could be broken after this call.
8795 @node Binding Programs with No Main Subprogram
8796 @subsection Binding Programs with No Main Subprogram
8798 @noindent
8799 It is possible to have an Ada program which does not have a main
8800 subprogram. This program will call the elaboration routines of all the
8801 packages, then the finalization routines.
8803 The following switch is used to bind programs organized in this manner:
8805 @table @option
8806 @item ^-z^/ZERO_MAIN^
8807 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8808 Normally the binder checks that the unit name given on the command line
8809 corresponds to a suitable main subprogram. When this switch is used,
8810 a list of ALI files can be given, and the execution of the program
8811 consists of elaboration of these units in an appropriate order. Note
8812 that the default wide character encoding method for standard Text_IO
8813 files is always set to Brackets if this switch is set (you can use
8814 the binder switch
8815 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8816 @end table
8818 @node Command-Line Access
8819 @section Command-Line Access
8821 @noindent
8822 The package @code{Ada.Command_Line} provides access to the command-line
8823 arguments and program name. In order for this interface to operate
8824 correctly, the two variables
8826 @smallexample
8827 @group
8828 int gnat_argc;
8829 char **gnat_argv;
8830 @end group
8831 @end smallexample
8833 @noindent
8834 @findex gnat_argv
8835 @findex gnat_argc
8836 are declared in one of the GNAT library routines. These variables must
8837 be set from the actual @code{argc} and @code{argv} values passed to the
8838 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8839 generates the C main program to automatically set these variables.
8840 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8841 set these variables. If they are not set, the procedures in
8842 @code{Ada.Command_Line} will not be available, and any attempt to use
8843 them will raise @code{Constraint_Error}. If command line access is
8844 required, your main program must set @code{gnat_argc} and
8845 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8848 @node Search Paths for gnatbind
8849 @section Search Paths for @code{gnatbind}
8851 @noindent
8852 The binder takes the name of an ALI file as its argument and needs to
8853 locate source files as well as other ALI files to verify object consistency.
8855 For source files, it follows exactly the same search rules as @command{gcc}
8856 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8857 directories searched are:
8859 @enumerate
8860 @item
8861 The directory containing the ALI file named in the command line, unless
8862 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8864 @item
8865 All directories specified by @option{^-I^/SEARCH^}
8866 switches on the @code{gnatbind}
8867 command line, in the order given.
8869 @item
8870 @findex ADA_PRJ_OBJECTS_FILE
8871 Each of the directories listed in the text file whose name is given
8872 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8874 @noindent
8875 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8876 driver when project files are used. It should not normally be set
8877 by other means.
8879 @item
8880 @findex ADA_OBJECTS_PATH
8881 Each of the directories listed in the value of the
8882 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8883 @ifset unw
8884 Construct this value
8885 exactly as the @env{PATH} environment variable: a list of directory
8886 names separated by colons (semicolons when working with the NT version
8887 of GNAT).
8888 @end ifset
8889 @ifset vms
8890 Normally, define this value as a logical name containing a comma separated
8891 list of directory names.
8893 This variable can also be defined by means of an environment string
8894 (an argument to the HP C exec* set of functions).
8896 Logical Name:
8897 @smallexample
8898 DEFINE ANOTHER_PATH FOO:[BAG]
8899 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8900 @end smallexample
8902 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8903 first, followed by the standard Ada
8904 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8905 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8906 (Text_IO, Sequential_IO, etc)
8907 instead of the standard Ada packages. Thus, in order to get the standard Ada
8908 packages by default, ADA_OBJECTS_PATH must be redefined.
8909 @end ifset
8911 @item
8912 The content of the @file{ada_object_path} file which is part of the GNAT
8913 installation tree and is used to store standard libraries such as the
8914 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8915 specified.
8916 @ifclear vms
8917 @ref{Installing a library}
8918 @end ifclear
8919 @end enumerate
8921 @noindent
8922 In the binder the switch @option{^-I^/SEARCH^}
8923 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8924 is used to specify both source and
8925 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8926 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8927 instead if you want to specify
8928 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8929 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8930 if you want to specify library paths
8931 only. This means that for the binder
8932 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8933 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8934 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8935 The binder generates the bind file (a C language source file) in the
8936 current working directory.
8938 @findex Ada
8939 @findex System
8940 @findex Interfaces
8941 @findex GNAT
8942 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8943 children make up the GNAT Run-Time Library, together with the package
8944 GNAT and its children, which contain a set of useful additional
8945 library functions provided by GNAT. The sources for these units are
8946 needed by the compiler and are kept together in one directory. The ALI
8947 files and object files generated by compiling the RTL are needed by the
8948 binder and the linker and are kept together in one directory, typically
8949 different from the directory containing the sources. In a normal
8950 installation, you need not specify these directory names when compiling
8951 or binding. Either the environment variables or the built-in defaults
8952 cause these files to be found.
8954 Besides simplifying access to the RTL, a major use of search paths is
8955 in compiling sources from multiple directories. This can make
8956 development environments much more flexible.
8958 @node Examples of gnatbind Usage
8959 @section Examples of @code{gnatbind} Usage
8961 @noindent
8962 This section contains a number of examples of using the GNAT binding
8963 utility @code{gnatbind}.
8965 @table @code
8966 @item gnatbind hello
8967 The main program @code{Hello} (source program in @file{hello.adb}) is
8968 bound using the standard switch settings. The generated main program is
8969 @file{b~hello.adb}. This is the normal, default use of the binder.
8971 @ifclear vms
8972 @item gnatbind hello -o mainprog.adb
8973 @end ifclear
8974 @ifset vms
8975 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8976 @end ifset
8977 The main program @code{Hello} (source program in @file{hello.adb}) is
8978 bound using the standard switch settings. The generated main program is
8979 @file{mainprog.adb} with the associated spec in
8980 @file{mainprog.ads}. Note that you must specify the body here not the
8981 spec. Note that if this option is used, then linking must be done manually,
8982 since gnatlink will not be able to find the generated file.
8983 @end table
8985 @c ------------------------------------
8986 @node Linking with gnatlink
8987 @chapter Linking with @command{gnatlink}
8988 @c ------------------------------------
8989 @findex gnatlink
8991 @noindent
8992 This chapter discusses @command{gnatlink}, a tool that links
8993 an Ada program and builds an executable file. This utility
8994 invokes the system linker ^(via the @command{gcc} command)^^
8995 with a correct list of object files and library references.
8996 @command{gnatlink} automatically determines the list of files and
8997 references for the Ada part of a program. It uses the binder file
8998 generated by the @command{gnatbind} to determine this list.
9000 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9001 driver (see @ref{The GNAT Driver and Project Files}).
9003 @menu
9004 * Running gnatlink::
9005 * Switches for gnatlink::
9006 @end menu
9008 @node Running gnatlink
9009 @section Running @command{gnatlink}
9011 @noindent
9012 The form of the @command{gnatlink} command is
9014 @smallexample
9015 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9016 @c            @ovar{non-Ada objects} @ovar{linker options}
9017 @c Expanding @ovar macro inline (explanation in macro def comments)
9018 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9019            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9021 @end smallexample
9023 @noindent
9024 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9025 non-Ada objects
9026 or linker options) may be in any order, provided that no non-Ada object may
9027 be mistaken for a main @file{ALI} file.
9028 Any file name @file{F} without the @file{.ali}
9029 extension will be taken as the main @file{ALI} file if a file exists
9030 whose name is the concatenation of @file{F} and @file{.ali}.
9032 @noindent
9033 @file{@var{mainprog}.ali} references the ALI file of the main program.
9034 The @file{.ali} extension of this file can be omitted. From this
9035 reference, @command{gnatlink} locates the corresponding binder file
9036 @file{b~@var{mainprog}.adb} and, using the information in this file along
9037 with the list of non-Ada objects and linker options, constructs a
9038 linker command file to create the executable.
9040 The arguments other than the @command{gnatlink} switches and the main
9041 @file{ALI} file are passed to the linker uninterpreted.
9042 They typically include the names of
9043 object files for units written in other languages than Ada and any library
9044 references required to resolve references in any of these foreign language
9045 units, or in @code{Import} pragmas in any Ada units.
9047 @var{linker options} is an optional list of linker specific
9048 switches.
9049 The default linker called by gnatlink is @command{gcc} which in
9050 turn calls the appropriate system linker.
9052 One useful option for the linker is @option{-s}: it reduces the size of the
9053 executable by removing all symbol table and relocation information from the
9054 executable.
9056 Standard options for the linker such as @option{-lmy_lib} or
9057 @option{-Ldir} can be added as is.
9058 For options that are not recognized by
9059 @command{gcc} as linker options, use the @command{gcc} switches
9060 @option{-Xlinker} or @option{-Wl,}.
9062 Refer to the GCC documentation for
9063 details.
9065 Here is an example showing how to generate a linker map:
9067 @smallexample
9068 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9069 @end smallexample
9071 Using @var{linker options} it is possible to set the program stack and
9072 heap size.
9073 @ifset unw
9074 See @ref{Setting Stack Size from gnatlink} and
9075 @ref{Setting Heap Size from gnatlink}.
9076 @end ifset
9078 @command{gnatlink} determines the list of objects required by the Ada
9079 program and prepends them to the list of objects passed to the linker.
9080 @command{gnatlink} also gathers any arguments set by the use of
9081 @code{pragma Linker_Options} and adds them to the list of arguments
9082 presented to the linker.
9084 @ifset vms
9085 @command{gnatlink} accepts the following types of extra files on the command
9086 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9087 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9088 handled according to their extension.
9089 @end ifset
9091 @node Switches for gnatlink
9092 @section Switches for @command{gnatlink}
9094 @noindent
9095 The following switches are available with the @command{gnatlink} utility:
9097 @table @option
9098 @c !sort!
9100 @item --version
9101 @cindex @option{--version} @command{gnatlink}
9102 Display Copyright and version, then exit disregarding all other options.
9104 @item --help
9105 @cindex @option{--help} @command{gnatlink}
9106 If @option{--version} was not used, display usage, then exit disregarding
9107 all other options.
9109 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9110 @cindex Command line length
9111 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9112 On some targets, the command line length is limited, and @command{gnatlink}
9113 will generate a separate file for the linker if the list of object files
9114 is too long.
9115 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9116 to be generated even if
9117 the limit is not exceeded. This is useful in some cases to deal with
9118 special situations where the command line length is exceeded.
9120 @item ^-g^/DEBUG^
9121 @cindex Debugging information, including
9122 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9123 The option to include debugging information causes the Ada bind file (in
9124 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9125 @option{^-g^/DEBUG^}.
9126 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9127 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9128 Without @option{^-g^/DEBUG^}, the binder removes these files by
9129 default. The same procedure apply if a C bind file was generated using
9130 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9131 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9133 @item ^-n^/NOCOMPILE^
9134 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9135 Do not compile the file generated by the binder. This may be used when
9136 a link is rerun with different options, but there is no need to recompile
9137 the binder file.
9139 @item ^-v^/VERBOSE^
9140 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9141 Causes additional information to be output, including a full list of the
9142 included object files. This switch option is most useful when you want
9143 to see what set of object files are being used in the link step.
9145 @item ^-v -v^/VERBOSE/VERBOSE^
9146 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9147 Very verbose mode. Requests that the compiler operate in verbose mode when
9148 it compiles the binder file, and that the system linker run in verbose mode.
9150 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9151 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9152 @var{exec-name} specifies an alternate name for the generated
9153 executable program. If this switch is omitted, the executable has the same
9154 name as the main unit. For example, @code{gnatlink try.ali} creates
9155 an executable called @file{^try^TRY.EXE^}.
9157 @ifclear vms
9158 @item -b @var{target}
9159 @cindex @option{-b} (@command{gnatlink})
9160 Compile your program to run on @var{target}, which is the name of a
9161 system configuration. You must have a GNAT cross-compiler built if
9162 @var{target} is not the same as your host system.
9164 @item -B@var{dir}
9165 @cindex @option{-B} (@command{gnatlink})
9166 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9167 from @var{dir} instead of the default location. Only use this switch
9168 when multiple versions of the GNAT compiler are available.
9169 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9170 for further details. You would normally use the @option{-b} or
9171 @option{-V} switch instead.
9173 @item -M
9174 When linking an executable, create a map file. The name of the map file
9175 has the same name as the executable with extension ".map".
9177 @item -M=mapfile
9178 When linking an executable, create a map file. The name of the map file is
9179 "mapfile".
9181 @item --GCC=@var{compiler_name}
9182 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9183 Program used for compiling the binder file. The default is
9184 @command{gcc}. You need to use quotes around @var{compiler_name} if
9185 @code{compiler_name} contains spaces or other separator characters.
9186 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9187 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9188 inserted after your command name. Thus in the above example the compiler
9189 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9190 A limitation of this syntax is that the name and path name of the executable
9191 itself must not include any embedded spaces. If the compiler executable is
9192 different from the default one (gcc or <prefix>-gcc), then the back-end
9193 switches in the ALI file are not used to compile the binder generated source.
9194 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9195 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9196 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9197 is taken into account. However, all the additional switches are also taken
9198 into account. Thus,
9199 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9200 @option{--GCC="bar -x -y -z -t"}.
9202 @item --LINK=@var{name}
9203 @cindex @option{--LINK=} (@command{gnatlink})
9204 @var{name} is the name of the linker to be invoked. This is especially
9205 useful in mixed language programs since languages such as C++ require
9206 their own linker to be used. When this switch is omitted, the default
9207 name for the linker is @command{gcc}. When this switch is used, the
9208 specified linker is called instead of @command{gcc} with exactly the same
9209 parameters that would have been passed to @command{gcc} so if the desired
9210 linker requires different parameters it is necessary to use a wrapper
9211 script that massages the parameters before invoking the real linker. It
9212 may be useful to control the exact invocation by using the verbose
9213 switch.
9215 @end ifclear
9217 @ifset vms
9218 @item /DEBUG=TRACEBACK
9219 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9220 This qualifier causes sufficient information to be included in the
9221 executable file to allow a traceback, but does not include the full
9222 symbol information needed by the debugger.
9224 @item /IDENTIFICATION="<string>"
9225 @code{"<string>"} specifies the string to be stored in the image file
9226 identification field in the image header.
9227 It overrides any pragma @code{Ident} specified string.
9229 @item /NOINHIBIT-EXEC
9230 Generate the executable file even if there are linker warnings.
9232 @item /NOSTART_FILES
9233 Don't link in the object file containing the ``main'' transfer address.
9234 Used when linking with a foreign language main program compiled with an
9235 HP compiler.
9237 @item /STATIC
9238 Prefer linking with object libraries over sharable images, even without
9239 /DEBUG.
9240 @end ifset
9242 @end table
9244 @node The GNAT Make Program gnatmake
9245 @chapter The GNAT Make Program @command{gnatmake}
9246 @findex gnatmake
9248 @menu
9249 * Running gnatmake::
9250 * Switches for gnatmake::
9251 * Mode Switches for gnatmake::
9252 * Notes on the Command Line::
9253 * How gnatmake Works::
9254 * Examples of gnatmake Usage::
9255 @end menu
9256 @noindent
9257 A typical development cycle when working on an Ada program consists of
9258 the following steps:
9260 @enumerate
9261 @item
9262 Edit some sources to fix bugs.
9264 @item
9265 Add enhancements.
9267 @item
9268 Compile all sources affected.
9270 @item
9271 Rebind and relink.
9273 @item
9274 Test.
9275 @end enumerate
9277 @noindent
9278 The third step can be tricky, because not only do the modified files
9279 @cindex Dependency rules
9280 have to be compiled, but any files depending on these files must also be
9281 recompiled. The dependency rules in Ada can be quite complex, especially
9282 in the presence of overloading, @code{use} clauses, generics and inlined
9283 subprograms.
9285 @command{gnatmake} automatically takes care of the third and fourth steps
9286 of this process. It determines which sources need to be compiled,
9287 compiles them, and binds and links the resulting object files.
9289 Unlike some other Ada make programs, the dependencies are always
9290 accurately recomputed from the new sources. The source based approach of
9291 the GNAT compilation model makes this possible. This means that if
9292 changes to the source program cause corresponding changes in
9293 dependencies, they will always be tracked exactly correctly by
9294 @command{gnatmake}.
9296 @node Running gnatmake
9297 @section Running @command{gnatmake}
9299 @noindent
9300 The usual form of the @command{gnatmake} command is
9302 @smallexample
9303 @c $ gnatmake @ovar{switches} @var{file_name}
9304 @c       @ovar{file_names} @ovar{mode_switches}
9305 @c Expanding @ovar macro inline (explanation in macro def comments)
9306 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9307       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9308 @end smallexample
9310 @noindent
9311 The only required argument is one @var{file_name}, which specifies
9312 a compilation unit that is a main program. Several @var{file_names} can be
9313 specified: this will result in several executables being built.
9314 If @code{switches} are present, they can be placed before the first
9315 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9316 If @var{mode_switches} are present, they must always be placed after
9317 the last @var{file_name} and all @code{switches}.
9319 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9320 extension may be omitted from the @var{file_name} arguments. However, if
9321 you are using non-standard extensions, then it is required that the
9322 extension be given. A relative or absolute directory path can be
9323 specified in a @var{file_name}, in which case, the input source file will
9324 be searched for in the specified directory only. Otherwise, the input
9325 source file will first be searched in the directory where
9326 @command{gnatmake} was invoked and if it is not found, it will be search on
9327 the source path of the compiler as described in
9328 @ref{Search Paths and the Run-Time Library (RTL)}.
9330 All @command{gnatmake} output (except when you specify
9331 @option{^-M^/DEPENDENCIES_LIST^}) is to
9332 @file{stderr}. The output produced by the
9333 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9334 @file{stdout}.
9336 @node Switches for gnatmake
9337 @section Switches for @command{gnatmake}
9339 @noindent
9340 You may specify any of the following switches to @command{gnatmake}:
9342 @table @option
9343 @c !sort!
9345 @item --version
9346 @cindex @option{--version} @command{gnatmake}
9347 Display Copyright and version, then exit disregarding all other options.
9349 @item --help
9350 @cindex @option{--help} @command{gnatmake}
9351 If @option{--version} was not used, display usage, then exit disregarding
9352 all other options.
9354 @ifclear vms
9355 @item --GCC=@var{compiler_name}
9356 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9357 Program used for compiling. The default is `@command{gcc}'. You need to use
9358 quotes around @var{compiler_name} if @code{compiler_name} contains
9359 spaces or other separator characters. As an example @option{--GCC="foo -x
9360 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9361 compiler. A limitation of this syntax is that the name and path name of
9362 the executable itself must not include any embedded spaces. Note that
9363 switch @option{-c} is always inserted after your command name. Thus in the
9364 above example the compiler command that will be used by @command{gnatmake}
9365 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9366 used, only the last @var{compiler_name} is taken into account. However,
9367 all the additional switches are also taken into account. Thus,
9368 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9369 @option{--GCC="bar -x -y -z -t"}.
9371 @item --GNATBIND=@var{binder_name}
9372 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9373 Program used for binding. The default is `@code{gnatbind}'. You need to
9374 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9375 or other separator characters. As an example @option{--GNATBIND="bar -x
9376 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9377 binder. Binder switches that are normally appended by @command{gnatmake}
9378 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9379 A limitation of this syntax is that the name and path name of the executable
9380 itself must not include any embedded spaces.
9382 @item --GNATLINK=@var{linker_name}
9383 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9384 Program used for linking. The default is `@command{gnatlink}'. You need to
9385 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9386 or other separator characters. As an example @option{--GNATLINK="lan -x
9387 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9388 linker. Linker switches that are normally appended by @command{gnatmake} to
9389 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9390 A limitation of this syntax is that the name and path name of the executable
9391 itself must not include any embedded spaces.
9393 @end ifclear
9395 @item ^--subdirs^/SUBDIRS^=subdir
9396 Actual object directory of each project file is the subdirectory subdir of the
9397 object directory specified or defaulted in the project file.
9399 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9400 Disallow simultaneous compilations in the same object directory when
9401 project files are used.
9403 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9404 By default, shared library projects are not allowed to import static library
9405 projects. When this switch is used on the command line, this restriction is
9406 relaxed.
9408 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9409 Specify a source info file. This switch is active only when project files
9410 are used. If the source info file is specified as a relative path, then it is
9411 relative to the object directory of the main project. If the source info file
9412 does not exist, then after the Project Manager has successfully parsed and
9413 processed the project files and found the sources, it creates the source info
9414 file. If the source info file already exists and can be read successfully,
9415 then the Project Manager will get all the needed information about the sources
9416 from the source info file and will not look for them. This reduces the time
9417 to process the project files, especially when looking for sources that take a
9418 long time. If the source info file exists but cannot be parsed successfully,
9419 the Project Manager will attempt to recreate it. If the Project Manager fails
9420 to create the source info file, a message is issued, but gnatmake does not
9421 fail. @command{gnatmake} "trusts" the source info file. This means that
9422 if the source files have changed (addition, deletion, moving to a different
9423 source directory), then the source info file need to be deleted and recreated.
9425 @ifclear vms
9426 @item --create-map-file
9427 When linking an executable, create a map file. The name of the map file
9428 has the same name as the executable with extension ".map".
9430 @item --create-map-file=mapfile
9431 When linking an executable, create a map file. The name of the map file is
9432 "mapfile".
9434 @end ifclear
9436 @item ^-a^/ALL_FILES^
9437 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9438 Consider all files in the make process, even the GNAT internal system
9439 files (for example, the predefined Ada library files), as well as any
9440 locked files. Locked files are files whose ALI file is write-protected.
9441 By default,
9442 @command{gnatmake} does not check these files,
9443 because the assumption is that the GNAT internal files are properly up
9444 to date, and also that any write protected ALI files have been properly
9445 installed. Note that if there is an installation problem, such that one
9446 of these files is not up to date, it will be properly caught by the
9447 binder.
9448 You may have to specify this switch if you are working on GNAT
9449 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9450 in conjunction with @option{^-f^/FORCE_COMPILE^}
9451 if you need to recompile an entire application,
9452 including run-time files, using special configuration pragmas,
9453 such as a @code{Normalize_Scalars} pragma.
9455 By default
9456 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9457 internal files with
9458 @ifclear vms
9459 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9460 @end ifclear
9461 @ifset vms
9462 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9463 @end ifset
9465 @item ^-b^/ACTIONS=BIND^
9466 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9467 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9468 compilation and binding, but no link.
9469 Can be combined with @option{^-l^/ACTIONS=LINK^}
9470 to do binding and linking. When not combined with
9471 @option{^-c^/ACTIONS=COMPILE^}
9472 all the units in the closure of the main program must have been previously
9473 compiled and must be up to date. The root unit specified by @var{file_name}
9474 may be given without extension, with the source extension or, if no GNAT
9475 Project File is specified, with the ALI file extension.
9477 @item ^-c^/ACTIONS=COMPILE^
9478 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9479 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9480 is also specified. Do not perform linking, except if both
9481 @option{^-b^/ACTIONS=BIND^} and
9482 @option{^-l^/ACTIONS=LINK^} are also specified.
9483 If the root unit specified by @var{file_name} is not a main unit, this is the
9484 default. Otherwise @command{gnatmake} will attempt binding and linking
9485 unless all objects are up to date and the executable is more recent than
9486 the objects.
9488 @item ^-C^/MAPPING^
9489 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9490 Use a temporary mapping file. A mapping file is a way to communicate
9491 to the compiler two mappings: from unit names to file names (without
9492 any directory information) and from file names to path names (with
9493 full directory information). A mapping file can make the compiler's
9494 file searches faster, especially if there are many source directories,
9495 or the sources are read over a slow network connection. If
9496 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9497 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9498 is initially populated based on the project file. If
9499 @option{^-C^/MAPPING^} is used without
9500 @option{^-P^/PROJECT_FILE^},
9501 the mapping file is initially empty. Each invocation of the compiler
9502 will add any newly accessed sources to the mapping file.
9504 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9505 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9506 Use a specific mapping file. The file, specified as a path name (absolute or
9507 relative) by this switch, should already exist, otherwise the switch is
9508 ineffective. The specified mapping file will be communicated to the compiler.
9509 This switch is not compatible with a project file
9510 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9511 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9513 @item ^-d^/DISPLAY_PROGRESS^
9514 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9515 Display progress for each source, up to date or not, as a single line
9517 @smallexample
9518 completed x out of y (zz%)
9519 @end smallexample
9521 If the file needs to be compiled this is displayed after the invocation of
9522 the compiler. These lines are displayed even in quiet output mode.
9524 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9525 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9526 Put all object files and ALI file in directory @var{dir}.
9527 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9528 and ALI files go in the current working directory.
9530 This switch cannot be used when using a project file.
9532 @item -eInnn
9533 @cindex @option{-eI} (@command{gnatmake})
9534 Indicates that the main source is a multi-unit source and the rank of the unit
9535 in the source file is nnn. nnn needs to be a positive number and a valid
9536 index in the source. This switch cannot be used when @command{gnatmake} is
9537 invoked for several mains.
9539 @ifclear vms
9540 @item -eL
9541 @cindex @option{-eL} (@command{gnatmake})
9542 @cindex symbolic links
9543 Follow all symbolic links when processing project files.
9544 This should be used if your project uses symbolic links for files or
9545 directories, but is not needed in other cases.
9547 @cindex naming scheme
9548 This also assumes that no directory matches the naming scheme for files (for
9549 instance that you do not have a directory called "sources.ads" when using the
9550 default GNAT naming scheme).
9552 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9553 save a lot of system calls (several per source file and object file), which
9554 can result in a significant speed up to load and manipulate a project file,
9555 especially when using source files from a remote system.
9557 @end ifclear
9559 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9560 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9561 Output the commands for the compiler, the binder and the linker
9562 on ^standard output^SYS$OUTPUT^,
9563 instead of ^standard error^SYS$ERROR^.
9565 @item ^-f^/FORCE_COMPILE^
9566 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9567 Force recompilations. Recompile all sources, even though some object
9568 files may be up to date, but don't recompile predefined or GNAT internal
9569 files or locked files (files with a write-protected ALI file),
9570 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9572 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9573 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9574 When using project files, if some errors or warnings are detected during
9575 parsing and verbose mode is not in effect (no use of switch
9576 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9577 file, rather than its simple file name.
9579 @item ^-g^/DEBUG^
9580 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9581 Enable debugging. This switch is simply passed to the compiler and to the
9582 linker.
9584 @item ^-i^/IN_PLACE^
9585 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9586 In normal mode, @command{gnatmake} compiles all object files and ALI files
9587 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9588 then instead object files and ALI files that already exist are overwritten
9589 in place. This means that once a large project is organized into separate
9590 directories in the desired manner, then @command{gnatmake} will automatically
9591 maintain and update this organization. If no ALI files are found on the
9592 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9593 the new object and ALI files are created in the
9594 directory containing the source being compiled. If another organization
9595 is desired, where objects and sources are kept in different directories,
9596 a useful technique is to create dummy ALI files in the desired directories.
9597 When detecting such a dummy file, @command{gnatmake} will be forced to
9598 recompile the corresponding source file, and it will be put the resulting
9599 object and ALI files in the directory where it found the dummy file.
9601 @item ^-j^/PROCESSES=^@var{n}
9602 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9603 @cindex Parallel make
9604 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9605 machine compilations will occur in parallel. If @var{n} is 0, then the
9606 maximum number of parallel compilations is the number of core processors
9607 on the platform. In the event of compilation errors, messages from various
9608 compilations might get interspersed (but @command{gnatmake} will give you the
9609 full ordered list of failing compiles at the end). If this is problematic,
9610 rerun the make process with n set to 1 to get a clean list of messages.
9612 @item ^-k^/CONTINUE_ON_ERROR^
9613 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9614 Keep going. Continue as much as possible after a compilation error. To
9615 ease the programmer's task in case of compilation errors, the list of
9616 sources for which the compile fails is given when @command{gnatmake}
9617 terminates.
9619 If @command{gnatmake} is invoked with several @file{file_names} and with this
9620 switch, if there are compilation errors when building an executable,
9621 @command{gnatmake} will not attempt to build the following executables.
9623 @item ^-l^/ACTIONS=LINK^
9624 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9625 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9626 and linking. Linking will not be performed if combined with
9627 @option{^-c^/ACTIONS=COMPILE^}
9628 but not with @option{^-b^/ACTIONS=BIND^}.
9629 When not combined with @option{^-b^/ACTIONS=BIND^}
9630 all the units in the closure of the main program must have been previously
9631 compiled and must be up to date, and the main program needs to have been bound.
9632 The root unit specified by @var{file_name}
9633 may be given without extension, with the source extension or, if no GNAT
9634 Project File is specified, with the ALI file extension.
9636 @item ^-m^/MINIMAL_RECOMPILATION^
9637 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9638 Specify that the minimum necessary amount of recompilations
9639 be performed. In this mode @command{gnatmake} ignores time
9640 stamp differences when the only
9641 modifications to a source file consist in adding/removing comments,
9642 empty lines, spaces or tabs. This means that if you have changed the
9643 comments in a source file or have simply reformatted it, using this
9644 switch will tell @command{gnatmake} not to recompile files that depend on it
9645 (provided other sources on which these files depend have undergone no
9646 semantic modifications). Note that the debugging information may be
9647 out of date with respect to the sources if the @option{-m} switch causes
9648 a compilation to be switched, so the use of this switch represents a
9649 trade-off between compilation time and accurate debugging information.
9651 @item ^-M^/DEPENDENCIES_LIST^
9652 @cindex Dependencies, producing list
9653 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9654 Check if all objects are up to date. If they are, output the object
9655 dependences to @file{stdout} in a form that can be directly exploited in
9656 a @file{Makefile}. By default, each source file is prefixed with its
9657 (relative or absolute) directory name. This name is whatever you
9658 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9659 and @option{^-I^/SEARCH^} switches. If you use
9660 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9661 @option{^-q^/QUIET^}
9662 (see below), only the source file names,
9663 without relative paths, are output. If you just specify the
9664 @option{^-M^/DEPENDENCIES_LIST^}
9665 switch, dependencies of the GNAT internal system files are omitted. This
9666 is typically what you want. If you also specify
9667 the @option{^-a^/ALL_FILES^} switch,
9668 dependencies of the GNAT internal files are also listed. Note that
9669 dependencies of the objects in external Ada libraries (see switch
9670 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9671 are never reported.
9673 @item ^-n^/DO_OBJECT_CHECK^
9674 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9675 Don't compile, bind, or link. Checks if all objects are up to date.
9676 If they are not, the full name of the first file that needs to be
9677 recompiled is printed.
9678 Repeated use of this option, followed by compiling the indicated source
9679 file, will eventually result in recompiling all required units.
9681 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9682 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9683 Output executable name. The name of the final executable program will be
9684 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9685 name for the executable will be the name of the input file in appropriate form
9686 for an executable file on the host system.
9688 This switch cannot be used when invoking @command{gnatmake} with several
9689 @file{file_names}.
9691 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9692 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9693 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9694 automatically missing object directories, library directories and exec
9695 directories.
9697 @item ^-P^/PROJECT_FILE=^@var{project}
9698 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9699 Use project file @var{project}. Only one such switch can be used.
9700 @xref{gnatmake and Project Files}.
9702 @item ^-q^/QUIET^
9703 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9704 Quiet. When this flag is not set, the commands carried out by
9705 @command{gnatmake} are displayed.
9707 @item ^-s^/SWITCH_CHECK/^
9708 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9709 Recompile if compiler switches have changed since last compilation.
9710 All compiler switches but -I and -o are taken into account in the
9711 following way:
9712 orders between different ``first letter'' switches are ignored, but
9713 orders between same switches are taken into account. For example,
9714 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9715 is equivalent to @option{-O -g}.
9717 This switch is recommended when Integrated Preprocessing is used.
9719 @item ^-u^/UNIQUE^
9720 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9721 Unique. Recompile at most the main files. It implies -c. Combined with
9722 -f, it is equivalent to calling the compiler directly. Note that using
9723 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9724 (@pxref{Project Files and Main Subprograms}).
9726 @item ^-U^/ALL_PROJECTS^
9727 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9728 When used without a project file or with one or several mains on the command
9729 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9730 on the command line, all sources of all project files are checked and compiled
9731 if not up to date, and libraries are rebuilt, if necessary.
9733 @item ^-v^/REASONS^
9734 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9735 Verbose. Display the reason for all recompilations @command{gnatmake}
9736 decides are necessary, with the highest verbosity level.
9738 @item ^-vl^/LOW_VERBOSITY^
9739 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9740 Verbosity level Low. Display fewer lines than in verbosity Medium.
9742 @item ^-vm^/MEDIUM_VERBOSITY^
9743 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9744 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9746 @item ^-vh^/HIGH_VERBOSITY^
9747 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9748 Verbosity level High. Equivalent to ^-v^/REASONS^.
9750 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9751 Indicate the verbosity of the parsing of GNAT project files.
9752 @xref{Switches Related to Project Files}.
9754 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9755 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9756 Indicate that sources that are not part of any Project File may be compiled.
9757 Normally, when using Project Files, only sources that are part of a Project
9758 File may be compile. When this switch is used, a source outside of all Project
9759 Files may be compiled. The ALI file and the object file will be put in the
9760 object directory of the main Project. The compilation switches used will only
9761 be those specified on the command line. Even when
9762 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9763 command line need to be sources of a project file.
9765 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9766 Indicate that external variable @var{name} has the value @var{value}.
9767 The Project Manager will use this value for occurrences of
9768 @code{external(name)} when parsing the project file.
9769 @xref{Switches Related to Project Files}.
9771 @item ^-z^/NOMAIN^
9772 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9773 No main subprogram. Bind and link the program even if the unit name
9774 given on the command line is a package name. The resulting executable
9775 will execute the elaboration routines of the package and its closure,
9776 then the finalization routines.
9778 @end table
9780 @table @asis
9781 @item @command{gcc} @asis{switches}
9782 @ifclear vms
9783 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9784 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9785 @end ifclear
9786 @ifset vms
9787 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9788 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9789 automatically treated as a compiler switch, and passed on to all
9790 compilations that are carried out.
9791 @end ifset
9792 @end table
9794 @noindent
9795 Source and library search path switches:
9797 @table @option
9798 @c !sort!
9799 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9800 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9801 When looking for source files also look in directory @var{dir}.
9802 The order in which source files search is undertaken is
9803 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9805 @item ^-aL^/SKIP_MISSING=^@var{dir}
9806 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9807 Consider @var{dir} as being an externally provided Ada library.
9808 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9809 files have been located in directory @var{dir}. This allows you to have
9810 missing bodies for the units in @var{dir} and to ignore out of date bodies
9811 for the same units. You still need to specify
9812 the location of the specs for these units by using the switches
9813 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9814 or @option{^-I^/SEARCH=^@var{dir}}.
9815 Note: this switch is provided for compatibility with previous versions
9816 of @command{gnatmake}. The easier method of causing standard libraries
9817 to be excluded from consideration is to write-protect the corresponding
9818 ALI files.
9820 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9821 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9822 When searching for library and object files, look in directory
9823 @var{dir}. The order in which library files are searched is described in
9824 @ref{Search Paths for gnatbind}.
9826 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9827 @cindex Search paths, for @command{gnatmake}
9828 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9829 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9830 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9832 @item ^-I^/SEARCH=^@var{dir}
9833 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9834 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9835 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9837 @item ^-I-^/NOCURRENT_DIRECTORY^
9838 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9839 @cindex Source files, suppressing search
9840 Do not look for source files in the directory containing the source
9841 file named in the command line.
9842 Do not look for ALI or object files in the directory
9843 where @command{gnatmake} was invoked.
9845 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9846 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9847 @cindex Linker libraries
9848 Add directory @var{dir} to the list of directories in which the linker
9849 will search for libraries. This is equivalent to
9850 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9851 @ifclear vms
9852 Furthermore, under Windows, the sources pointed to by the libraries path
9853 set in the registry are not searched for.
9854 @end ifclear
9856 @item -nostdinc
9857 @cindex @option{-nostdinc} (@command{gnatmake})
9858 Do not look for source files in the system default directory.
9860 @item -nostdlib
9861 @cindex @option{-nostdlib} (@command{gnatmake})
9862 Do not look for library files in the system default directory.
9864 @item --RTS=@var{rts-path}
9865 @cindex @option{--RTS} (@command{gnatmake})
9866 Specifies the default location of the runtime library. GNAT looks for the
9867 runtime
9868 in the following directories, and stops as soon as a valid runtime is found
9869 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9870 @file{ada_object_path} present):
9872 @itemize @bullet
9873 @item <current directory>/$rts_path
9875 @item <default-search-dir>/$rts_path
9877 @item <default-search-dir>/rts-$rts_path
9878 @end itemize
9880 @noindent
9881 The selected path is handled like a normal RTS path.
9883 @end table
9885 @node Mode Switches for gnatmake
9886 @section Mode Switches for @command{gnatmake}
9888 @noindent
9889 The mode switches (referred to as @code{mode_switches}) allow the
9890 inclusion of switches that are to be passed to the compiler itself, the
9891 binder or the linker. The effect of a mode switch is to cause all
9892 subsequent switches up to the end of the switch list, or up to the next
9893 mode switch, to be interpreted as switches to be passed on to the
9894 designated component of GNAT.
9896 @table @option
9897 @c !sort!
9898 @item -cargs @var{switches}
9899 @cindex @option{-cargs} (@command{gnatmake})
9900 Compiler switches. Here @var{switches} is a list of switches
9901 that are valid switches for @command{gcc}. They will be passed on to
9902 all compile steps performed by @command{gnatmake}.
9904 @item -bargs @var{switches}
9905 @cindex @option{-bargs} (@command{gnatmake})
9906 Binder switches. Here @var{switches} is a list of switches
9907 that are valid switches for @code{gnatbind}. They will be passed on to
9908 all bind steps performed by @command{gnatmake}.
9910 @item -largs @var{switches}
9911 @cindex @option{-largs} (@command{gnatmake})
9912 Linker switches. Here @var{switches} is a list of switches
9913 that are valid switches for @command{gnatlink}. They will be passed on to
9914 all link steps performed by @command{gnatmake}.
9916 @item -margs @var{switches}
9917 @cindex @option{-margs} (@command{gnatmake})
9918 Make switches. The switches are directly interpreted by @command{gnatmake},
9919 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9920 or @option{-largs}.
9921 @end table
9923 @node Notes on the Command Line
9924 @section Notes on the Command Line
9926 @noindent
9927 This section contains some additional useful notes on the operation
9928 of the @command{gnatmake} command.
9930 @itemize @bullet
9931 @item
9932 @cindex Recompilation, by @command{gnatmake}
9933 If @command{gnatmake} finds no ALI files, it recompiles the main program
9934 and all other units required by the main program.
9935 This means that @command{gnatmake}
9936 can be used for the initial compile, as well as during subsequent steps of
9937 the development cycle.
9939 @item
9940 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9941 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9942 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9943 warning.
9945 @item
9946 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9947 is used to specify both source and
9948 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9949 instead if you just want to specify
9950 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9951 if you want to specify library paths
9952 only.
9954 @item
9955 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9956 This may conveniently be used to exclude standard libraries from
9957 consideration and in particular it means that the use of the
9958 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9959 unless @option{^-a^/ALL_FILES^} is also specified.
9961 @item
9962 @command{gnatmake} has been designed to make the use of Ada libraries
9963 particularly convenient. Assume you have an Ada library organized
9964 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9965 of your Ada compilation units,
9966 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9967 specs of these units, but no bodies. Then to compile a unit
9968 stored in @code{main.adb}, which uses this Ada library you would just type
9970 @smallexample
9971 @ifclear vms
9972 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9973 @end ifclear
9974 @ifset vms
9975 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9976            /SKIP_MISSING=@i{[OBJ_DIR]} main
9977 @end ifset
9978 @end smallexample
9980 @item
9981 Using @command{gnatmake} along with the
9982 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9983 switch provides a mechanism for avoiding unnecessary recompilations. Using
9984 this switch,
9985 you can update the comments/format of your
9986 source files without having to recompile everything. Note, however, that
9987 adding or deleting lines in a source files may render its debugging
9988 info obsolete. If the file in question is a spec, the impact is rather
9989 limited, as that debugging info will only be useful during the
9990 elaboration phase of your program. For bodies the impact can be more
9991 significant. In all events, your debugger will warn you if a source file
9992 is more recent than the corresponding object, and alert you to the fact
9993 that the debugging information may be out of date.
9994 @end itemize
9996 @node How gnatmake Works
9997 @section How @command{gnatmake} Works
9999 @noindent
10000 Generally @command{gnatmake} automatically performs all necessary
10001 recompilations and you don't need to worry about how it works. However,
10002 it may be useful to have some basic understanding of the @command{gnatmake}
10003 approach and in particular to understand how it uses the results of
10004 previous compilations without incorrectly depending on them.
10006 First a definition: an object file is considered @dfn{up to date} if the
10007 corresponding ALI file exists and if all the source files listed in the
10008 dependency section of this ALI file have time stamps matching those in
10009 the ALI file. This means that neither the source file itself nor any
10010 files that it depends on have been modified, and hence there is no need
10011 to recompile this file.
10013 @command{gnatmake} works by first checking if the specified main unit is up
10014 to date. If so, no compilations are required for the main unit. If not,
10015 @command{gnatmake} compiles the main program to build a new ALI file that
10016 reflects the latest sources. Then the ALI file of the main unit is
10017 examined to find all the source files on which the main program depends,
10018 and @command{gnatmake} recursively applies the above procedure on all these
10019 files.
10021 This process ensures that @command{gnatmake} only trusts the dependencies
10022 in an existing ALI file if they are known to be correct. Otherwise it
10023 always recompiles to determine a new, guaranteed accurate set of
10024 dependencies. As a result the program is compiled ``upside down'' from what may
10025 be more familiar as the required order of compilation in some other Ada
10026 systems. In particular, clients are compiled before the units on which
10027 they depend. The ability of GNAT to compile in any order is critical in
10028 allowing an order of compilation to be chosen that guarantees that
10029 @command{gnatmake} will recompute a correct set of new dependencies if
10030 necessary.
10032 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10033 imported by several of the executables, it will be recompiled at most once.
10035 Note: when using non-standard naming conventions
10036 (@pxref{Using Other File Names}), changing through a configuration pragmas
10037 file the version of a source and invoking @command{gnatmake} to recompile may
10038 have no effect, if the previous version of the source is still accessible
10039 by @command{gnatmake}. It may be necessary to use the switch
10040 ^-f^/FORCE_COMPILE^.
10042 @node Examples of gnatmake Usage
10043 @section Examples of @command{gnatmake} Usage
10045 @table @code
10046 @item gnatmake hello.adb
10047 Compile all files necessary to bind and link the main program
10048 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10049 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10051 @item gnatmake main1 main2 main3
10052 Compile all files necessary to bind and link the main programs
10053 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10054 (containing unit @code{Main2}) and @file{main3.adb}
10055 (containing unit @code{Main3}) and bind and link the resulting object files
10056 to generate three executable files @file{^main1^MAIN1.EXE^},
10057 @file{^main2^MAIN2.EXE^}
10058 and @file{^main3^MAIN3.EXE^}.
10060 @ifclear vms
10061 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10062 @end ifclear
10064 @ifset vms
10065 @item gnatmake Main_Unit /QUIET
10066 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10067 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10068 @end ifset
10069 Compile all files necessary to bind and link the main program unit
10070 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10071 be done with optimization level 2 and the order of elaboration will be
10072 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10073 displaying commands it is executing.
10074 @end table
10076 @c *************************
10077 @node Improving Performance
10078 @chapter Improving Performance
10079 @cindex Improving performance
10081 @noindent
10082 This chapter presents several topics related to program performance.
10083 It first describes some of the tradeoffs that need to be considered
10084 and some of the techniques for making your program run faster.
10085 It then documents the @command{gnatelim} tool and unused subprogram/data
10086 elimination feature, which can reduce the size of program executables.
10088 @ifnottex
10089 @menu
10090 * Performance Considerations::
10091 * Text_IO Suggestions::
10092 * Reducing Size of Ada Executables with gnatelim::
10093 * Reducing Size of Executables with unused subprogram/data elimination::
10094 @end menu
10095 @end ifnottex
10097 @c *****************************
10098 @node Performance Considerations
10099 @section Performance Considerations
10101 @noindent
10102 The GNAT system provides a number of options that allow a trade-off
10103 between
10105 @itemize @bullet
10106 @item
10107 performance of the generated code
10109 @item
10110 speed of compilation
10112 @item
10113 minimization of dependences and recompilation
10115 @item
10116 the degree of run-time checking.
10117 @end itemize
10119 @noindent
10120 The defaults (if no options are selected) aim at improving the speed
10121 of compilation and minimizing dependences, at the expense of performance
10122 of the generated code:
10124 @itemize @bullet
10125 @item
10126 no optimization
10128 @item
10129 no inlining of subprogram calls
10131 @item
10132 all run-time checks enabled except overflow and elaboration checks
10133 @end itemize
10135 @noindent
10136 These options are suitable for most program development purposes. This
10137 chapter describes how you can modify these choices, and also provides
10138 some guidelines on debugging optimized code.
10140 @menu
10141 * Controlling Run-Time Checks::
10142 * Use of Restrictions::
10143 * Optimization Levels::
10144 * Debugging Optimized Code::
10145 * Inlining of Subprograms::
10146 * Vectorization of loops::
10147 * Other Optimization Switches::
10148 * Optimization and Strict Aliasing::
10149 * Aliased Variables and Optimization::
10151 @ifset vms
10152 * Coverage Analysis::
10153 @end ifset
10154 @end menu
10156 @node Controlling Run-Time Checks
10157 @subsection Controlling Run-Time Checks
10159 @noindent
10160 By default, GNAT generates all run-time checks, except integer overflow
10161 checks, stack overflow checks, and checks for access before elaboration on
10162 subprogram calls. The latter are not required in default mode, because all
10163 necessary checking is done at compile time.
10164 @cindex @option{-gnatp} (@command{gcc})
10165 @cindex @option{-gnato} (@command{gcc})
10166 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10167 be modified. @xref{Run-Time Checks}.
10169 Our experience is that the default is suitable for most development
10170 purposes.
10172 We treat integer overflow specially because these
10173 are quite expensive and in our experience are not as important as other
10174 run-time checks in the development process. Note that division by zero
10175 is not considered an overflow check, and divide by zero checks are
10176 generated where required by default.
10178 Elaboration checks are off by default, and also not needed by default, since
10179 GNAT uses a static elaboration analysis approach that avoids the need for
10180 run-time checking. This manual contains a full chapter discussing the issue
10181 of elaboration checks, and if the default is not satisfactory for your use,
10182 you should read this chapter.
10184 For validity checks, the minimal checks required by the Ada Reference
10185 Manual (for case statements and assignments to array elements) are on
10186 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10187 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10188 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10189 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10190 are also suppressed entirely if @option{-gnatp} is used.
10192 @cindex Overflow checks
10193 @cindex Checks, overflow
10194 @findex Suppress
10195 @findex Unsuppress
10196 @cindex pragma Suppress
10197 @cindex pragma Unsuppress
10198 Note that the setting of the switches controls the default setting of
10199 the checks. They may be modified using either @code{pragma Suppress} (to
10200 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10201 checks) in the program source.
10203 @node Use of Restrictions
10204 @subsection Use of Restrictions
10206 @noindent
10207 The use of pragma Restrictions allows you to control which features are
10208 permitted in your program. Apart from the obvious point that if you avoid
10209 relatively expensive features like finalization (enforceable by the use
10210 of pragma Restrictions (No_Finalization), the use of this pragma does not
10211 affect the generated code in most cases.
10213 One notable exception to this rule is that the possibility of task abort
10214 results in some distributed overhead, particularly if finalization or
10215 exception handlers are used. The reason is that certain sections of code
10216 have to be marked as non-abortable.
10218 If you use neither the @code{abort} statement, nor asynchronous transfer
10219 of control (@code{select @dots{} then abort}), then this distributed overhead
10220 is removed, which may have a general positive effect in improving
10221 overall performance.  Especially code involving frequent use of tasking
10222 constructs and controlled types will show much improved performance.
10223 The relevant restrictions pragmas are
10225 @smallexample @c ada
10226    pragma Restrictions (No_Abort_Statements);
10227    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10228 @end smallexample
10230 @noindent
10231 It is recommended that these restriction pragmas be used if possible. Note
10232 that this also means that you can write code without worrying about the
10233 possibility of an immediate abort at any point.
10235 @node Optimization Levels
10236 @subsection Optimization Levels
10237 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10239 @noindent
10240 Without any optimization ^option,^qualifier,^
10241 the compiler's goal is to reduce the cost of
10242 compilation and to make debugging produce the expected results.
10243 Statements are independent: if you stop the program with a breakpoint between
10244 statements, you can then assign a new value to any variable or change
10245 the program counter to any other statement in the subprogram and get exactly
10246 the results you would expect from the source code.
10248 Turning on optimization makes the compiler attempt to improve the
10249 performance and/or code size at the expense of compilation time and
10250 possibly the ability to debug the program.
10252 If you use multiple
10253 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10254 the last such option is the one that is effective.
10256 @noindent
10257 The default is optimization off. This results in the fastest compile
10258 times, but GNAT makes absolutely no attempt to optimize, and the
10259 generated programs are considerably larger and slower than when
10260 optimization is enabled. You can use the
10261 @ifclear vms
10262 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10263 @option{-O2}, @option{-O3}, and @option{-Os})
10264 @end ifclear
10265 @ifset vms
10266 @code{OPTIMIZE} qualifier
10267 @end ifset
10268 to @command{gcc} to control the optimization level:
10270 @table @option
10271 @item ^-O0^/OPTIMIZE=NONE^
10272 No optimization (the default);
10273 generates unoptimized code but has
10274 the fastest compilation time.
10276 Note that many other compilers do fairly extensive optimization
10277 even if ``no optimization'' is specified. With gcc, it is
10278 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10279 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10280 really does mean no optimization at all. This difference between
10281 gcc and other compilers should be kept in mind when doing
10282 performance comparisons.
10284 @item ^-O1^/OPTIMIZE=SOME^
10285 Moderate optimization;
10286 optimizes reasonably well but does not
10287 degrade compilation time significantly.
10289 @item ^-O2^/OPTIMIZE=ALL^
10290 @ifset vms
10291 @itemx /OPTIMIZE=DEVELOPMENT
10292 @end ifset
10293 Full optimization;
10294 generates highly optimized code and has
10295 the slowest compilation time.
10297 @item ^-O3^/OPTIMIZE=INLINING^
10298 Full optimization as in @option{-O2};
10299 also uses more aggressive automatic inlining of subprograms within a unit
10300 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10302 @item ^-Os^/OPTIMIZE=SPACE^
10303 Optimize space usage (code and data) of resulting program.
10304 @end table
10306 @noindent
10307 Higher optimization levels perform more global transformations on the
10308 program and apply more expensive analysis algorithms in order to generate
10309 faster and more compact code. The price in compilation time, and the
10310 resulting improvement in execution time,
10311 both depend on the particular application and the hardware environment.
10312 You should experiment to find the best level for your application.
10314 Since the precise set of optimizations done at each level will vary from
10315 release to release (and sometime from target to target), it is best to think
10316 of the optimization settings in general terms.
10317 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10318 the GNU Compiler Collection (GCC)}, for details about
10319 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10320 individually enable or disable specific optimizations.
10322 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10323 been tested extensively at all optimization levels. There are some bugs
10324 which appear only with optimization turned on, but there have also been
10325 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10326 level of optimization does not improve the reliability of the code
10327 generator, which in practice is highly reliable at all optimization
10328 levels.
10330 Note regarding the use of @option{-O3}: The use of this optimization level
10331 is generally discouraged with GNAT, since it often results in larger
10332 executables which may run more slowly. See further discussion of this point
10333 in @ref{Inlining of Subprograms}.
10335 @node Debugging Optimized Code
10336 @subsection Debugging Optimized Code
10337 @cindex Debugging optimized code
10338 @cindex Optimization and debugging
10340 @noindent
10341 Although it is possible to do a reasonable amount of debugging at
10342 @ifclear vms
10343 nonzero optimization levels,
10344 the higher the level the more likely that
10345 @end ifclear
10346 @ifset vms
10347 @option{/OPTIMIZE} settings other than @code{NONE},
10348 such settings will make it more likely that
10349 @end ifset
10350 source-level constructs will have been eliminated by optimization.
10351 For example, if a loop is strength-reduced, the loop
10352 control variable may be completely eliminated and thus cannot be
10353 displayed in the debugger.
10354 This can only happen at @option{-O2} or @option{-O3}.
10355 Explicit temporary variables that you code might be eliminated at
10356 ^level^setting^ @option{-O1} or higher.
10358 The use of the @option{^-g^/DEBUG^} switch,
10359 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10360 which is needed for source-level debugging,
10361 affects the size of the program executable on disk,
10362 and indeed the debugging information can be quite large.
10363 However, it has no effect on the generated code (and thus does not
10364 degrade performance)
10366 Since the compiler generates debugging tables for a compilation unit before
10367 it performs optimizations, the optimizing transformations may invalidate some
10368 of the debugging data.  You therefore need to anticipate certain
10369 anomalous situations that may arise while debugging optimized code.
10370 These are the most common cases:
10372 @enumerate
10373 @item
10374 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10375 commands show
10376 the PC bouncing back and forth in the code.  This may result from any of
10377 the following optimizations:
10379 @itemize @bullet
10380 @item
10381 @i{Common subexpression elimination:} using a single instance of code for a
10382 quantity that the source computes several times.  As a result you
10383 may not be able to stop on what looks like a statement.
10385 @item
10386 @i{Invariant code motion:} moving an expression that does not change within a
10387 loop, to the beginning of the loop.
10389 @item
10390 @i{Instruction scheduling:} moving instructions so as to
10391 overlap loads and stores (typically) with other code, or in
10392 general to move computations of values closer to their uses. Often
10393 this causes you to pass an assignment statement without the assignment
10394 happening and then later bounce back to the statement when the
10395 value is actually needed.  Placing a breakpoint on a line of code
10396 and then stepping over it may, therefore, not always cause all the
10397 expected side-effects.
10398 @end itemize
10400 @item
10401 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10402 two identical pieces of code are merged and the program counter suddenly
10403 jumps to a statement that is not supposed to be executed, simply because
10404 it (and the code following) translates to the same thing as the code
10405 that @emph{was} supposed to be executed.  This effect is typically seen in
10406 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10407 a @code{break} in a C @code{^switch^switch^} statement.
10409 @item
10410 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10411 There are various reasons for this effect:
10413 @itemize @bullet
10414 @item
10415 In a subprogram prologue, a parameter may not yet have been moved to its
10416 ``home''.
10418 @item
10419 A variable may be dead, and its register re-used.  This is
10420 probably the most common cause.
10422 @item
10423 As mentioned above, the assignment of a value to a variable may
10424 have been moved.
10426 @item
10427 A variable may be eliminated entirely by value propagation or
10428 other means.  In this case, GCC may incorrectly generate debugging
10429 information for the variable
10430 @end itemize
10432 @noindent
10433 In general, when an unexpected value appears for a local variable or parameter
10434 you should first ascertain if that value was actually computed by
10435 your program, as opposed to being incorrectly reported by the debugger.
10436 Record fields or
10437 array elements in an object designated by an access value
10438 are generally less of a problem, once you have ascertained that the access
10439 value is sensible.
10440 Typically, this means checking variables in the preceding code and in the
10441 calling subprogram to verify that the value observed is explainable from other
10442 values (one must apply the procedure recursively to those
10443 other values); or re-running the code and stopping a little earlier
10444 (perhaps before the call) and stepping to better see how the variable obtained
10445 the value in question; or continuing to step @emph{from} the point of the
10446 strange value to see if code motion had simply moved the variable's
10447 assignments later.
10448 @end enumerate
10450 @noindent
10451 In light of such anomalies, a recommended technique is to use @option{-O0}
10452 early in the software development cycle, when extensive debugging capabilities
10453 are most needed, and then move to @option{-O1} and later @option{-O2} as
10454 the debugger becomes less critical.
10455 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10456 a release management issue.
10457 @ifclear vms
10458 Note that if you use @option{-g} you can then use the @command{strip} program
10459 on the resulting executable,
10460 which removes both debugging information and global symbols.
10461 @end ifclear
10463 @node Inlining of Subprograms
10464 @subsection Inlining of Subprograms
10466 @noindent
10467 A call to a subprogram in the current unit is inlined if all the
10468 following conditions are met:
10470 @itemize @bullet
10471 @item
10472 The optimization level is at least @option{-O1}.
10474 @item
10475 The called subprogram is suitable for inlining: It must be small enough
10476 and not contain something that @command{gcc} cannot support in inlined
10477 subprograms.
10479 @item
10480 @cindex pragma Inline
10481 @findex Inline
10482 Any one of the following applies: @code{pragma Inline} is applied to the
10483 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10484 subprogram is local to the unit and called once from within it; the
10485 subprogram is small and optimization level @option{-O2} is specified;
10486 optimization level @option{-O3} is specified.
10487 @end itemize
10489 @noindent
10490 Calls to subprograms in @code{with}'ed units are normally not inlined.
10491 To achieve actual inlining (that is, replacement of the call by the code
10492 in the body of the subprogram), the following conditions must all be true:
10494 @itemize @bullet
10495 @item
10496 The optimization level is at least @option{-O1}.
10498 @item
10499 The called subprogram is suitable for inlining: It must be small enough
10500 and not contain something that @command{gcc} cannot support in inlined
10501 subprograms.
10503 @item
10504 The call appears in a body (not in a package spec).
10506 @item
10507 There is a @code{pragma Inline} for the subprogram.
10509 @item
10510 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10511 @end itemize
10513 Even if all these conditions are met, it may not be possible for
10514 the compiler to inline the call, due to the length of the body,
10515 or features in the body that make it impossible for the compiler
10516 to do the inlining.
10518 Note that specifying the @option{-gnatn} switch causes additional
10519 compilation dependencies. Consider the following:
10521 @smallexample @c ada
10522 @cartouche
10523 package R is
10524    procedure Q;
10525    pragma Inline (Q);
10526 end R;
10527 package body R is
10528    @dots{}
10529 end R;
10531 with R;
10532 procedure Main is
10533 begin
10534    @dots{}
10535    R.Q;
10536 end Main;
10537 @end cartouche
10538 @end smallexample
10540 @noindent
10541 With the default behavior (no @option{-gnatn} switch specified), the
10542 compilation of the @code{Main} procedure depends only on its own source,
10543 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10544 means that editing the body of @code{R} does not require recompiling
10545 @code{Main}.
10547 On the other hand, the call @code{R.Q} is not inlined under these
10548 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10549 is compiled, the call will be inlined if the body of @code{Q} is small
10550 enough, but now @code{Main} depends on the body of @code{R} in
10551 @file{r.adb} as well as on the spec. This means that if this body is edited,
10552 the main program must be recompiled. Note that this extra dependency
10553 occurs whether or not the call is in fact inlined by @command{gcc}.
10555 The use of front end inlining with @option{-gnatN} generates similar
10556 additional dependencies.
10558 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10559 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10560 can be used to prevent
10561 all inlining. This switch overrides all other conditions and ensures
10562 that no inlining occurs. The extra dependences resulting from
10563 @option{-gnatn} will still be active, even if
10564 this switch is used to suppress the resulting inlining actions.
10566 @cindex @option{-fno-inline-functions} (@command{gcc})
10567 Note: The @option{-fno-inline-functions} switch can be used to prevent
10568 automatic inlining of subprograms if @option{-O3} is used.
10570 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10571 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10572 automatic inlining of small subprograms if @option{-O2} is used.
10574 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10575 Note: The @option{-fno-inline-functions-called-once} switch
10576 can be used to prevent inlining of subprograms local to the unit
10577 and called once from within it if @option{-O1} is used.
10579 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10580 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10581 specified in lieu of it, @option{-gnatn} being translated into one of them
10582 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10583 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10584 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10585 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10586 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
10587 effect of inlining subprograms you did not think should be inlined. We have
10588 found that the use of @option{-O3} may slow down the compilation and increase
10589 the code size by performing excessive inlining, leading to increased
10590 instruction cache pressure from the increased code size and thus minor
10591 performance improvements. So the bottom line here is that you should not
10592 automatically assume that @option{-O3} is better than @option{-O2}, and
10593 indeed you should use @option{-O3} only if tests show that it actually
10594 improves performance for your program.
10596 @node Vectorization of loops
10597 @subsection Vectorization of loops
10598 @cindex Optimization Switches
10600 You can take advantage of the auto-vectorizer present in the @command{gcc}
10601 back end to vectorize loops with GNAT.  The corresponding command line switch
10602 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10603 and other aggressive optimizations helpful for vectorization also are enabled
10604 by default at this level, using @option{-O3} directly is recommended.
10606 You also need to make sure that the target architecture features a supported
10607 SIMD instruction set.  For example, for the x86 architecture, you should at
10608 least specify @option{-msse2} to get significant vectorization (but you don't
10609 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10610 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10612 The preferred loop form for vectorization is the @code{for} iteration scheme.
10613 Loops with a @code{while} iteration scheme can also be vectorized if they are
10614 very simple, but the vectorizer will quickly give up otherwise.  With either
10615 iteration scheme, the flow of control must be straight, in particular no
10616 @code{exit} statement may appear in the loop body.  The loop may however
10617 contain a single nested loop, if it can be vectorized when considered alone:
10619 @smallexample @c ada
10620 @cartouche
10621    A : array (1..4, 1..4) of Long_Float;
10622    S : array (1..4) of Long_Float;
10624    procedure Sum is
10625    begin
10626       for I in A'Range(1) loop
10627          for J in A'Range(2) loop
10628             S (I) := S (I) + A (I, J);
10629          end loop;
10630       end loop;
10631    end Sum;
10632 @end cartouche
10633 @end smallexample
10635 The vectorizable operations depend on the targeted SIMD instruction set, but
10636 the adding and some of the multiplying operators are generally supported, as
10637 well as the logical operators for modular types.  Note that, in the former
10638 case, enabling overflow checks, for example with @option{-gnato}, totally
10639 disables vectorization.  The other checks are not supposed to have the same
10640 definitive effect, although compiling with @option{-gnatp} might well reveal
10641 cases where some checks do thwart vectorization.
10643 Type conversions may also prevent vectorization if they involve semantics that
10644 are not directly supported by the code generator or the SIMD instruction set.
10645 A typical example is direct conversion from floating-point to integer types.
10646 The solution in this case is to use the following idiom:
10648 @smallexample @c ada
10649    Integer (S'Truncation (F))
10650 @end smallexample
10652 @noindent
10653 if @code{S} is the subtype of floating-point object @code{F}.
10655 In most cases, the vectorizable loops are loops that iterate over arrays.
10656 All kinds of array types are supported, i.e. constrained array types with
10657 static bounds:
10659 @smallexample @c ada
10660    type Array_Type is array (1 .. 4) of Long_Float;
10661 @end smallexample
10663 @noindent
10664 constrained array types with dynamic bounds:
10666 @smallexample @c ada
10667    type Array_Type is array (1 .. Q.N) of Long_Float;
10669    type Array_Type is array (Q.K .. 4) of Long_Float;
10671    type Array_Type is array (Q.K .. Q.N) of Long_Float;
10672 @end smallexample
10674 @noindent
10675 or unconstrained array types:
10677 @smallexample @c ada
10678   type Array_Type is array (Positive range <>) of Long_Float;
10679 @end smallexample
10681 @noindent
10682 The quality of the generated code decreases when the dynamic aspect of the
10683 array type increases, the worst code being generated for unconstrained array
10684 types.  This is so because, the less information the compiler has about the
10685 bounds of the array, the more fallback code it needs to generate in order to
10686 fix things up at run time.
10688 It is possible to specify that a given loop should be subject to vectorization
10689 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10691 @smallexample @c ada
10692   pragma Loop_Optimize (Vector);
10693 @end smallexample
10695 @noindent
10696 placed immediately within the loop will convey the appropriate hint to the
10697 compiler for this loop.
10699 @node Other Optimization Switches
10700 @subsection Other Optimization Switches
10701 @cindex Optimization Switches
10703 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10704 @command{gcc} optimization switches are potentially usable. These switches
10705 have not been extensively tested with GNAT but can generally be expected
10706 to work. Examples of switches in this category are @option{-funroll-loops}
10707 and the various target-specific @option{-m} options (in particular, it has
10708 been observed that @option{-march=xxx} can significantly improve performance
10709 on appropriate machines). For full details of these switches, see
10710 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10711 the GNU Compiler Collection (GCC)}.
10713 @node Optimization and Strict Aliasing
10714 @subsection Optimization and Strict Aliasing
10715 @cindex Aliasing
10716 @cindex Strict Aliasing
10717 @cindex No_Strict_Aliasing
10719 @noindent
10720 The strong typing capabilities of Ada allow an optimizer to generate
10721 efficient code in situations where other languages would be forced to
10722 make worst case assumptions preventing such optimizations. Consider
10723 the following example:
10725 @smallexample @c ada
10726 @cartouche
10727 procedure R is
10728    type Int1 is new Integer;
10729    type Int2 is new Integer;
10730    type Int1A is access Int1;
10731    type Int2A is access Int2;
10732    Int1V : Int1A;
10733    Int2V : Int2A;
10734    @dots{}
10736 begin
10737    @dots{}
10738    for J in Data'Range loop
10739       if Data (J) = Int1V.all then
10740          Int2V.all := Int2V.all + 1;
10741       end if;
10742    end loop;
10743    @dots{}
10744 end R;
10745 @end cartouche
10746 @end smallexample
10748 @noindent
10749 In this example, since the variable @code{Int1V} can only access objects
10750 of type @code{Int1}, and @code{Int2V} can only access objects of type
10751 @code{Int2}, there is no possibility that the assignment to
10752 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10753 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10754 for all iterations of the loop and avoid the extra memory reference
10755 required to dereference it each time through the loop.
10757 This kind of optimization, called strict aliasing analysis, is
10758 triggered by specifying an optimization level of @option{-O2} or
10759 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10760 when access values are involved.
10762 However, although this optimization is always correct in terms of
10763 the formal semantics of the Ada Reference Manual, difficulties can
10764 arise if features like @code{Unchecked_Conversion} are used to break
10765 the typing system. Consider the following complete program example:
10767 @smallexample @c ada
10768 @cartouche
10769 package p1 is
10770    type int1 is new integer;
10771    type int2 is new integer;
10772    type a1 is access int1;
10773    type a2 is access int2;
10774 end p1;
10776 with p1; use p1;
10777 package p2 is
10778    function to_a2 (Input : a1) return a2;
10779 end p2;
10781 with Unchecked_Conversion;
10782 package body p2 is
10783    function to_a2 (Input : a1) return a2 is
10784       function to_a2u is
10785         new Unchecked_Conversion (a1, a2);
10786    begin
10787       return to_a2u (Input);
10788    end to_a2;
10789 end p2;
10791 with p2; use p2;
10792 with p1; use p1;
10793 with Text_IO; use Text_IO;
10794 procedure m is
10795    v1 : a1 := new int1;
10796    v2 : a2 := to_a2 (v1);
10797 begin
10798    v1.all := 1;
10799    v2.all := 0;
10800    put_line (int1'image (v1.all));
10801 end;
10802 @end cartouche
10803 @end smallexample
10805 @noindent
10806 This program prints out 0 in @option{-O0} or @option{-O1}
10807 mode, but it prints out 1 in @option{-O2} mode. That's
10808 because in strict aliasing mode, the compiler can and
10809 does assume that the assignment to @code{v2.all} could not
10810 affect the value of @code{v1.all}, since different types
10811 are involved.
10813 This behavior is not a case of non-conformance with the standard, since
10814 the Ada RM specifies that an unchecked conversion where the resulting
10815 bit pattern is not a correct value of the target type can result in an
10816 abnormal value and attempting to reference an abnormal value makes the
10817 execution of a program erroneous.  That's the case here since the result
10818 does not point to an object of type @code{int2}.  This means that the
10819 effect is entirely unpredictable.
10821 However, although that explanation may satisfy a language
10822 lawyer, in practice an applications programmer expects an
10823 unchecked conversion involving pointers to create true
10824 aliases and the behavior of printing 1 seems plain wrong.
10825 In this case, the strict aliasing optimization is unwelcome.
10827 Indeed the compiler recognizes this possibility, and the
10828 unchecked conversion generates a warning:
10830 @smallexample
10831 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10832 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10833 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10834 @end smallexample
10836 @noindent
10837 Unfortunately the problem is recognized when compiling the body of
10838 package @code{p2}, but the actual "bad" code is generated while
10839 compiling the body of @code{m} and this latter compilation does not see
10840 the suspicious @code{Unchecked_Conversion}.
10842 As implied by the warning message, there are approaches you can use to
10843 avoid the unwanted strict aliasing optimization in a case like this.
10845 One possibility is to simply avoid the use of @option{-O2}, but
10846 that is a bit drastic, since it throws away a number of useful
10847 optimizations that do not involve strict aliasing assumptions.
10849 A less drastic approach is to compile the program using the
10850 option @option{-fno-strict-aliasing}. Actually it is only the
10851 unit containing the dereferencing of the suspicious pointer
10852 that needs to be compiled. So in this case, if we compile
10853 unit @code{m} with this switch, then we get the expected
10854 value of zero printed. Analyzing which units might need
10855 the switch can be painful, so a more reasonable approach
10856 is to compile the entire program with options @option{-O2}
10857 and @option{-fno-strict-aliasing}. If the performance is
10858 satisfactory with this combination of options, then the
10859 advantage is that the entire issue of possible "wrong"
10860 optimization due to strict aliasing is avoided.
10862 To avoid the use of compiler switches, the configuration
10863 pragma @code{No_Strict_Aliasing} with no parameters may be
10864 used to specify that for all access types, the strict
10865 aliasing optimization should be suppressed.
10867 However, these approaches are still overkill, in that they causes
10868 all manipulations of all access values to be deoptimized. A more
10869 refined approach is to concentrate attention on the specific
10870 access type identified as problematic.
10872 First, if a careful analysis of uses of the pointer shows
10873 that there are no possible problematic references, then
10874 the warning can be suppressed by bracketing the
10875 instantiation of @code{Unchecked_Conversion} to turn
10876 the warning off:
10878 @smallexample @c ada
10879    pragma Warnings (Off);
10880    function to_a2u is
10881      new Unchecked_Conversion (a1, a2);
10882    pragma Warnings (On);
10883 @end smallexample
10885 @noindent
10886 Of course that approach is not appropriate for this particular
10887 example, since indeed there is a problematic reference. In this
10888 case we can take one of two other approaches.
10890 The first possibility is to move the instantiation of unchecked
10891 conversion to the unit in which the type is declared. In
10892 this example, we would move the instantiation of
10893 @code{Unchecked_Conversion} from the body of package
10894 @code{p2} to the spec of package @code{p1}. Now the
10895 warning disappears. That's because any use of the
10896 access type knows there is a suspicious unchecked
10897 conversion, and the strict aliasing optimization
10898 is automatically suppressed for the type.
10900 If it is not practical to move the unchecked conversion to the same unit
10901 in which the destination access type is declared (perhaps because the
10902 source type is not visible in that unit), you may use pragma
10903 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10904 same declarative sequence as the declaration of the access type:
10906 @smallexample @c ada
10907    type a2 is access int2;
10908    pragma No_Strict_Aliasing (a2);
10909 @end smallexample
10911 @noindent
10912 Here again, the compiler now knows that the strict aliasing optimization
10913 should be suppressed for any reference to type @code{a2} and the
10914 expected behavior is obtained.
10916 Finally, note that although the compiler can generate warnings for
10917 simple cases of unchecked conversions, there are tricker and more
10918 indirect ways of creating type incorrect aliases which the compiler
10919 cannot detect. Examples are the use of address overlays and unchecked
10920 conversions involving composite types containing access types as
10921 components. In such cases, no warnings are generated, but there can
10922 still be aliasing problems. One safe coding practice is to forbid the
10923 use of address clauses for type overlaying, and to allow unchecked
10924 conversion only for primitive types. This is not really a significant
10925 restriction since any possible desired effect can be achieved by
10926 unchecked conversion of access values.
10928 The aliasing analysis done in strict aliasing mode can certainly
10929 have significant benefits. We have seen cases of large scale
10930 application code where the time is increased by up to 5% by turning
10931 this optimization off. If you have code that includes significant
10932 usage of unchecked conversion, you might want to just stick with
10933 @option{-O1} and avoid the entire issue. If you get adequate
10934 performance at this level of optimization level, that's probably
10935 the safest approach. If tests show that you really need higher
10936 levels of optimization, then you can experiment with @option{-O2}
10937 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10938 has on size and speed of the code. If you really need to use
10939 @option{-O2} with strict aliasing in effect, then you should
10940 review any uses of unchecked conversion of access types,
10941 particularly if you are getting the warnings described above.
10943 @node Aliased Variables and Optimization
10944 @subsection Aliased Variables and Optimization
10945 @cindex Aliasing
10946 There are scenarios in which programs may
10947 use low level techniques to modify variables
10948 that otherwise might be considered to be unassigned. For example,
10949 a variable can be passed to a procedure by reference, which takes
10950 the address of the parameter and uses the address to modify the
10951 variable's value, even though it is passed as an IN parameter.
10952 Consider the following example:
10954 @smallexample @c ada
10955 procedure P is
10956    Max_Length : constant Natural := 16;
10957    type Char_Ptr is access all Character;
10959    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
10960    pragma Import (C, Get_String, "get_string");
10962    Name : aliased String (1 .. Max_Length) := (others => ' ');
10963    Temp : Char_Ptr;
10965    function Addr (S : String) return Char_Ptr is
10966       function To_Char_Ptr is
10967         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
10968    begin
10969       return To_Char_Ptr (S (S'First)'Address);
10970    end;
10972 begin
10973    Temp := Addr (Name);
10974    Get_String (Temp, Max_Length);
10975 end;
10976 @end smallexample
10978 @noindent
10979 where Get_String is a C function that uses the address in Temp to
10980 modify the variable @code{Name}. This code is dubious, and arguably
10981 erroneous, and the compiler would be entitled to assume that
10982 @code{Name} is never modified, and generate code accordingly.
10984 However, in practice, this would cause some existing code that
10985 seems to work with no optimization to start failing at high
10986 levels of optimzization.
10988 What the compiler does for such cases is to assume that marking
10989 a variable as aliased indicates that some "funny business" may
10990 be going on. The optimizer recognizes the aliased keyword and
10991 inhibits optimizations that assume the value cannot be assigned.
10992 This means that the above example will in fact "work" reliably,
10993 that is, it will produce the expected results.
10995 @ifset vms
10996 @node Coverage Analysis
10997 @subsection Coverage Analysis
10999 @noindent
11000 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11001 the user to determine the distribution of execution time across a program,
11002 @pxref{Profiling} for details of usage.
11003 @end ifset
11006 @node Text_IO Suggestions
11007 @section @code{Text_IO} Suggestions
11008 @cindex @code{Text_IO} and performance
11010 @noindent
11011 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11012 the requirement of maintaining page and line counts. If performance
11013 is critical, a recommendation is to use @code{Stream_IO} instead of
11014 @code{Text_IO} for volume output, since this package has less overhead.
11016 If @code{Text_IO} must be used, note that by default output to the standard
11017 output and standard error files is unbuffered (this provides better
11018 behavior when output statements are used for debugging, or if the
11019 progress of a program is observed by tracking the output, e.g. by
11020 using the Unix @command{tail -f} command to watch redirected output.
11022 If you are generating large volumes of output with @code{Text_IO} and
11023 performance is an important factor, use a designated file instead
11024 of the standard output file, or change the standard output file to
11025 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11029 @node Reducing Size of Ada Executables with gnatelim
11030 @section Reducing Size of Ada Executables with @code{gnatelim}
11031 @findex gnatelim
11033 @noindent
11034 This section describes @command{gnatelim}, a tool which detects unused
11035 subprograms and helps the compiler to create a smaller executable for your
11036 program.
11038 @menu
11039 * About gnatelim::
11040 * Running gnatelim::
11041 * Processing Precompiled Libraries::
11042 * Correcting the List of Eliminate Pragmas::
11043 * Making Your Executables Smaller::
11044 * Summary of the gnatelim Usage Cycle::
11045 @end menu
11047 @node About gnatelim
11048 @subsection About @code{gnatelim}
11050 @noindent
11051 When a program shares a set of Ada
11052 packages with other programs, it may happen that this program uses
11053 only a fraction of the subprograms defined in these packages. The code
11054 created for these unused subprograms increases the size of the executable.
11056 @code{gnatelim} tracks unused subprograms in an Ada program and
11057 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11058 subprograms that are declared but never called. By placing the list of
11059 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11060 recompiling your program, you may decrease the size of its executable,
11061 because the compiler will not generate the code for 'eliminated' subprograms.
11062 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11063 information about this pragma.
11065 @code{gnatelim} needs as its input data the name of the main subprogram.
11067 If a set of source files is specified as @code{gnatelim} arguments, it
11068 treats these files as a complete set of sources making up a program to
11069 analyse, and analyses only these sources.
11071 After a full successful build of the main subprogram @code{gnatelim} can be
11072 called without  specifying sources to analyse, in this case it computes
11073 the source closure of the main unit from the @file{ALI} files.
11075 The following command will create the set of @file{ALI} files needed for
11076 @code{gnatelim}:
11078 @smallexample
11079 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11080 @end smallexample
11082 Note that @code{gnatelim} does not need object files.
11084 @node Running gnatelim
11085 @subsection Running @code{gnatelim}
11087 @noindent
11088 @code{gnatelim} has the following command-line interface:
11090 @smallexample
11091 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11092 @end smallexample
11094 @noindent
11095 @var{main_unit_name} should be a name of a source file that contains the main
11096 subprogram of a program (partition).
11098 Each @var{filename} is the name (including the extension) of a source
11099 file to process. ``Wildcards'' are allowed, and
11100 the file name may contain path information.
11102 @samp{@var{gcc_switches}} is a list of switches for
11103 @command{gcc}. They will be passed on to all compiler invocations made by
11104 @command{gnatelim} to generate the ASIS trees. Here you can provide
11105 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11106 use the @option{-gnatec} switch to set the configuration file,
11107 use the @option{-gnat05} switch if sources should be compiled in
11108 Ada 2005 mode etc.
11110 @code{gnatelim} has the following switches:
11112 @table @option
11113 @c !sort!
11114 @item --version
11115 @cindex @option{--version} @command{gnatelim}
11116 Display Copyright and version, then exit disregarding all other options.
11118 @item --help
11119 @cindex @option{--help} @command{gnatelim}
11120 Display usage, then exit disregarding all other options.
11122 @item ^-files^/FILES^=@var{filename}
11123 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11124 Take the argument source files from the specified file. This file should be an
11125 ordinary text file containing file names separated by spaces or
11126 line breaks. You can use this switch more than once in the same call to
11127 @command{gnatelim}. You also can combine this switch with
11128 an explicit list of files.
11130 @item ^-log^/LOG^
11131 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11132 Duplicate all the output sent to @file{stderr} into a log file. The log file
11133 is named @file{gnatelim.log} and is located in the current directory.
11135 @item ^-log^/LOGFILE^=@var{filename}
11136 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11137 Duplicate all the output sent to @file{stderr} into a specified log file.
11139 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11140 @item ^--no-elim-dispatch^/NO_DISPATCH^
11141 Do not generate pragmas for dispatching operations.
11143 @item ^--ignore^/IGNORE^=@var{filename}
11144 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11145 Do not generate pragmas for subprograms declared in the sources
11146 listed in a specified file
11148 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11149 @item ^-o^/OUTPUT^=@var{report_file}
11150 Put @command{gnatelim} output into a specified file. If this file already exists,
11151 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11152 into @file{stderr}
11154 @item ^-q^/QUIET^
11155 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11156 Quiet mode: by default @code{gnatelim} outputs to the standard error
11157 stream the number of program units left to be processed. This option turns
11158 this trace off.
11160 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11161 @item ^-t^/TIME^
11162 Print out execution time.
11164 @item ^-v^/VERBOSE^
11165 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11166 Verbose mode: @code{gnatelim} version information is printed as Ada
11167 comments to the standard output stream. Also, in addition to the number of
11168 program units left @code{gnatelim} will output the name of the current unit
11169 being processed.
11171 @item ^-wq^/WARNINGS=QUIET^
11172 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11173 Quiet warning mode - some warnings are suppressed. In particular warnings that
11174 indicate that the analysed set of sources is incomplete to make up a
11175 partition and that some subprogram bodies are missing are not generated.
11176 @end table
11178 @noindent
11179 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11180 driver (see @ref{The GNAT Driver and Project Files}).
11182 @node Processing Precompiled Libraries
11183 @subsection Processing Precompiled Libraries
11185 @noindent
11186 If some program uses a precompiled Ada library, it can be processed by
11187 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11188 Eliminate pragma for a subprogram if the body of this subprogram has not
11189 been analysed, this is a typical case for subprograms from precompiled
11190 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11191 warnings about missing source files and non-analyzed subprogram bodies
11192 that can be generated when processing precompiled Ada libraries.
11194 @node Correcting the List of Eliminate Pragmas
11195 @subsection Correcting the List of Eliminate Pragmas
11197 @noindent
11198 In some rare cases @code{gnatelim} may try to eliminate
11199 subprograms that are actually called in the program. In this case, the
11200 compiler will generate an error message of the form:
11202 @smallexample
11203 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11204 @end smallexample
11206 @noindent
11207 You will need to manually remove the wrong @code{Eliminate} pragmas from
11208 the configuration file indicated in the error message. You should recompile
11209 your program from scratch after that, because you need a consistent
11210 configuration file(s) during the entire compilation.
11212 @node Making Your Executables Smaller
11213 @subsection Making Your Executables Smaller
11215 @noindent
11216 In order to get a smaller executable for your program you now have to
11217 recompile the program completely with the configuration file containing
11218 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11219 @file{gnat.adc} file located in your current directory, just do:
11221 @smallexample
11222 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11223 @end smallexample
11225 @noindent
11226 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11227 recompile everything
11228 with the set of pragmas @code{Eliminate} that you have obtained with
11229 @command{gnatelim}).
11231 Be aware that the set of @code{Eliminate} pragmas is specific to each
11232 program. It is not recommended to merge sets of @code{Eliminate}
11233 pragmas created for different programs in one configuration file.
11235 @node Summary of the gnatelim Usage Cycle
11236 @subsection Summary of the @code{gnatelim} Usage Cycle
11238 @noindent
11239 Here is a quick summary of the steps to be taken in order to reduce
11240 the size of your executables with @code{gnatelim}. You may use
11241 other GNAT options to control the optimization level,
11242 to produce the debugging information, to set search path, etc.
11244 @enumerate
11245 @item
11246 Create a complete set of @file{ALI} files (if the program has not been
11247 built already)
11249 @smallexample
11250 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11251 @end smallexample
11253 @item
11254 Generate a list of @code{Eliminate} pragmas in default configuration file
11255 @file{gnat.adc} in the current directory
11256 @smallexample
11257 @ifset vms
11258 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11259 @end ifset
11260 @ifclear vms
11261 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11262 @end ifclear
11263 @end smallexample
11265 @item
11266 Recompile the application
11268 @smallexample
11269 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11270 @end smallexample
11272 @end enumerate
11274 @node Reducing Size of Executables with unused subprogram/data elimination
11275 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11276 @findex unused subprogram/data elimination
11278 @noindent
11279 This section describes how you can eliminate unused subprograms and data from
11280 your executable just by setting options at compilation time.
11282 @menu
11283 * About unused subprogram/data elimination::
11284 * Compilation options::
11285 * Example of unused subprogram/data elimination::
11286 @end menu
11288 @node About unused subprogram/data elimination
11289 @subsection About unused subprogram/data elimination
11291 @noindent
11292 By default, an executable contains all code and data of its composing objects
11293 (directly linked or coming from statically linked libraries), even data or code
11294 never used by this executable.
11296 This feature will allow you to eliminate such unused code from your
11297 executable, making it smaller (in disk and in memory).
11299 This functionality is available on all Linux platforms except for the IA-64
11300 architecture and on all cross platforms using the ELF binary file format.
11301 In both cases GNU binutils version 2.16 or later are required to enable it.
11303 @node Compilation options
11304 @subsection Compilation options
11306 @noindent
11307 The operation of eliminating the unused code and data from the final executable
11308 is directly performed by the linker.
11310 In order to do this, it has to work with objects compiled with the
11311 following options:
11312 @option{-ffunction-sections} @option{-fdata-sections}.
11313 @cindex @option{-ffunction-sections} (@command{gcc})
11314 @cindex @option{-fdata-sections} (@command{gcc})
11315 These options are usable with C and Ada files.
11316 They will place respectively each
11317 function or data in a separate section in the resulting object file.
11319 Once the objects and static libraries are created with these options, the
11320 linker can perform the dead code elimination. You can do this by setting
11321 the @option{-Wl,--gc-sections} option to gcc command or in the
11322 @option{-largs} section of @command{gnatmake}. This will perform a
11323 garbage collection of code and data never referenced.
11325 If the linker performs a partial link (@option{-r} ld linker option), then you
11326 will need to provide one or several entry point using the
11327 @option{-e} / @option{--entry} ld option.
11329 Note that objects compiled without the @option{-ffunction-sections} and
11330 @option{-fdata-sections} options can still be linked with the executable.
11331 However, no dead code elimination will be performed on those objects (they will
11332 be linked as is).
11334 The GNAT static library is now compiled with -ffunction-sections and
11335 -fdata-sections on some platforms. This allows you to eliminate the unused code
11336 and data of the GNAT library from your executable.
11338 @node Example of unused subprogram/data elimination
11339 @subsection Example of unused subprogram/data elimination
11341 @noindent
11342 Here is a simple example:
11344 @smallexample @c ada
11345 with Aux;
11347 procedure Test is
11348 begin
11349    Aux.Used (10);
11350 end Test;
11352 package Aux is
11353    Used_Data   : Integer;
11354    Unused_Data : Integer;
11356    procedure Used   (Data : Integer);
11357    procedure Unused (Data : Integer);
11358 end Aux;
11360 package body Aux is
11361    procedure Used (Data : Integer) is
11362    begin
11363       Used_Data := Data;
11364    end Used;
11366    procedure Unused (Data : Integer) is
11367    begin
11368       Unused_Data := Data;
11369    end Unused;
11370 end Aux;
11371 @end smallexample
11373 @noindent
11374 @code{Unused} and @code{Unused_Data} are never referenced in this code
11375 excerpt, and hence they may be safely removed from the final executable.
11377 @smallexample
11378 $ gnatmake test
11380 $ nm test | grep used
11381 020015f0 T aux__unused
11382 02005d88 B aux__unused_data
11383 020015cc T aux__used
11384 02005d84 B aux__used_data
11386 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11387      -largs -Wl,--gc-sections
11389 $ nm test | grep used
11390 02005350 T aux__used
11391 0201ffe0 B aux__used_data
11392 @end smallexample
11394 @noindent
11395 It can be observed that the procedure @code{Unused} and the object
11396 @code{Unused_Data} are removed by the linker when using the
11397 appropriate options.
11399 @c ********************************
11400 @node Renaming Files with gnatchop
11401 @chapter Renaming Files with @code{gnatchop}
11402 @findex gnatchop
11404 @noindent
11405 This chapter discusses how to handle files with multiple units by using
11406 the @code{gnatchop} utility. This utility is also useful in renaming
11407 files to meet the standard GNAT default file naming conventions.
11409 @menu
11410 * Handling Files with Multiple Units::
11411 * Operating gnatchop in Compilation Mode::
11412 * Command Line for gnatchop::
11413 * Switches for gnatchop::
11414 * Examples of gnatchop Usage::
11415 @end menu
11417 @node Handling Files with Multiple Units
11418 @section Handling Files with Multiple Units
11420 @noindent
11421 The basic compilation model of GNAT requires that a file submitted to the
11422 compiler have only one unit and there be a strict correspondence
11423 between the file name and the unit name.
11425 The @code{gnatchop} utility allows both of these rules to be relaxed,
11426 allowing GNAT to process files which contain multiple compilation units
11427 and files with arbitrary file names. @code{gnatchop}
11428 reads the specified file and generates one or more output files,
11429 containing one unit per file. The unit and the file name correspond,
11430 as required by GNAT.
11432 If you want to permanently restructure a set of ``foreign'' files so that
11433 they match the GNAT rules, and do the remaining development using the
11434 GNAT structure, you can simply use @command{gnatchop} once, generate the
11435 new set of files and work with them from that point on.
11437 Alternatively, if you want to keep your files in the ``foreign'' format,
11438 perhaps to maintain compatibility with some other Ada compilation
11439 system, you can set up a procedure where you use @command{gnatchop} each
11440 time you compile, regarding the source files that it writes as temporary
11441 files that you throw away.
11443 Note that if your file containing multiple units starts with a byte order
11444 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11445 will each start with a copy of this BOM, meaning that they can be compiled
11446 automatically in UTF-8 mode without needing to specify an explicit encoding.
11448 @node Operating gnatchop in Compilation Mode
11449 @section Operating gnatchop in Compilation Mode
11451 @noindent
11452 The basic function of @code{gnatchop} is to take a file with multiple units
11453 and split it into separate files. The boundary between files is reasonably
11454 clear, except for the issue of comments and pragmas. In default mode, the
11455 rule is that any pragmas between units belong to the previous unit, except
11456 that configuration pragmas always belong to the following unit. Any comments
11457 belong to the following unit. These rules
11458 almost always result in the right choice of
11459 the split point without needing to mark it explicitly and most users will
11460 find this default to be what they want. In this default mode it is incorrect to
11461 submit a file containing only configuration pragmas, or one that ends in
11462 configuration pragmas, to @code{gnatchop}.
11464 However, using a special option to activate ``compilation mode'',
11465 @code{gnatchop}
11466 can perform another function, which is to provide exactly the semantics
11467 required by the RM for handling of configuration pragmas in a compilation.
11468 In the absence of configuration pragmas (at the main file level), this
11469 option has no effect, but it causes such configuration pragmas to be handled
11470 in a quite different manner.
11472 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11473 only configuration pragmas, then this file is appended to the
11474 @file{gnat.adc} file in the current directory. This behavior provides
11475 the required behavior described in the RM for the actions to be taken
11476 on submitting such a file to the compiler, namely that these pragmas
11477 should apply to all subsequent compilations in the same compilation
11478 environment. Using GNAT, the current directory, possibly containing a
11479 @file{gnat.adc} file is the representation
11480 of a compilation environment. For more information on the
11481 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11483 Second, in compilation mode, if @code{gnatchop}
11484 is given a file that starts with
11485 configuration pragmas, and contains one or more units, then these
11486 configuration pragmas are prepended to each of the chopped files. This
11487 behavior provides the required behavior described in the RM for the
11488 actions to be taken on compiling such a file, namely that the pragmas
11489 apply to all units in the compilation, but not to subsequently compiled
11490 units.
11492 Finally, if configuration pragmas appear between units, they are appended
11493 to the previous unit. This results in the previous unit being illegal,
11494 since the compiler does not accept configuration pragmas that follow
11495 a unit. This provides the required RM behavior that forbids configuration
11496 pragmas other than those preceding the first compilation unit of a
11497 compilation.
11499 For most purposes, @code{gnatchop} will be used in default mode. The
11500 compilation mode described above is used only if you need exactly
11501 accurate behavior with respect to compilations, and you have files
11502 that contain multiple units and configuration pragmas. In this
11503 circumstance the use of @code{gnatchop} with the compilation mode
11504 switch provides the required behavior, and is for example the mode
11505 in which GNAT processes the ACVC tests.
11507 @node Command Line for gnatchop
11508 @section Command Line for @code{gnatchop}
11510 @noindent
11511 The @code{gnatchop} command has the form:
11513 @smallexample
11514 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11515 @c      @ovar{directory}
11516 @c Expanding @ovar macro inline (explanation in macro def comments)
11517 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11518       @r{[}@var{directory}@r{]}
11519 @end smallexample
11521 @noindent
11522 The only required argument is the file name of the file to be chopped.
11523 There are no restrictions on the form of this file name. The file itself
11524 contains one or more Ada units, in normal GNAT format, concatenated
11525 together. As shown, more than one file may be presented to be chopped.
11527 When run in default mode, @code{gnatchop} generates one output file in
11528 the current directory for each unit in each of the files.
11530 @var{directory}, if specified, gives the name of the directory to which
11531 the output files will be written. If it is not specified, all files are
11532 written to the current directory.
11534 For example, given a
11535 file called @file{hellofiles} containing
11537 @smallexample @c ada
11538 @group
11539 @cartouche
11540 procedure hello;
11542 with Text_IO; use Text_IO;
11543 procedure hello is
11544 begin
11545    Put_Line ("Hello");
11546 end hello;
11547 @end cartouche
11548 @end group
11549 @end smallexample
11551 @noindent
11552 the command
11554 @smallexample
11555 $ gnatchop ^hellofiles^HELLOFILES.^
11556 @end smallexample
11558 @noindent
11559 generates two files in the current directory, one called
11560 @file{hello.ads} containing the single line that is the procedure spec,
11561 and the other called @file{hello.adb} containing the remaining text. The
11562 original file is not affected. The generated files can be compiled in
11563 the normal manner.
11565 @noindent
11566 When gnatchop is invoked on a file that is empty or that contains only empty
11567 lines and/or comments, gnatchop will not fail, but will not produce any
11568 new sources.
11570 For example, given a
11571 file called @file{toto.txt} containing
11573 @smallexample @c ada
11574 @group
11575 @cartouche
11576 --  Just a comment
11577 @end cartouche
11578 @end group
11579 @end smallexample
11581 @noindent
11582 the command
11584 @smallexample
11585 $ gnatchop ^toto.txt^TOT.TXT^
11586 @end smallexample
11588 @noindent
11589 will not produce any new file and will result in the following warnings:
11591 @smallexample
11592 toto.txt:1:01: warning: empty file, contains no compilation units
11593 no compilation units found
11594 no source files written
11595 @end smallexample
11597 @node Switches for gnatchop
11598 @section Switches for @code{gnatchop}
11600 @noindent
11601 @command{gnatchop} recognizes the following switches:
11603 @table @option
11604 @c !sort!
11606 @item --version
11607 @cindex @option{--version} @command{gnatchop}
11608 Display Copyright and version, then exit disregarding all other options.
11610 @item --help
11611 @cindex @option{--help} @command{gnatchop}
11612 If @option{--version} was not used, display usage, then exit disregarding
11613 all other options.
11615 @item ^-c^/COMPILATION^
11616 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11617 Causes @code{gnatchop} to operate in compilation mode, in which
11618 configuration pragmas are handled according to strict RM rules. See
11619 previous section for a full description of this mode.
11621 @ifclear vms
11622 @item -gnat@var{xxx}
11623 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11624 used to parse the given file. Not all @var{xxx} options make sense,
11625 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11626 process a source file that uses Latin-2 coding for identifiers.
11627 @end ifclear
11629 @item ^-h^/HELP^
11630 Causes @code{gnatchop} to generate a brief help summary to the standard
11631 output file showing usage information.
11633 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11634 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11635 Limit generated file names to the specified number @code{mm}
11636 of characters.
11637 This is useful if the
11638 resulting set of files is required to be interoperable with systems
11639 which limit the length of file names.
11640 @ifset vms
11641 If no value is given, or
11642 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11643 a default of 39, suitable for OpenVMS Alpha
11644 Systems, is assumed
11645 @end ifset
11646 @ifclear vms
11647 No space is allowed between the @option{-k} and the numeric value. The numeric
11648 value may be omitted in which case a default of @option{-k8},
11649 suitable for use
11650 with DOS-like file systems, is used. If no @option{-k} switch
11651 is present then
11652 there is no limit on the length of file names.
11653 @end ifclear
11655 @item ^-p^/PRESERVE^
11656 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11657 Causes the file ^modification^creation^ time stamp of the input file to be
11658 preserved and used for the time stamp of the output file(s). This may be
11659 useful for preserving coherency of time stamps in an environment where
11660 @code{gnatchop} is used as part of a standard build process.
11662 @item ^-q^/QUIET^
11663 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11664 Causes output of informational messages indicating the set of generated
11665 files to be suppressed. Warnings and error messages are unaffected.
11667 @item ^-r^/REFERENCE^
11668 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11669 @findex Source_Reference
11670 Generate @code{Source_Reference} pragmas. Use this switch if the output
11671 files are regarded as temporary and development is to be done in terms
11672 of the original unchopped file. This switch causes
11673 @code{Source_Reference} pragmas to be inserted into each of the
11674 generated files to refers back to the original file name and line number.
11675 The result is that all error messages refer back to the original
11676 unchopped file.
11677 In addition, the debugging information placed into the object file (when
11678 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11679 specified)
11680 also refers back to this original file so that tools like profilers and
11681 debuggers will give information in terms of the original unchopped file.
11683 If the original file to be chopped itself contains
11684 a @code{Source_Reference}
11685 pragma referencing a third file, then gnatchop respects
11686 this pragma, and the generated @code{Source_Reference} pragmas
11687 in the chopped file refer to the original file, with appropriate
11688 line numbers. This is particularly useful when @code{gnatchop}
11689 is used in conjunction with @code{gnatprep} to compile files that
11690 contain preprocessing statements and multiple units.
11692 @item ^-v^/VERBOSE^
11693 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11694 Causes @code{gnatchop} to operate in verbose mode. The version
11695 number and copyright notice are output, as well as exact copies of
11696 the gnat1 commands spawned to obtain the chop control information.
11698 @item ^-w^/OVERWRITE^
11699 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11700 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11701 fatal error if there is already a file with the same name as a
11702 file it would otherwise output, in other words if the files to be
11703 chopped contain duplicated units. This switch bypasses this
11704 check, and causes all but the last instance of such duplicated
11705 units to be skipped.
11707 @ifclear vms
11708 @item --GCC=@var{xxxx}
11709 @cindex @option{--GCC=} (@code{gnatchop})
11710 Specify the path of the GNAT parser to be used. When this switch is used,
11711 no attempt is made to add the prefix to the GNAT parser executable.
11712 @end ifclear
11713 @end table
11715 @node Examples of gnatchop Usage
11716 @section Examples of @code{gnatchop} Usage
11718 @table @code
11719 @ifset vms
11720 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11721 @end ifset
11722 @ifclear vms
11723 @item gnatchop -w hello_s.ada prerelease/files
11724 @end ifclear
11726 Chops the source file @file{hello_s.ada}. The output files will be
11727 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11728 overwriting any
11729 files with matching names in that directory (no files in the current
11730 directory are modified).
11732 @item gnatchop ^archive^ARCHIVE.^
11733 Chops the source file @file{^archive^ARCHIVE.^}
11734 into the current directory. One
11735 useful application of @code{gnatchop} is in sending sets of sources
11736 around, for example in email messages. The required sources are simply
11737 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11738 command), and then
11739 @command{gnatchop} is used at the other end to reconstitute the original
11740 file names.
11742 @item gnatchop file1 file2 file3 direc
11743 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11744 the resulting files in the directory @file{direc}. Note that if any units
11745 occur more than once anywhere within this set of files, an error message
11746 is generated, and no files are written. To override this check, use the
11747 @option{^-w^/OVERWRITE^} switch,
11748 in which case the last occurrence in the last file will
11749 be the one that is output, and earlier duplicate occurrences for a given
11750 unit will be skipped.
11751 @end table
11753 @node Configuration Pragmas
11754 @chapter Configuration Pragmas
11755 @cindex Configuration pragmas
11756 @cindex Pragmas, configuration
11758 @menu
11759 * Handling of Configuration Pragmas::
11760 * The Configuration Pragmas Files::
11761 @end menu
11763 @noindent
11764 Configuration pragmas include those pragmas described as
11765 such in the Ada Reference Manual, as well as
11766 implementation-dependent pragmas that are configuration pragmas.
11767 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11768 for details on these additional GNAT-specific configuration pragmas.
11769 Most notably, the pragma @code{Source_File_Name}, which allows
11770 specifying non-default names for source files, is a configuration
11771 pragma. The following is a complete list of configuration pragmas
11772 recognized by GNAT:
11774 @smallexample
11775    Ada_83
11776    Ada_95
11777    Ada_05
11778    Ada_2005
11779    Ada_12
11780    Ada_2012
11781    Annotate
11782    Assertion_Policy
11783    Assume_No_Invalid_Values
11784    C_Pass_By_Copy
11785    Check_Name
11786    Check_Policy
11787    Compile_Time_Error
11788    Compile_Time_Warning
11789    Compiler_Unit
11790    Component_Alignment
11791    Convention_Identifier
11792    Debug_Policy
11793    Detect_Blocking
11794    Default_Storage_Pool
11795    Discard_Names
11796    Elaboration_Checks
11797    Eliminate
11798    Extend_System
11799    Extensions_Allowed
11800    External_Name_Casing
11801    Fast_Math
11802    Favor_Top_Level
11803    Float_Representation
11804    Implicit_Packing
11805    Initialize_Scalars
11806    Interrupt_State
11807    License
11808    Locking_Policy
11809    Long_Float
11810    No_Run_Time
11811    No_Strict_Aliasing
11812    Normalize_Scalars
11813    Optimize_Alignment
11814    Persistent_BSS
11815    Polling
11816    Priority_Specific_Dispatching
11817    Profile
11818    Profile_Warnings
11819    Propagate_Exceptions
11820    Queuing_Policy
11821    Ravenscar
11822    Restricted_Run_Time
11823    Restrictions
11824    Restrictions_Warnings
11825    Reviewable
11826    Short_Circuit_And_Or
11827    Source_File_Name
11828    Source_File_Name_Project
11829    SPARK_Mode
11830    Style_Checks
11831    Suppress
11832    Suppress_Exception_Locations
11833    Task_Dispatching_Policy
11834    Universal_Data
11835    Unsuppress
11836    Use_VADS_Size
11837    Validity_Checks
11838    Warnings
11839    Wide_Character_Encoding
11840 @end smallexample
11842 @node Handling of Configuration Pragmas
11843 @section Handling of Configuration Pragmas
11845 Configuration pragmas may either appear at the start of a compilation
11846 unit, or they can appear in a configuration pragma file to apply to
11847 all compilations performed in a given compilation environment.
11849 GNAT also provides the @code{gnatchop} utility to provide an automatic
11850 way to handle configuration pragmas following the semantics for
11851 compilations (that is, files with multiple units), described in the RM.
11852 See @ref{Operating gnatchop in Compilation Mode} for details.
11853 However, for most purposes, it will be more convenient to edit the
11854 @file{gnat.adc} file that contains configuration pragmas directly,
11855 as described in the following section.
11857 In the case of @code{Restrictions} pragmas appearing as configuration
11858 pragmas in individual compilation units, the exact handling depends on
11859 the type of restriction.
11861 Restrictions that require partition-wide consistency (like
11862 @code{No_Tasking}) are
11863 recognized wherever they appear
11864 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11865 unit. This makes sense since the binder will in any case insist on seeing
11866 consistent use, so any unit not conforming to any restrictions that are
11867 anywhere in the partition will be rejected, and you might as well find
11868 that out at compile time rather than at bind time.
11870 For restrictions that do not require partition-wide consistency, e.g.
11871 SPARK or No_Implementation_Attributes, in general the restriction applies
11872 only to the unit in which the pragma appears, and not to any other units.
11874 The exception is No_Elaboration_Code which always applies to the entire
11875 object file from a compilation, i.e. to the body, spec, and all subunits.
11876 This restriction can be specified in a configuration pragma file, or it
11877 can be on the body and/or the spec (in eithe case it applies to all the
11878 relevant units). It can appear on a subunit only if it has previously
11879 appeared in the body of spec.
11881 @node The Configuration Pragmas Files
11882 @section The Configuration Pragmas Files
11883 @cindex @file{gnat.adc}
11885 @noindent
11886 In GNAT a compilation environment is defined by the current
11887 directory at the time that a compile command is given. This current
11888 directory is searched for a file whose name is @file{gnat.adc}. If
11889 this file is present, it is expected to contain one or more
11890 configuration pragmas that will be applied to the current compilation.
11891 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11892 considered.
11894 Configuration pragmas may be entered into the @file{gnat.adc} file
11895 either by running @code{gnatchop} on a source file that consists only of
11896 configuration pragmas, or more conveniently  by
11897 direct editing of the @file{gnat.adc} file, which is a standard format
11898 source file.
11900 In addition to @file{gnat.adc}, additional files containing configuration
11901 pragmas may be applied to the current compilation using the switch
11902 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11903 contains only configuration pragmas. These configuration pragmas are
11904 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11905 is present and switch @option{-gnatA} is not used).
11907 It is allowed to specify several switches @option{-gnatec}, all of which
11908 will be taken into account.
11910 If you are using project file, a separate mechanism is provided using
11911 project attributes, see @ref{Specifying Configuration Pragmas} for more
11912 details.
11914 @ifset vms
11915 Of special interest to GNAT OpenVMS Alpha is the following
11916 configuration pragma:
11918 @smallexample @c ada
11919 @cartouche
11920 pragma Extend_System (Aux_DEC);
11921 @end cartouche
11922 @end smallexample
11924 @noindent
11925 In the presence of this pragma, GNAT adds to the definition of the
11926 predefined package SYSTEM all the additional types and subprograms that are
11927 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11928 @end ifset
11930 @node Handling Arbitrary File Naming Conventions with gnatname
11931 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
11932 @cindex Arbitrary File Naming Conventions
11934 @menu
11935 * Arbitrary File Naming Conventions::
11936 * Running gnatname::
11937 * Switches for gnatname::
11938 * Examples of gnatname Usage::
11939 @end menu
11941 @node Arbitrary File Naming Conventions
11942 @section Arbitrary File Naming Conventions
11944 @noindent
11945 The GNAT compiler must be able to know the source file name of a compilation
11946 unit.  When using the standard GNAT default file naming conventions
11947 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11948 does not need additional information.
11950 @noindent
11951 When the source file names do not follow the standard GNAT default file naming
11952 conventions, the GNAT compiler must be given additional information through
11953 a configuration pragmas file (@pxref{Configuration Pragmas})
11954 or a project file.
11955 When the non-standard file naming conventions are well-defined,
11956 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11957 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11958 if the file naming conventions are irregular or arbitrary, a number
11959 of pragma @code{Source_File_Name} for individual compilation units
11960 must be defined.
11961 To help maintain the correspondence between compilation unit names and
11962 source file names within the compiler,
11963 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11964 set of files.
11966 @node Running gnatname
11967 @section Running @code{gnatname}
11969 @noindent
11970 The usual form of the @code{gnatname} command is
11972 @smallexample
11973 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11974 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11975 @c Expanding @ovar macro inline (explanation in macro def comments)
11976 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11977       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11978 @end smallexample
11980 @noindent
11981 All of the arguments are optional. If invoked without any argument,
11982 @code{gnatname} will display its usage.
11984 @noindent
11985 When used with at least one naming pattern, @code{gnatname} will attempt to
11986 find all the compilation units in files that follow at least one of the
11987 naming patterns. To find these compilation units,
11988 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11989 regular files.
11991 @noindent
11992 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11993 Each Naming Pattern is enclosed between double quotes (or single
11994 quotes on Windows).
11995 A Naming Pattern is a regular expression similar to the wildcard patterns
11996 used in file names by the Unix shells or the DOS prompt.
11998 @noindent
11999 @code{gnatname} may be called with several sections of directories/patterns.
12000 Sections are separated by switch @code{--and}. In each section, there must be
12001 at least one pattern. If no directory is specified in a section, the current
12002 directory (or the project directory is @code{-P} is used) is implied.
12003 The options other that the directory switches and the patterns apply globally
12004 even if they are in different sections.
12006 @noindent
12007 Examples of Naming Patterns are
12009 @smallexample
12010    "*.[12].ada"
12011    "*.ad[sb]*"
12012    "body_*"    "spec_*"
12013 @end smallexample
12015 @noindent
12016 For a more complete description of the syntax of Naming Patterns,
12017 see the second kind of regular expressions described in @file{g-regexp.ads}
12018 (the ``Glob'' regular expressions).
12020 @noindent
12021 When invoked with no switch @code{-P}, @code{gnatname} will create a
12022 configuration pragmas file @file{gnat.adc} in the current working directory,
12023 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12024 unit.
12026 @node Switches for gnatname
12027 @section Switches for @code{gnatname}
12029 @noindent
12030 Switches for @code{gnatname} must precede any specified Naming Pattern.
12032 @noindent
12033 You may specify any of the following switches to @code{gnatname}:
12035 @table @option
12036 @c !sort!
12038 @item --version
12039 @cindex @option{--version} @command{gnatname}
12040 Display Copyright and version, then exit disregarding all other options.
12042 @item --help
12043 @cindex @option{--help} @command{gnatname}
12044 If @option{--version} was not used, display usage, then exit disregarding
12045 all other options.
12047 @item --subdirs=<dir>
12048 Real object, library or exec directories are subdirectories <dir> of the
12049 specified ones.
12051 @item --no-backup
12052 Do not create a backup copy of an existing project file.
12054 @item --and
12055 Start another section of directories/patterns.
12057 @item ^-c^/CONFIG_FILE=^@file{file}
12058 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12059 Create a configuration pragmas file @file{file} (instead of the default
12060 @file{gnat.adc}).
12061 @ifclear vms
12062 There may be zero, one or more space between @option{-c} and
12063 @file{file}.
12064 @end ifclear
12065 @file{file} may include directory information. @file{file} must be
12066 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12067 When a switch @option{^-c^/CONFIG_FILE^} is
12068 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12070 @item ^-d^/SOURCE_DIRS=^@file{dir}
12071 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12072 Look for source files in directory @file{dir}. There may be zero, one or more
12073 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12074 @file{dir} may end with @code{/**}, that is it may be of the form
12075 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
12076 subdirectories, recursively, have to be searched for sources.
12077 When a switch @option{^-d^/SOURCE_DIRS^}
12078 is specified, the current working directory will not be searched for source
12079 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12080 or @option{^-D^/DIR_FILES^} switch.
12081 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12082 If @file{dir} is a relative path, it is relative to the directory of
12083 the configuration pragmas file specified with switch
12084 @option{^-c^/CONFIG_FILE^},
12085 or to the directory of the project file specified with switch
12086 @option{^-P^/PROJECT_FILE^} or,
12087 if neither switch @option{^-c^/CONFIG_FILE^}
12088 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12089 current working directory. The directory
12090 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12092 @item ^-D^/DIRS_FILE=^@file{file}
12093 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12094 Look for source files in all directories listed in text file @file{file}.
12095 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12096 and @file{file}.
12097 @file{file} must be an existing, readable text file.
12098 Each nonempty line in @file{file} must be a directory.
12099 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12100 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12101 @file{file}.
12103 @item -eL
12104 Follow symbolic links when processing project files.
12106 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12107 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12108 Foreign patterns. Using this switch, it is possible to add sources of languages
12109 other than Ada to the list of sources of a project file.
12110 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12111 For example,
12112 @smallexample
12113 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12114 @end smallexample
12115 @noindent
12116 will look for Ada units in all files with the @file{.ada} extension,
12117 and will add to the list of file for project @file{prj.gpr} the C files
12118 with extension @file{.^c^C^}.
12120 @item ^-h^/HELP^
12121 @cindex @option{^-h^/HELP^} (@code{gnatname})
12122 Output usage (help) information. The output is written to @file{stdout}.
12124 @item ^-P^/PROJECT_FILE=^@file{proj}
12125 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12126 Create or update project file @file{proj}. There may be zero, one or more space
12127 between @option{-P} and @file{proj}. @file{proj} may include directory
12128 information. @file{proj} must be writable.
12129 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12130 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12131 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12132 On all platforms, except on VMS, when @code{gnatname} is invoked for an
12133 existing project file <proj>.gpr, a backup copy of the project file is created
12134 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
12135 non negative number that makes this backup copy a new file.
12137 @item ^-v^/VERBOSE^
12138 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12139 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12140 This includes name of the file written, the name of the directories to search
12141 and, for each file in those directories whose name matches at least one of
12142 the Naming Patterns, an indication of whether the file contains a unit,
12143 and if so the name of the unit.
12145 @item ^-v -v^/VERBOSE /VERBOSE^
12146 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12147 Very Verbose mode. In addition to the output produced in verbose mode,
12148 for each file in the searched directories whose name matches none of
12149 the Naming Patterns, an indication is given that there is no match.
12151 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12152 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12153 Excluded patterns. Using this switch, it is possible to exclude some files
12154 that would match the name patterns. For example,
12155 @smallexample
12156 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12157 @end smallexample
12158 @noindent
12159 will look for Ada units in all files with the @file{.ada} extension,
12160 except those whose names end with @file{_nt.ada}.
12162 @end table
12164 @node Examples of gnatname Usage
12165 @section Examples of @code{gnatname} Usage
12167 @ifset vms
12168 @smallexample
12169 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12170 @end smallexample
12171 @end ifset
12173 @ifclear vms
12174 @smallexample
12175 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12176 @end smallexample
12177 @end ifclear
12179 @noindent
12180 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12181 and be writable. In addition, the directory
12182 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12183 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12185 @ifclear vms
12186 Note the optional spaces after @option{-c} and @option{-d}.
12187 @end ifclear
12189 @smallexample
12190 @ifclear vms
12191 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12192   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12193 @end ifclear
12194 @ifset vms
12195 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
12196   /EXCLUDED_PATTERN=*_nt_body.ada
12197   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12198   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12199 @end ifset
12200 @end smallexample
12202 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12203 even in conjunction with one or several switches
12204 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12205 are used in this example.
12207 @c *****************************************
12208 @c * G N A T  P r o j e c t  M a n a g e r *
12209 @c *****************************************
12211 @c ------ macros for projects.texi
12212 @c These macros are needed when building the gprbuild documentation, but
12213 @c should have no effect in the gnat user's guide
12215 @macro CODESAMPLE{TXT}
12216 @smallexample
12217 @group
12218 \TXT\
12219 @end group
12220 @end smallexample
12221 @end macro
12223 @macro PROJECTFILE{TXT}
12224 @CODESAMPLE{\TXT\}
12225 @end macro
12227 @c simulates a newline when in a @CODESAMPLE
12228 @macro NL{}
12229 @end macro
12231 @macro TIP{TXT}
12232 @quotation
12233 @noindent
12234 \TXT\
12235 @end quotation
12236 @end macro
12238 @macro TIPHTML{TXT}
12239 \TXT\
12240 @end macro
12242 @macro IMPORTANT{TXT}
12243 @quotation
12244 @noindent
12245 \TXT\
12246 @end quotation
12248 @end macro
12250 @macro NOTE{TXT}
12251 @quotation
12252 @noindent
12253 \TXT\
12254 @end quotation
12255 @end macro
12257 @include projects.texi
12259 @c ---------------------------------------------
12260 @c Tools Supporting Project Files
12261 @c ---------------------------------------------
12263 @node Tools Supporting Project Files
12264 @chapter Tools Supporting Project Files
12266 @noindent
12268 @menu
12269 * gnatmake and Project Files::
12270 * The GNAT Driver and Project Files::
12271 @end menu
12273 @c ---------------------------------------------
12274 @node gnatmake and Project Files
12275 @section gnatmake and Project Files
12276 @c ---------------------------------------------
12278 @noindent
12279 This section covers several topics related to @command{gnatmake} and
12280 project files: defining ^switches^switches^ for @command{gnatmake}
12281 and for the tools that it invokes; specifying configuration pragmas;
12282 the use of the @code{Main} attribute; building and rebuilding library project
12283 files.
12285 @menu
12286 * Switches Related to Project Files::
12287 * Switches and Project Files::
12288 * Specifying Configuration Pragmas::
12289 * Project Files and Main Subprograms::
12290 * Library Project Files::
12291 @end menu
12293 @c ---------------------------------------------
12294 @node Switches Related to Project Files
12295 @subsection Switches Related to Project Files
12296 @c ---------------------------------------------
12298 @noindent
12299 The following switches are used by GNAT tools that support project files:
12301 @table @option
12303 @item ^-P^/PROJECT_FILE=^@var{project}
12304 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12305 Indicates the name of a project file. This project file will be parsed with
12306 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12307 if any, and using the external references indicated
12308 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12309 @ifclear vms
12310 There may zero, one or more spaces between @option{-P} and @var{project}.
12311 @end ifclear
12313 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12315 Since the Project Manager parses the project file only after all the switches
12316 on the command line are checked, the order of the switches
12317 @option{^-P^/PROJECT_FILE^},
12318 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12319 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12321 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12322 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12323 Indicates that external variable @var{name} has the value @var{value}.
12324 The Project Manager will use this value for occurrences of
12325 @code{external(name)} when parsing the project file.
12327 @ifclear vms
12328 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12329 put between quotes.
12330 @smallexample
12331   -XOS=NT
12332   -X"user=John Doe"
12333 @end smallexample
12334 @end ifclear
12336 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12337 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12338 @var{name}, only the last one is used.
12340 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12341 takes precedence over the value of the same name in the environment.
12343 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12344 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12345 Indicates the verbosity of the parsing of GNAT project files.
12347 @ifclear vms
12348 @option{-vP0} means Default;
12349 @option{-vP1} means Medium;
12350 @option{-vP2} means High.
12351 @end ifclear
12353 @ifset vms
12354 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12355 HIGH.
12356 @end ifset
12358 The default is ^Default^DEFAULT^: no output for syntactically correct
12359 project files.
12360 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12361 only the last one is used.
12363 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12364 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12365 Add directory <dir> at the beginning of the project search path, in order,
12366 after the current working directory.
12368 @ifclear vms
12369 @item -eL
12370 @cindex @option{-eL} (any project-aware tool)
12371 Follow all symbolic links when processing project files.
12372 @end ifclear
12374 @item ^--subdirs^/SUBDIRS^=<subdir>
12375 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12376 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12377 indicate that the real directories (except the source directories) are the
12378 subdirectories <subdir> of the directories specified in the project files.
12379 This applies in particular to object directories, library directories and
12380 exec directories. If the subdirectories do not exist, they are created
12381 automatically.
12383 @end table
12385 @c ---------------------------------------------
12386 @node Switches and Project Files
12387 @subsection Switches and Project Files
12388 @c ---------------------------------------------
12390 @noindent
12391 @ifset vms
12392 It is not currently possible to specify VMS style qualifiers in the project
12393 files; only Unix style ^switches^switches^ may be specified.
12394 @end ifset
12396 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12397 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12398 attribute, a @code{Switches} attribute, or both;
12399 as their names imply, these ^switch^switch^-related
12400 attributes affect the ^switches^switches^ that are used for each of these GNAT
12401 components when
12402 @command{gnatmake} is invoked.  As will be explained below, these
12403 component-specific ^switches^switches^ precede
12404 the ^switches^switches^ provided on the @command{gnatmake} command line.
12406 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12407 indexed by language name (case insensitive) whose value is a string list.
12408 For example:
12410 @smallexample @c projectfile
12411 @group
12412 package Compiler is
12413   for ^Default_Switches^Default_Switches^ ("Ada")
12414       use ("^-gnaty^-gnaty^",
12415            "^-v^-v^");
12416 end Compiler;
12417 @end group
12418 @end smallexample
12420 @noindent
12421 The @code{Switches} attribute is indexed on a file name (which may or may
12422 not be case sensitive, depending
12423 on the operating system) whose value is a string list.  For example:
12425 @smallexample @c projectfile
12426 @group
12427 package Builder is
12428    for Switches ("main1.adb")
12429        use ("^-O2^-O2^");
12430    for Switches ("main2.adb")
12431        use ("^-g^-g^");
12432 end Builder;
12433 @end group
12434 @end smallexample
12436 @noindent
12437 For the @code{Builder} package, the file names must designate source files
12438 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12439 file names must designate @file{ALI} or source files for main subprograms.
12440 In each case just the file name without an explicit extension is acceptable.
12442 For each tool used in a program build (@command{gnatmake}, the compiler, the
12443 binder, and the linker), the corresponding package @dfn{contributes} a set of
12444 ^switches^switches^ for each file on which the tool is invoked, based on the
12445 ^switch^switch^-related attributes defined in the package.
12446 In particular, the ^switches^switches^
12447 that each of these packages contributes for a given file @var{f} comprise:
12449 @itemize @bullet
12450 @item the value of attribute @code{Switches (@var{f})},
12451   if it is specified in the package for the given file,
12452 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12453   if it is specified in the package.
12455 @end itemize
12457 @noindent
12458 If neither of these attributes is defined in the package, then the package does
12459 not contribute any ^switches^switches^ for the given file.
12461 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12462 two sets, in the following order: those contributed for the file
12463 by the @code{Builder} package;
12464 and the switches passed on the command line.
12466 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12467 the ^switches^switches^ passed to the tool comprise three sets,
12468 in the following order:
12470 @enumerate
12471 @item
12472 the applicable ^switches^switches^ contributed for the file
12473 by the @code{Builder} package in the project file supplied on the command line;
12475 @item
12476 those contributed for the file by the package (in the relevant project file --
12477 see below) corresponding to the tool; and
12479 @item
12480 the applicable switches passed on the command line.
12481 @end enumerate
12483 The term @emph{applicable ^switches^switches^} reflects the fact that
12484 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12485 tools, depending on the individual ^switch^switch^.
12487 @command{gnatmake} may invoke the compiler on source files from different
12488 projects. The Project Manager will use the appropriate project file to
12489 determine the @code{Compiler} package for each source file being compiled.
12490 Likewise for the @code{Binder} and @code{Linker} packages.
12492 As an example, consider the following package in a project file:
12494 @smallexample @c projectfile
12495 @group
12496 project Proj1 is
12497    package Compiler is
12498       for ^Default_Switches^Default_Switches^ ("Ada")
12499           use ("^-g^-g^");
12500       for Switches ("a.adb")
12501           use ("^-O1^-O1^");
12502       for Switches ("b.adb")
12503           use ("^-O2^-O2^",
12504                "^-gnaty^-gnaty^");
12505    end Compiler;
12506 end Proj1;
12507 @end group
12508 @end smallexample
12510 @noindent
12511 If @command{gnatmake} is invoked with this project file, and it needs to
12512 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12513 @file{a.adb} will be compiled with the ^switch^switch^
12514 @option{^-O1^-O1^},
12515 @file{b.adb} with ^switches^switches^
12516 @option{^-O2^-O2^}
12517 and @option{^-gnaty^-gnaty^},
12518 and @file{c.adb} with @option{^-g^-g^}.
12520 The following example illustrates the ordering of the ^switches^switches^
12521 contributed by different packages:
12523 @smallexample @c projectfile
12524 @group
12525 project Proj2 is
12526    package Builder is
12527       for Switches ("main.adb")
12528           use ("^-g^-g^",
12529                "^-O1^-)1^",
12530                "^-f^-f^");
12531    end Builder;
12532 @end group
12534 @group
12535    package Compiler is
12536       for Switches ("main.adb")
12537           use ("^-O2^-O2^");
12538    end Compiler;
12539 end Proj2;
12540 @end group
12541 @end smallexample
12543 @noindent
12544 If you issue the command:
12546 @smallexample
12547     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12548 @end smallexample
12550 @noindent
12551 then the compiler will be invoked on @file{main.adb} with the following
12552 sequence of ^switches^switches^
12554 @smallexample
12555    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12556 @end smallexample
12558 @noindent
12559 with the last @option{^-O^-O^}
12560 ^switch^switch^ having precedence over the earlier ones;
12561 several other ^switches^switches^
12562 (such as @option{^-c^-c^}) are added implicitly.
12564 The ^switches^switches^
12565 @option{^-g^-g^}
12566 and @option{^-O1^-O1^} are contributed by package
12567 @code{Builder},  @option{^-O2^-O2^} is contributed
12568 by the package @code{Compiler}
12569 and @option{^-O0^-O0^} comes from the command line.
12571 The @option{^-g^-g^}
12572 ^switch^switch^ will also be passed in the invocation of
12573 @command{Gnatlink.}
12575 A final example illustrates switch contributions from packages in different
12576 project files:
12578 @smallexample @c projectfile
12579 @group
12580 project Proj3 is
12581    for Source_Files use ("pack.ads", "pack.adb");
12582    package Compiler is
12583       for ^Default_Switches^Default_Switches^ ("Ada")
12584           use ("^-gnata^-gnata^");
12585    end Compiler;
12586 end Proj3;
12587 @end group
12589 @group
12590 with "Proj3";
12591 project Proj4 is
12592    for Source_Files use ("foo_main.adb", "bar_main.adb");
12593    package Builder is
12594       for Switches ("foo_main.adb")
12595           use ("^-s^-s^",
12596                "^-g^-g^");
12597    end Builder;
12598 end Proj4;
12599 @end group
12601 @group
12602 -- Ada source file:
12603 with Pack;
12604 procedure Foo_Main is
12605    @dots{}
12606 end Foo_Main;
12607 @end group
12608 @end smallexample
12610 @noindent
12611 If the command is
12612 @smallexample
12613 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12614 @end smallexample
12616 @noindent
12617 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12618 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12619 @option{^-gnato^-gnato^} (passed on the command line).
12620 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12621 are @option{^-g^-g^} from @code{Proj4.Builder},
12622 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12623 and @option{^-gnato^-gnato^} from the command line.
12625 When using @command{gnatmake} with project files, some ^switches^switches^ or
12626 arguments may be expressed as relative paths. As the working directory where
12627 compilation occurs may change, these relative paths are converted to absolute
12628 paths. For the ^switches^switches^ found in a project file, the relative paths
12629 are relative to the project file directory, for the switches on the command
12630 line, they are relative to the directory where @command{gnatmake} is invoked.
12631 The ^switches^switches^ for which this occurs are:
12632 ^-I^-I^,
12633 ^-A^-A^,
12634 ^-L^-L^,
12635 ^-aO^-aO^,
12636 ^-aL^-aL^,
12637 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12638 ^switch^switch^
12639 ^-o^-o^, object files specified in package @code{Linker} or after
12640 -largs on the command line). The exception to this rule is the ^switch^switch^
12641 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12643 @c ---------------------------------------------
12644 @node Specifying Configuration Pragmas
12645 @subsection Specifying Configuration Pragmas
12646 @c ---------------------------------------------
12648 @noindent
12649 When using @command{gnatmake} with project files, if there exists a file
12650 @file{gnat.adc} that contains configuration pragmas, this file will be
12651 ignored.
12653 Configuration pragmas can be defined by means of the following attributes in
12654 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12655 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12657 Both these attributes are single string attributes. Their values is the path
12658 name of a file containing configuration pragmas. If a path name is relative,
12659 then it is relative to the project directory of the project file where the
12660 attribute is defined.
12662 When compiling a source, the configuration pragmas used are, in order,
12663 those listed in the file designated by attribute
12664 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12665 project file, if it is specified, and those listed in the file designated by
12666 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12667 the project file of the source, if it exists.
12669 @c ---------------------------------------------
12670 @node Project Files and Main Subprograms
12671 @subsection Project Files and Main Subprograms
12672 @c ---------------------------------------------
12674 @noindent
12675 When using a project file, you can invoke @command{gnatmake}
12676 with one or several main subprograms, by specifying their source files on the
12677 command line.
12679 @smallexample
12680     gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
12681 @end smallexample
12683 @noindent
12684 Each of these needs to be a source file of the same project, except
12685 when the switch ^-u^/UNIQUE^ is used.
12687 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
12688 same project, one of the project in the tree rooted at the project specified
12689 on the command line. The package @code{Builder} of this common project, the
12690 "main project" is the one that is considered by @command{gnatmake}.
12692 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
12693 imported directly or indirectly by the project specified on the command line.
12694 Note that if such a source file is not part of the project specified on the
12695 command line, the ^switches^switches^ found in package @code{Builder} of the
12696 project specified on the command line, if any, that are transmitted
12697 to the compiler will still be used, not those found in the project file of
12698 the source file.
12700 When using a project file, you can also invoke @command{gnatmake} without
12701 explicitly specifying any main, and the effect depends on whether you have
12702 defined the @code{Main} attribute.  This attribute has a string list value,
12703 where each element in the list is the name of a source file (the file
12704 extension is optional) that contains a unit that can be a main subprogram.
12706 If the @code{Main} attribute is defined in a project file as a non-empty
12707 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
12708 line, then invoking @command{gnatmake} with this project file but without any
12709 main on the command line is equivalent to invoking @command{gnatmake} with all
12710 the file names in the @code{Main} attribute on the command line.
12712 Example:
12713 @smallexample @c projectfile
12714 @group
12715    project Prj is
12716       for Main use ("main1.adb", "main2.adb", "main3.adb");
12717    end Prj;
12718 @end group
12719 @end smallexample
12721 @noindent
12722 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
12723 is equivalent to
12724 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
12726 When the project attribute @code{Main} is not specified, or is specified
12727 as an empty string list, or when the switch @option{-u} is used on the command
12728 line, then invoking @command{gnatmake} with no main on the command line will
12729 result in all immediate sources of the project file being checked, and
12730 potentially recompiled. Depending on the presence of the switch @option{-u},
12731 sources from other project files on which the immediate sources of the main
12732 project file depend are also checked and potentially recompiled. In other
12733 words, the @option{-u} switch is applied to all of the immediate sources of the
12734 main project file.
12736 When no main is specified on the command line and attribute @code{Main} exists
12737 and includes several mains, or when several mains are specified on the
12738 command line, the default ^switches^switches^ in package @code{Builder} will
12739 be used for all mains, even if there are specific ^switches^switches^
12740 specified for one or several mains.
12742 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
12743 the specific ^switches^switches^ for each main, if they are specified.
12745 @c ---------------------------------------------
12746 @node Library Project Files
12747 @subsection Library Project Files
12748 @c ---------------------------------------------
12750 @noindent
12751 When @command{gnatmake} is invoked with a main project file that is a library
12752 project file, it is not allowed to specify one or more mains on the command
12753 line.
12755 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
12756 ^-l^/ACTION=LINK^ have special meanings.
12758 @itemize @bullet
12759 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
12760   to @command{gnatmake} that @command{gnatbind} should be invoked for the
12761   library.
12763 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
12764   to @command{gnatmake} that the binder generated file should be compiled
12765   (in the case of a stand-alone library) and that the library should be built.
12766 @end itemize
12768 @c ---------------------------------------------
12769 @node The GNAT Driver and Project Files
12770 @section The GNAT Driver and Project Files
12771 @c ---------------------------------------------
12773 @noindent
12774 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
12775 can benefit from project files:
12776 (@command{^gnatbind^gnatbind^},
12777 @command{^gnatcheck^gnatcheck^},
12778 @command{^gnatclean^gnatclean^},
12779 @command{^gnatelim^gnatelim^},
12780 @command{^gnatfind^gnatfind^},
12781 @command{^gnatlink^gnatlink^},
12782 @command{^gnatls^gnatls^},
12783 @command{^gnatmetric^gnatmetric^},
12784 @command{^gnatpp^gnatpp^},
12785 @command{^gnatstub^gnatstub^},
12786 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
12787 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
12788 They must be invoked through the @command{gnat} driver.
12790 The @command{gnat} driver is a wrapper that accepts a number of commands and
12791 calls the corresponding tool. It was designed initially for VMS platforms (to
12792 convert VMS qualifiers to Unix-style switches), but it is now available on all
12793 GNAT platforms.
12795 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12796 (case insensitive):
12798 @itemize @bullet
12799 @item BIND to invoke @command{^gnatbind^gnatbind^}
12800 @item CHOP to invoke @command{^gnatchop^gnatchop^}
12801 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
12802 @item COMP or COMPILE to invoke the compiler
12803 @item ELIM to invoke @command{^gnatelim^gnatelim^}
12804 @item FIND to invoke @command{^gnatfind^gnatfind^}
12805 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
12806 @item LINK to invoke @command{^gnatlink^gnatlink^}
12807 @item LS or LIST to invoke @command{^gnatls^gnatls^}
12808 @item MAKE to invoke @command{^gnatmake^gnatmake^}
12809 @item NAME to invoke @command{^gnatname^gnatname^}
12810 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
12811 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
12812 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
12813 @item STUB to invoke @command{^gnatstub^gnatstub^}
12814 @item XREF to invoke @command{^gnatxref^gnatxref^}
12816 @end itemize
12818 @noindent
12819 (note that the compiler is invoked using the command
12820 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
12822 On non-VMS platforms, between @command{gnat} and the command, two
12823 special switches may be used:
12825 @itemize @bullet
12826 @item @command{-v} to display the invocation of the tool.
12827 @item @command{-dn} to prevent the @command{gnat} driver from removing
12828   the temporary files it has created. These temporary files are
12829   configuration files and temporary file list files.
12831 @end itemize
12833 @noindent
12834 The command may be followed by switches and arguments for the invoked
12835 tool.
12837 @smallexample
12838   gnat bind -C main.ali
12839   gnat ls -a main
12840   gnat chop foo.txt
12841 @end smallexample
12843 @noindent
12844 Switches may also be put in text files, one switch per line, and the text
12845 files may be specified with their path name preceded by '@@'.
12847 @smallexample
12848    gnat bind @@args.txt main.ali
12849 @end smallexample
12851 @noindent
12852 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
12853 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
12854 (@option{^-P^/PROJECT_FILE^},
12855 @option{^-X^/EXTERNAL_REFERENCE^} and
12856 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
12857 the switches of the invoking tool.
12859 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12860 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
12861 the immediate sources of the specified project file.
12863 When GNAT METRIC is used with a project file, but with no source
12864 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
12865 with all the immediate sources of the specified project file and with
12866 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
12867 of the project.
12869 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12870 a project file, no source is specified on the command line and
12871 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
12872 the underlying tool (^gnatpp^gnatpp^ or
12873 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
12874 not only for the immediate sources of the main project.
12875 @ifclear vms
12876 (-U stands for Universal or Union of the project files of the project tree)
12877 @end ifclear
12879 For each of the following commands, there is optionally a corresponding
12880 package in the main project.
12882 @itemize @bullet
12883 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
12885 @item package @code{Check} for command CHECK (invoking
12886   @code{^gnatcheck^gnatcheck^})
12888 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12890 @item package @code{Cross_Reference} for command XREF (invoking
12891   @code{^gnatxref^gnatxref^})
12893 @item package @code{Eliminate} for command ELIM (invoking
12894   @code{^gnatelim^gnatelim^})
12896 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
12898 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
12900 @item package @code{Gnatstub} for command STUB
12901   (invoking @code{^gnatstub^gnatstub^})
12903 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
12905 @item package @code{Check} for command CHECK
12906   (invoking @code{^gnatcheck^gnatcheck^})
12908 @item package @code{Metrics} for command METRIC
12909   (invoking @code{^gnatmetric^gnatmetric^})
12911 @item package @code{Pretty_Printer} for command PP or PRETTY
12912   (invoking @code{^gnatpp^gnatpp^})
12914 @end itemize
12916 @noindent
12917 Package @code{Gnatls} has a unique attribute @code{Switches},
12918 a simple variable with a string list value. It contains ^switches^switches^
12919 for the invocation of @code{^gnatls^gnatls^}.
12921 @smallexample @c projectfile
12922 @group
12923 project Proj1 is
12924    package gnatls is
12925       for Switches
12926           use ("^-a^-a^",
12927                "^-v^-v^");
12928    end gnatls;
12929 end Proj1;
12930 @end group
12931 @end smallexample
12933 @noindent
12934 All other packages have two attribute @code{Switches} and
12935 @code{^Default_Switches^Default_Switches^}.
12937 @code{Switches} is an indexed attribute, indexed by the
12938 source file name, that has a string list value: the ^switches^switches^ to be
12939 used when the tool corresponding to the package is invoked for the specific
12940 source file.
12942 @code{^Default_Switches^Default_Switches^} is an attribute,
12943 indexed by  the programming language that has a string list value.
12944 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
12945 ^switches^switches^ for the invocation of the tool corresponding
12946 to the package, except if a specific @code{Switches} attribute
12947 is specified for the source file.
12949 @smallexample @c projectfile
12950 @group
12951 project Proj is
12953    for Source_Dirs use ("**");
12955    package gnatls is
12956       for Switches use
12957           ("^-a^-a^",
12958            "^-v^-v^");
12959    end gnatls;
12960 @end group
12961 @group
12963    package Compiler is
12964       for ^Default_Switches^Default_Switches^ ("Ada")
12965           use ("^-gnatv^-gnatv^",
12966                "^-gnatwa^-gnatwa^");
12967    end Binder;
12968 @end group
12969 @group
12971    package Binder is
12972       for ^Default_Switches^Default_Switches^ ("Ada")
12973           use ("^-C^-C^",
12974                "^-e^-e^");
12975    end Binder;
12976 @end group
12977 @group
12979    package Linker is
12980       for ^Default_Switches^Default_Switches^ ("Ada")
12981           use ("^-C^-C^");
12982       for Switches ("main.adb")
12983           use ("^-C^-C^",
12984                "^-v^-v^",
12985                "^-v^-v^");
12986    end Linker;
12987 @end group
12988 @group
12990    package Finder is
12991       for ^Default_Switches^Default_Switches^ ("Ada")
12992            use ("^-a^-a^",
12993                 "^-f^-f^");
12994    end Finder;
12995 @end group
12996 @group
12998    package Cross_Reference is
12999       for ^Default_Switches^Default_Switches^ ("Ada")
13000           use ("^-a^-a^",
13001                "^-f^-f^",
13002                "^-d^-d^",
13003                "^-u^-u^");
13004    end Cross_Reference;
13005 end Proj;
13006 @end group
13007 @end smallexample
13009 @noindent
13010 With the above project file, commands such as
13012 @smallexample
13013    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13014    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13015    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13016    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13017    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13018 @end smallexample
13020 @noindent
13021 will set up the environment properly and invoke the tool with the switches
13022 found in the package corresponding to the tool:
13023 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13024 except @code{Switches ("main.adb")}
13025 for @code{^gnatlink^gnatlink^}.
13026 It is also possible to invoke some of the tools,
13027 (@code{^gnatcheck^gnatcheck^},
13028 @code{^gnatmetric^gnatmetric^},
13029 and @code{^gnatpp^gnatpp^})
13030 on a set of project units thanks to the combination of the switches
13031 @option{-P}, @option{-U} and possibly the main unit when one is interested
13032 in its closure. For instance,
13033 @smallexample
13034 gnat metric -Pproj
13035 @end smallexample
13037 @noindent
13038 will compute the metrics for all the immediate units of project
13039 @code{proj}.
13040 @smallexample
13041 gnat metric -Pproj -U
13042 @end smallexample
13044 @noindent
13045 will compute the metrics for all the units of the closure of projects
13046 rooted at @code{proj}.
13047 @smallexample
13048 gnat metric -Pproj -U main_unit
13049 @end smallexample
13051 @noindent
13052 will compute the metrics for the closure of units rooted at
13053 @code{main_unit}. This last possibility relies implicitly
13054 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
13055 tool invoked by the @command{gnat} driver are explicitly  specified
13056 either directly or through the tool @option{-files} option, then the tool
13057 is called only for these explicitly specified files.
13059 @c *****************************************
13060 @c * Cross-referencing tools
13061 @c *****************************************
13063 @node The Cross-Referencing Tools gnatxref and gnatfind
13064 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13065 @findex gnatxref
13066 @findex gnatfind
13068 @noindent
13069 The compiler generates cross-referencing information (unless
13070 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13071 This information indicates where in the source each entity is declared and
13072 referenced. Note that entities in package Standard are not included, but
13073 entities in all other predefined units are included in the output.
13075 Before using any of these two tools, you need to compile successfully your
13076 application, so that GNAT gets a chance to generate the cross-referencing
13077 information.
13079 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13080 information to provide the user with the capability to easily locate the
13081 declaration and references to an entity. These tools are quite similar,
13082 the difference being that @code{gnatfind} is intended for locating
13083 definitions and/or references to a specified entity or entities, whereas
13084 @code{gnatxref} is oriented to generating a full report of all
13085 cross-references.
13087 To use these tools, you must not compile your application using the
13088 @option{-gnatx} switch on the @command{gnatmake} command line
13089 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13090 information will not be generated.
13092 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
13093 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
13095 @menu
13096 * Switches for gnatxref::
13097 * Switches for gnatfind::
13098 * Project Files for gnatxref and gnatfind::
13099 * Regular Expressions in gnatfind and gnatxref::
13100 * Examples of gnatxref Usage::
13101 * Examples of gnatfind Usage::
13102 @end menu
13104 @node Switches for gnatxref
13105 @section @code{gnatxref} Switches
13107 @noindent
13108 The command invocation for @code{gnatxref} is:
13109 @smallexample
13110 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13111 @c Expanding @ovar macro inline (explanation in macro def comments)
13112 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13113 @end smallexample
13115 @noindent
13116 where
13118 @table @var
13119 @item sourcefile1
13120 @itemx sourcefile2
13121 identifies the source files for which a report is to be generated. The
13122 ``with''ed units will be processed too. You must provide at least one file.
13124 These file names are considered to be regular expressions, so for instance
13125 specifying @file{source*.adb} is the same as giving every file in the current
13126 directory whose name starts with @file{source} and whose extension is
13127 @file{adb}.
13129 You shouldn't specify any directory name, just base names. @command{gnatxref}
13130 and @command{gnatfind} will be able to locate these files by themselves using
13131 the source path. If you specify directories, no result is produced.
13133 @end table
13135 @noindent
13136 The switches can be:
13137 @table @option
13138 @c !sort!
13139 @item --version
13140 @cindex @option{--version} @command{gnatxref}
13141 Display Copyright and version, then exit disregarding all other options.
13143 @item --help
13144 @cindex @option{--help} @command{gnatxref}
13145 If @option{--version} was not used, display usage, then exit disregarding
13146 all other options.
13148 @item ^-a^/ALL_FILES^
13149 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13150 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13151 the read-only files found in the library search path. Otherwise, these files
13152 will be ignored. This option can be used to protect Gnat sources or your own
13153 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13154 much faster, and their output much smaller. Read-only here refers to access
13155 or permissions status in the file system for the current user.
13157 @item -aIDIR
13158 @cindex @option{-aIDIR} (@command{gnatxref})
13159 When looking for source files also look in directory DIR. The order in which
13160 source file search is undertaken is the same as for @command{gnatmake}.
13162 @item -aODIR
13163 @cindex @option{-aODIR} (@command{gnatxref})
13164 When searching for library and object files, look in directory
13165 DIR. The order in which library files are searched is the same as for
13166 @command{gnatmake}.
13168 @item -nostdinc
13169 @cindex @option{-nostdinc} (@command{gnatxref})
13170 Do not look for sources in the system default directory.
13172 @item -nostdlib
13173 @cindex @option{-nostdlib} (@command{gnatxref})
13174 Do not look for library files in the system default directory.
13176 @item --ext=@var{extension}
13177 @cindex @option{--ext} (@command{gnatxref})
13178 Specify an alternate ali file extension. The default is @code{ali} and other
13179 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13180 switch. Note that if this switch overrides the default, which means that only
13181 the new extension will be considered.
13183 @item --RTS=@var{rts-path}
13184 @cindex @option{--RTS} (@command{gnatxref})
13185 Specifies the default location of the runtime library. Same meaning as the
13186 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13188 @item ^-d^/DERIVED_TYPES^
13189 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13190 If this switch is set @code{gnatxref} will output the parent type
13191 reference for each matching derived types.
13193 @item ^-f^/FULL_PATHNAME^
13194 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13195 If this switch is set, the output file names will be preceded by their
13196 directory (if the file was found in the search path). If this switch is
13197 not set, the directory will not be printed.
13199 @item ^-g^/IGNORE_LOCALS^
13200 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13201 If this switch is set, information is output only for library-level
13202 entities, ignoring local entities. The use of this switch may accelerate
13203 @code{gnatfind} and @code{gnatxref}.
13205 @item -IDIR
13206 @cindex @option{-IDIR} (@command{gnatxref})
13207 Equivalent to @samp{-aODIR -aIDIR}.
13209 @item -pFILE
13210 @cindex @option{-pFILE} (@command{gnatxref})
13211 Specify a project file to use @xref{GNAT Project Manager}.
13212 If you need to use the @file{.gpr}
13213 project files, you should use gnatxref through the GNAT driver
13214 (@command{gnat xref -Pproject}).
13216 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13217 project file in the current directory.
13219 If a project file is either specified or found by the tools, then the content
13220 of the source directory and object directory lines are added as if they
13221 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13222 and @samp{^-aO^OBJECT_SEARCH^}.
13223 @item ^-u^/UNUSED^
13224 Output only unused symbols. This may be really useful if you give your
13225 main compilation unit on the command line, as @code{gnatxref} will then
13226 display every unused entity and 'with'ed package.
13228 @ifclear vms
13229 @item -v
13230 Instead of producing the default output, @code{gnatxref} will generate a
13231 @file{tags} file that can be used by vi. For examples how to use this
13232 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13233 to the standard output, thus you will have to redirect it to a file.
13234 @end ifclear
13236 @end table
13238 @noindent
13239 All these switches may be in any order on the command line, and may even
13240 appear after the file names. They need not be separated by spaces, thus
13241 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13242 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13244 @node Switches for gnatfind
13245 @section @code{gnatfind} Switches
13247 @noindent
13248 The command line for @code{gnatfind} is:
13250 @smallexample
13251 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13252 @c       @r{[}@var{file1} @var{file2} @dots{}]
13253 @c Expanding @ovar macro inline (explanation in macro def comments)
13254 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13255       @r{[}@var{file1} @var{file2} @dots{}@r{]}
13256 @end smallexample
13258 @noindent
13259 where
13261 @table @var
13262 @item pattern
13263 An entity will be output only if it matches the regular expression found
13264 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13266 Omitting the pattern is equivalent to specifying @samp{*}, which
13267 will match any entity. Note that if you do not provide a pattern, you
13268 have to provide both a sourcefile and a line.
13270 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13271 for matching purposes. At the current time there is no support for
13272 8-bit codes other than Latin-1, or for wide characters in identifiers.
13274 @item sourcefile
13275 @code{gnatfind} will look for references, bodies or declarations
13276 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13277 and column @var{column}. See @ref{Examples of gnatfind Usage}
13278 for syntax examples.
13280 @item line
13281 is a decimal integer identifying the line number containing
13282 the reference to the entity (or entities) to be located.
13284 @item column
13285 is a decimal integer identifying the exact location on the
13286 line of the first character of the identifier for the
13287 entity reference. Columns are numbered from 1.
13289 @item file1 file2 @dots{}
13290 The search will be restricted to these source files. If none are given, then
13291 the search will be done for every library file in the search path.
13292 These file must appear only after the pattern or sourcefile.
13294 These file names are considered to be regular expressions, so for instance
13295 specifying @file{source*.adb} is the same as giving every file in the current
13296 directory whose name starts with @file{source} and whose extension is
13297 @file{adb}.
13299 The location of the spec of the entity will always be displayed, even if it
13300 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
13301 occurrences of the entity in the separate units of the ones given on the
13302 command line will also be displayed.
13304 Note that if you specify at least one file in this part, @code{gnatfind} may
13305 sometimes not be able to find the body of the subprograms.
13307 @end table
13309 @noindent
13310 At least one of 'sourcefile' or 'pattern' has to be present on
13311 the command line.
13313 The following switches are available:
13314 @table @option
13315 @c !sort!
13317 @cindex @option{--version} @command{gnatfind}
13318 Display Copyright and version, then exit disregarding all other options.
13320 @item --help
13321 @cindex @option{--help} @command{gnatfind}
13322 If @option{--version} was not used, display usage, then exit disregarding
13323 all other options.
13325 @item ^-a^/ALL_FILES^
13326 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13327 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13328 the read-only files found in the library search path. Otherwise, these files
13329 will be ignored. This option can be used to protect Gnat sources or your own
13330 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13331 much faster, and their output much smaller. Read-only here refers to access
13332 or permission status in the file system for the current user.
13334 @item -aIDIR
13335 @cindex @option{-aIDIR} (@command{gnatfind})
13336 When looking for source files also look in directory DIR. The order in which
13337 source file search is undertaken is the same as for @command{gnatmake}.
13339 @item -aODIR
13340 @cindex @option{-aODIR} (@command{gnatfind})
13341 When searching for library and object files, look in directory
13342 DIR. The order in which library files are searched is the same as for
13343 @command{gnatmake}.
13345 @item -nostdinc
13346 @cindex @option{-nostdinc} (@command{gnatfind})
13347 Do not look for sources in the system default directory.
13349 @item -nostdlib
13350 @cindex @option{-nostdlib} (@command{gnatfind})
13351 Do not look for library files in the system default directory.
13353 @item --ext=@var{extension}
13354 @cindex @option{--ext} (@command{gnatfind})
13355 Specify an alternate ali file extension. The default is @code{ali} and other
13356 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13357 switch. Note that if this switch overrides the default, which means that only
13358 the new extension will be considered.
13360 @item --RTS=@var{rts-path}
13361 @cindex @option{--RTS} (@command{gnatfind})
13362 Specifies the default location of the runtime library. Same meaning as the
13363 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13365 @item ^-d^/DERIVED_TYPE_INFORMATION^
13366 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13367 If this switch is set, then @code{gnatfind} will output the parent type
13368 reference for each matching derived types.
13370 @item ^-e^/EXPRESSIONS^
13371 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13372 By default, @code{gnatfind} accept the simple regular expression set for
13373 @samp{pattern}. If this switch is set, then the pattern will be
13374 considered as full Unix-style regular expression.
13376 @item ^-f^/FULL_PATHNAME^
13377 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13378 If this switch is set, the output file names will be preceded by their
13379 directory (if the file was found in the search path). If this switch is
13380 not set, the directory will not be printed.
13382 @item ^-g^/IGNORE_LOCALS^
13383 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13384 If this switch is set, information is output only for library-level
13385 entities, ignoring local entities. The use of this switch may accelerate
13386 @code{gnatfind} and @code{gnatxref}.
13388 @item -IDIR
13389 @cindex @option{-IDIR} (@command{gnatfind})
13390 Equivalent to @samp{-aODIR -aIDIR}.
13392 @item -pFILE
13393 @cindex @option{-pFILE} (@command{gnatfind})
13394 Specify a project file (@pxref{GNAT Project Manager}) to use.
13395 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13396 project file in the current directory.
13398 If a project file is either specified or found by the tools, then the content
13399 of the source directory and object directory lines are added as if they
13400 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13401 @samp{^-aO^/OBJECT_SEARCH^}.
13403 @item ^-r^/REFERENCES^
13404 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13405 By default, @code{gnatfind} will output only the information about the
13406 declaration, body or type completion of the entities. If this switch is
13407 set, the @code{gnatfind} will locate every reference to the entities in
13408 the files specified on the command line (or in every file in the search
13409 path if no file is given on the command line).
13411 @item ^-s^/PRINT_LINES^
13412 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13413 If this switch is set, then @code{gnatfind} will output the content
13414 of the Ada source file lines were the entity was found.
13416 @item ^-t^/TYPE_HIERARCHY^
13417 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13418 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13419 the specified type. It act like -d option but recursively from parent
13420 type to parent type. When this switch is set it is not possible to
13421 specify more than one file.
13423 @end table
13425 @noindent
13426 All these switches may be in any order on the command line, and may even
13427 appear after the file names. They need not be separated by spaces, thus
13428 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13429 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13431 As stated previously, gnatfind will search in every directory in the
13432 search path. You can force it to look only in the current directory if
13433 you specify @code{*} at the end of the command line.
13435 @node Project Files for gnatxref and gnatfind
13436 @section Project Files for @command{gnatxref} and @command{gnatfind}
13438 @noindent
13439 Project files allow a programmer to specify how to compile its
13440 application, where to find sources, etc.  These files are used
13441 @ifclear vms
13442 primarily by GPS, but they can also be used
13443 @end ifclear
13444 by the two tools
13445 @code{gnatxref} and @code{gnatfind}.
13447 A project file name must end with @file{.gpr}. If a single one is
13448 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13449 extract the information from it. If multiple project files are found, none of
13450 them is read, and you have to use the @samp{-p} switch to specify the one
13451 you want to use.
13453 The following lines can be included, even though most of them have default
13454 values which can be used in most cases.
13455 The lines can be entered in any order in the file.
13456 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13457 each line. If you have multiple instances, only the last one is taken into
13458 account.
13460 @table @code
13461 @item src_dir=DIR
13462 [default: @code{"^./^[]^"}]
13463 specifies a directory where to look for source files. Multiple @code{src_dir}
13464 lines can be specified and they will be searched in the order they
13465 are specified.
13467 @item obj_dir=DIR
13468 [default: @code{"^./^[]^"}]
13469 specifies a directory where to look for object and library files. Multiple
13470 @code{obj_dir} lines can be specified, and they will be searched in the order
13471 they are specified
13473 @item comp_opt=SWITCHES
13474 [default: @code{""}]
13475 creates a variable which can be referred to subsequently by using
13476 the @code{$@{comp_opt@}} notation. This is intended to store the default
13477 switches given to @command{gnatmake} and @command{gcc}.
13479 @item bind_opt=SWITCHES
13480 [default: @code{""}]
13481 creates a variable which can be referred to subsequently by using
13482 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13483 switches given to @command{gnatbind}.
13485 @item link_opt=SWITCHES
13486 [default: @code{""}]
13487 creates a variable which can be referred to subsequently by using
13488 the @samp{$@{link_opt@}} notation. This is intended to store the default
13489 switches given to @command{gnatlink}.
13491 @item main=EXECUTABLE
13492 [default: @code{""}]
13493 specifies the name of the executable for the application. This variable can
13494 be referred to in the following lines by using the @samp{$@{main@}} notation.
13496 @ifset vms
13497 @item comp_cmd=COMMAND
13498 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13499 @end ifset
13500 @ifclear vms
13501 @item comp_cmd=COMMAND
13502 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13503 @end ifclear
13504 specifies the command used to compile a single file in the application.
13506 @ifset vms
13507 @item make_cmd=COMMAND
13508 [default: @code{"GNAT MAKE $@{main@}
13509 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13510 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13511 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13512 @end ifset
13513 @ifclear vms
13514 @item make_cmd=COMMAND
13515 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13516 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13517 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13518 @end ifclear
13519 specifies the command used to recompile the whole application.
13521 @item run_cmd=COMMAND
13522 [default: @code{"$@{main@}"}]
13523 specifies the command used to run the application.
13525 @item debug_cmd=COMMAND
13526 [default: @code{"gdb $@{main@}"}]
13527 specifies the command used to debug the application
13529 @end table
13531 @noindent
13532 @command{gnatxref} and @command{gnatfind} only take into account the
13533 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13535 @node Regular Expressions in gnatfind and gnatxref
13536 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13538 @noindent
13539 As specified in the section about @command{gnatfind}, the pattern can be a
13540 regular expression. Actually, there are to set of regular expressions
13541 which are recognized by the program:
13543 @table @code
13544 @item globbing patterns
13545 These are the most usual regular expression. They are the same that you
13546 generally used in a Unix shell command line, or in a DOS session.
13548 Here is a more formal grammar:
13549 @smallexample
13550 @group
13551 @iftex
13552 @leftskip=.5cm
13553 @end iftex
13554 regexp ::= term
13555 term   ::= elmt            -- matches elmt
13556 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13557 term   ::= *               -- any string of 0 or more characters
13558 term   ::= ?               -- matches any character
13559 term   ::= [char @{char@}]   -- matches any character listed
13560 term   ::= [char - char]   -- matches any character in range
13561 @end group
13562 @end smallexample
13564 @item full regular expression
13565 The second set of regular expressions is much more powerful. This is the
13566 type of regular expressions recognized by utilities such a @file{grep}.
13568 The following is the form of a regular expression, expressed in Ada
13569 reference manual style BNF is as follows
13571 @smallexample
13572 @iftex
13573 @leftskip=.5cm
13574 @end iftex
13575 @group
13576 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
13578 term ::= item @{item@}       -- concatenation (item then item)
13580 item ::= elmt              -- match elmt
13581 item ::= elmt *            -- zero or more elmt's
13582 item ::= elmt +            -- one or more elmt's
13583 item ::= elmt ?            -- matches elmt or nothing
13584 @end group
13585 @group
13586 elmt ::= nschar            -- matches given character
13587 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13588 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13589 elmt ::= [char - char]     -- matches chars in given range
13590 elmt ::= \ char            -- matches given character
13591 elmt ::= .                 -- matches any single character
13592 elmt ::= ( regexp )        -- parens used for grouping
13594 char ::= any character, including special characters
13595 nschar ::= any character except ()[].*+?^^^
13596 @end group
13597 @end smallexample
13599 Following are a few examples:
13601 @table @samp
13602 @item abcde|fghi
13603 will match any of the two strings @samp{abcde} and @samp{fghi},
13605 @item abc*d
13606 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13607 @samp{abcccd}, and so on,
13609 @item [a-z]+
13610 will match any string which has only lowercase characters in it (and at
13611 least one character.
13613 @end table
13614 @end table
13616 @node Examples of gnatxref Usage
13617 @section Examples of @code{gnatxref} Usage
13619 @subsection General Usage
13621 @noindent
13622 For the following examples, we will consider the following units:
13624 @smallexample @c ada
13625 @group
13626 @cartouche
13627 main.ads:
13628 1: with Bar;
13629 2: package Main is
13630 3:     procedure Foo (B : in Integer);
13631 4:     C : Integer;
13632 5: private
13633 6:     D : Integer;
13634 7: end Main;
13636 main.adb:
13637 1: package body Main is
13638 2:     procedure Foo (B : in Integer) is
13639 3:     begin
13640 4:        C := B;
13641 5:        D := B;
13642 6:        Bar.Print (B);
13643 7:        Bar.Print (C);
13644 8:     end Foo;
13645 9: end Main;
13647 bar.ads:
13648 1: package Bar is
13649 2:     procedure Print (B : Integer);
13650 3: end bar;
13651 @end cartouche
13652 @end group
13653 @end smallexample
13655 @table @code
13657 @noindent
13658 The first thing to do is to recompile your application (for instance, in
13659 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13660 the cross-referencing information.
13661 You can then issue any of the following commands:
13663 @item gnatxref main.adb
13664 @code{gnatxref} generates cross-reference information for main.adb
13665 and every unit 'with'ed by main.adb.
13667 The output would be:
13668 @smallexample
13669 @iftex
13670 @leftskip=0cm
13671 @end iftex
13672 B                                                      Type: Integer
13673   Decl: bar.ads           2:22
13674 B                                                      Type: Integer
13675   Decl: main.ads          3:20
13676   Body: main.adb          2:20
13677   Ref:  main.adb          4:13     5:13     6:19
13678 Bar                                                    Type: Unit
13679   Decl: bar.ads           1:9
13680   Ref:  main.adb          6:8      7:8
13681        main.ads           1:6
13682 C                                                      Type: Integer
13683   Decl: main.ads          4:5
13684   Modi: main.adb          4:8
13685   Ref:  main.adb          7:19
13686 D                                                      Type: Integer
13687   Decl: main.ads          6:5
13688   Modi: main.adb          5:8
13689 Foo                                                    Type: Unit
13690   Decl: main.ads          3:15
13691   Body: main.adb          2:15
13692 Main                                                    Type: Unit
13693   Decl: main.ads          2:9
13694   Body: main.adb          1:14
13695 Print                                                   Type: Unit
13696   Decl: bar.ads           2:15
13697   Ref:  main.adb          6:12     7:12
13698 @end smallexample
13700 @noindent
13701 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13702 its body is in main.adb, line 1, column 14 and is not referenced any where.
13704 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13705 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13707 @item gnatxref package1.adb package2.ads
13708 @code{gnatxref} will generates cross-reference information for
13709 package1.adb, package2.ads and any other package 'with'ed by any
13710 of these.
13712 @end table
13714 @ifclear vms
13715 @subsection Using gnatxref with vi
13717 @code{gnatxref} can generate a tags file output, which can be used
13718 directly from @command{vi}. Note that the standard version of @command{vi}
13719 will not work properly with overloaded symbols. Consider using another
13720 free implementation of @command{vi}, such as @command{vim}.
13722 @smallexample
13723 $ gnatxref -v gnatfind.adb > tags
13724 @end smallexample
13726 @noindent
13727 will generate the tags file for @code{gnatfind} itself (if the sources
13728 are in the search path!).
13730 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13731 (replacing @var{entity} by whatever you are looking for), and vi will
13732 display a new file with the corresponding declaration of entity.
13733 @end ifclear
13735 @node Examples of gnatfind Usage
13736 @section Examples of @code{gnatfind} Usage
13738 @table @code
13740 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13741 Find declarations for all entities xyz referenced at least once in
13742 main.adb. The references are search in every library file in the search
13743 path.
13745 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13746 switch is set)
13748 The output will look like:
13749 @smallexample
13750 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13751 ^directory/^[directory]^main.adb:24:10: xyz <= body
13752 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13753 @end smallexample
13755 @noindent
13756 that is to say, one of the entities xyz found in main.adb is declared at
13757 line 12 of main.ads (and its body is in main.adb), and another one is
13758 declared at line 45 of foo.ads
13760 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13761 This is the same command as the previous one, instead @code{gnatfind} will
13762 display the content of the Ada source file lines.
13764 The output will look like:
13766 @smallexample
13767 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13768    procedure xyz;
13769 ^directory/^[directory]^main.adb:24:10: xyz <= body
13770    procedure xyz is
13771 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13772    xyz : Integer;
13773 @end smallexample
13775 @noindent
13776 This can make it easier to find exactly the location your are looking
13777 for.
13779 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13780 Find references to all entities containing an x that are
13781 referenced on line 123 of main.ads.
13782 The references will be searched only in main.ads and foo.adb.
13784 @item gnatfind main.ads:123
13785 Find declarations and bodies for all entities that are referenced on
13786 line 123 of main.ads.
13788 This is the same as @code{gnatfind "*":main.adb:123}.
13790 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13791 Find the declaration for the entity referenced at column 45 in
13792 line 123 of file main.adb in directory mydir. Note that it
13793 is usual to omit the identifier name when the column is given,
13794 since the column position identifies a unique reference.
13796 The column has to be the beginning of the identifier, and should not
13797 point to any character in the middle of the identifier.
13799 @end table
13801 @c *********************************
13802 @node The GNAT Pretty-Printer gnatpp
13803 @chapter The GNAT Pretty-Printer @command{gnatpp}
13804 @findex gnatpp
13805 @cindex Pretty-Printer
13807 @menu
13808 * Switches for gnatpp::
13809 * Formatting Rules::
13810 @end menu
13812 @noindent
13813 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13814 for source reformatting / pretty-printing.
13815 It takes an Ada source file as input and generates a reformatted
13816 version as output.
13817 You can specify various style directives via switches; e.g.,
13818 identifier case conventions, rules of indentation, and comment layout.
13820 Note: A newly-redesigned set of formatting algorithms used by gnatpp
13821 is now available.
13822 To invoke the new experimental formatting algorithms, use the
13823 @option{--pp-new} switch.
13824 The default is @option{--pp-old}; that is, gnatpp uses the old
13825 formatting algorithms by default.
13826 We intend to make @option{--pp-new} the default at some point.
13828 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13829 tree for the input source and thus requires the input to be syntactically and
13830 semantically legal.
13831 If this condition is not met, @command{gnatpp} will terminate with an
13832 error message; no output file will be generated.
13834 @command{gnatpp} cannot process sources that contain
13835 preprocessing directives.
13837 If the compilation unit
13838 contained in the input source depends semantically upon units located
13839 outside the current directory, you have to provide the source search path
13840 when invoking @command{gnatpp}, if these units are contained in files with
13841 names that do not follow the GNAT file naming rules, you have to provide
13842 the configuration file describing the corresponding naming scheme;
13843 see the description of the @command{gnatpp}
13844 switches below. Another possibility is to use a project file and to
13845 call @command{gnatpp} through the @command{gnat} driver
13846 (see @ref{The GNAT Driver and Project Files}).
13848 The @command{gnatpp} command has the form
13850 @smallexample
13851 @c $ gnatpp @ovar{switches} @var{filename}
13852 @c Expanding @ovar macro inline (explanation in macro def comments)
13853 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13854 @end smallexample
13856 @noindent
13857 where
13858 @itemize @bullet
13859 @item
13860 @var{switches} is an optional sequence of switches defining such properties as
13861 the formatting rules, the source search path, and the destination for the
13862 output source file
13864 @item
13865 @var{filename} is the name (including the extension) of the source file to
13866 reformat; ``wildcards'' or several file names on the same gnatpp command are
13867 allowed.  The file name may contain path information; it does not have to
13868 follow the GNAT file naming rules
13870 @item
13871 @samp{@var{gcc_switches}} is a list of switches for
13872 @command{gcc}. They will be passed on to all compiler invocations made by
13873 @command{gnatelim} to generate the ASIS trees. Here you can provide
13874 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13875 use the @option{-gnatec} switch to set the configuration file,
13876 use the @option{-gnat05} switch if sources should be compiled in
13877 Ada 2005 mode  etc.
13878 @end itemize
13880 @node Switches for gnatpp
13881 @section Switches for @command{gnatpp}
13883 @noindent
13884 The following subsections describe the various switches accepted by
13885 @command{gnatpp}, organized by category.
13887 @ifclear vms
13888 You specify a switch by supplying a name and generally also a value.
13889 In many cases the values for a switch with a given name are incompatible with
13890 each other
13891 (for example the switch that controls the casing of a reserved word may have
13892 exactly one value: upper case, lower case, or
13893 mixed case) and thus exactly one such switch can be in effect for an
13894 invocation of @command{gnatpp}.
13895 If more than one is supplied, the last one is used.
13896 However, some values for the same switch are mutually compatible.
13897 You may supply several such switches to @command{gnatpp}, but then
13898 each must be specified in full, with both the name and the value.
13899 Abbreviated forms (the name appearing once, followed by each value) are
13900 not permitted.
13901 For example, to set
13902 the alignment of the assignment delimiter both in declarations and in
13903 assignment statements, you must write @option{-A2A3}
13904 (or @option{-A2 -A3}), but not @option{-A23}.
13905 @end ifclear
13907 @ifset vms
13908 In many cases the set of options for a given qualifier are incompatible with
13909 each other (for example the qualifier that controls the casing of a reserved
13910 word may have exactly one option, which specifies either upper case, lower
13911 case, or mixed case), and thus exactly one such option can be in effect for
13912 an invocation of @command{gnatpp}.
13913 If more than one is supplied, the last one is used.
13914 However, some qualifiers have options that are mutually compatible,
13915 and then you may then supply several such options when invoking
13916 @command{gnatpp}.
13917 @end ifset
13919 In most cases, it is obvious whether or not the
13920 ^values for a switch with a given name^options for a given qualifier^
13921 are compatible with each other.
13922 When the semantics might not be evident, the summaries below explicitly
13923 indicate the effect.
13925 @menu
13926 * Alignment Control::
13927 * Casing Control::
13928 * Construct Layout Control::
13929 * General Text Layout Control::
13930 * Other Formatting Options::
13931 * Setting the Source Search Path::
13932 * Output File Control::
13933 * Other gnatpp Switches::
13934 @end menu
13936 @node Alignment Control
13937 @subsection Alignment Control
13938 @cindex Alignment control in @command{gnatpp}
13940 @noindent
13941 Programs can be easier to read if certain constructs are vertically aligned.
13942 By default all alignments are set ON.
13943 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13944 OFF, and then use one or more of the other
13945 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13946 to activate alignment for specific constructs.
13948 @table @option
13949 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13951 @ifset vms
13952 @item /ALIGN=ON
13953 Set all alignments to ON
13954 @end ifset
13956 @item ^-A0^/ALIGN=OFF^
13957 Set all alignments to OFF
13959 @item ^-A1^/ALIGN=COLONS^
13960 Align @code{:} in declarations
13962 @item ^-A2^/ALIGN=DECLARATIONS^
13963 Align @code{:=} in initializations in declarations
13965 @item ^-A3^/ALIGN=STATEMENTS^
13966 Align @code{:=} in assignment statements
13968 @item ^-A4^/ALIGN=ARROWS^
13969 Align @code{=>} in associations
13971 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13972 Align @code{at} keywords in the component clauses in record
13973 representation clauses
13974 @end table
13976 @noindent
13977 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13978 is allowed.
13980 @node Casing Control
13981 @subsection Casing Control
13982 @cindex Casing control in @command{gnatpp}
13984 @noindent
13985 @command{gnatpp} allows you to specify the casing for reserved words,
13986 pragma names, attribute designators and identifiers.
13987 For identifiers you may define a
13988 general rule for name casing but also override this rule
13989 via a set of dictionary files.
13991 Three types of casing are supported: lower case, upper case, and mixed case.
13992 Lower and upper case are self-explanatory (but since some letters in
13993 Latin1 and other GNAT-supported character sets
13994 exist only in lower-case form, an upper case conversion will have no
13995 effect on them.)
13996 ``Mixed case'' means that the first letter, and also each letter immediately
13997 following an underscore, are converted to their uppercase forms;
13998 all the other letters are converted to their lowercase forms.
14000 @table @option
14001 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14002 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14003 Attribute designators are lower case
14005 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14006 Attribute designators are upper case
14008 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14009 Attribute designators are mixed case (this is the default)
14011 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14012 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14013 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14014 lower case (this is the default)
14016 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14017 Keywords are upper case
14019 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14020 @item ^-nD^/NAME_CASING=AS_DECLARED^
14021 Name casing for defining occurrences are as they appear in the source file
14022 (this is the default)
14024 @item ^-nU^/NAME_CASING=UPPER_CASE^
14025 Names are in upper case
14027 @item ^-nL^/NAME_CASING=LOWER_CASE^
14028 Names are in lower case
14030 @item ^-nM^/NAME_CASING=MIXED_CASE^
14031 Names are in mixed case
14033 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
14034 @item ^-neD^/ENUM_CASING=AS_DECLARED^
14035 Enumeration literal casing for defining occurrences are as they appear in the
14036 source file. Overrides ^-n^/NAME_CASING^ casing setting.
14038 @item ^-neU^/ENUM_CASING=UPPER_CASE^
14039 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
14040 setting.
14042 @item ^-neL^/ENUM_CASING=LOWER_CASE^
14043 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
14044 setting.
14046 @item ^-neM^/ENUM_CASING=MIXED_CASE^
14047 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
14048 setting.
14050 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
14051 @item ^-neD^/TYPE_CASING=AS_DECLARED^
14052 Names introduced by type and subtype declarations are always
14053 cased as they appear in the declaration in the source file.
14054 Overrides ^-n^/NAME_CASING^ casing setting.
14056 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
14057 Names introduced by type and subtype declarations are always in
14058 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14060 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
14061 Names introduced by type and subtype declarations are always in
14062 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14064 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
14065 Names introduced by type and subtype declarations are always in
14066 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14068 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
14069 Names introduced by number declarations are always in
14070 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14072 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
14073 Names introduced by number declarations are always in
14074 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14076 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
14077 Names introduced by number declarations are always in
14078 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14080 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14081 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14082 Pragma names are lower case
14084 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14085 Pragma names are upper case
14087 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14088 Pragma names are mixed case (this is the default)
14090 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14091 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14092 Use @var{file} as a @emph{dictionary file} that defines
14093 the casing for a set of specified names,
14094 thereby overriding the effect on these names by
14095 any explicit or implicit
14096 ^-n^/NAME_CASING^ switch.
14097 To supply more than one dictionary file,
14098 use ^several @option{-D} switches^a list of files as options^.
14100 @noindent
14101 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14102 to define the casing for the Ada predefined names and
14103 the names declared in the GNAT libraries.
14105 @item ^-D-^/SPECIFIC_CASING^
14106 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14107 Do not use the default dictionary file;
14108 instead, use the casing
14109 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14110 dictionary file(s)
14111 @end table
14113 @noindent
14114 The structure of a dictionary file, and details on the conventions
14115 used in the default dictionary file, are defined in @ref{Name Casing}.
14117 The @option{^-D-^/SPECIFIC_CASING^} and
14118 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14119 compatible.
14121 @node Construct Layout Control
14122 @subsection Construct Layout Control
14123 @cindex Layout control in @command{gnatpp}
14125 @noindent
14126 This group of @command{gnatpp} switches controls the layout of comments and
14127 complex syntactic constructs.  See @ref{Formatting Comments} for details
14128 on their effect.
14130 @table @option
14131 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14132 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14133 All the comments remain unchanged
14135 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14136 GNAT-style comment line indentation (this is the default).
14138 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14139 Reference-manual comment line indentation.
14141 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14142 GNAT-style comment beginning
14144 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14145 Reformat comment blocks
14147 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14148 Keep unchanged special form comments
14150 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14151 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14152 GNAT-style layout (this is the default)
14154 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14155 Compact layout
14157 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14158 Uncompact layout
14160 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
14161 @item ^-N^/NOTABS^
14162 All the VT characters are removed from the comment text. All the HT characters
14163 are expanded with the sequences of space characters to get to the next tab
14164 stops.
14166 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14167 @item ^--no-separate-is^/NO_SEPARATE_IS^
14168 Do not place the keyword @code{is} on a separate line in a subprogram body in
14169 case if the spec occupies more than one line.
14171 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
14172 @item ^--separate-label^/SEPARATE_LABEL^
14173 Place statement label(s) on a separate line, with the following statement
14174 on the next line.
14176 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14177 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14178 Place the keyword @code{loop} in FOR and WHILE loop statements and the
14179 keyword @code{then} in IF statements on a separate line.
14181 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14182 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14183 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14184 keyword @code{then} in IF statements on a separate line. This option is
14185 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14187 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14188 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
14189 Start each USE clause in a context clause from a separate line.
14191 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
14192 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
14193 Use a separate line for a loop or block statement name, but do not use an extra
14194 indentation level for the statement itself.
14196 @end table
14198 @ifclear vms
14199 @noindent
14200 The @option{-c1} and @option{-c2} switches are incompatible.
14201 The @option{-c3} and @option{-c4} switches are compatible with each other and
14202 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14203 the other comment formatting switches.
14205 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14206 @end ifclear
14208 @ifset vms
14209 @noindent
14210 For the @option{/COMMENTS_LAYOUT} qualifier:
14211 @itemize @bullet
14212 @item
14213 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14214 @item
14215 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14216 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14217 @end itemize
14219 @noindent
14220 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14221 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14222 @end ifset
14224 @node General Text Layout Control
14225 @subsection General Text Layout Control
14227 @noindent
14228 These switches allow control over line length and indentation.
14230 @table @option
14231 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14232 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14233 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14235 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14236 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14237 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14239 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14240 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14241 Indentation level for continuation lines (relative to the line being
14242 continued), @var{nnn} from 1@dots{}9.
14243 The default
14244 value is one less than the (normal) indentation level, unless the
14245 indentation is set to 1 (in which case the default value for continuation
14246 line indentation is also 1)
14247 @end table
14249 @node Other Formatting Options
14250 @subsection Other Formatting Options
14252 @noindent
14253 These switches control the inclusion of missing end/exit labels, and
14254 the indentation level in @b{case} statements.
14256 @table @option
14257 @item ^-e^/NO_MISSED_LABELS^
14258 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14259 Do not insert missing end/exit labels. An end label is the name of
14260 a construct that may optionally be repeated at the end of the
14261 construct's declaration;
14262 e.g., the names of packages, subprograms, and tasks.
14263 An exit label is the name of a loop that may appear as target
14264 of an exit statement within the loop.
14265 By default, @command{gnatpp} inserts these end/exit labels when
14266 they are absent from the original source. This option suppresses such
14267 insertion, so that the formatted source reflects the original.
14269 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14270 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14271 Insert a Form Feed character after a pragma Page.
14273 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
14274 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14275 Do not use an additional indentation level for @b{case} alternatives
14276 and variants if there are @var{nnn} or more (the default
14277 value is 10).
14278 If @var{nnn} is 0, an additional indentation level is
14279 used for @b{case} alternatives and variants regardless of their number.
14281 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14282 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14283 If the number of parameter associations is greater than @var{nnn} and if at
14284 least one association uses named notation, start each association from
14285 a new line. If @var{nnn} is 0, no check for the number of associations
14286 is made, this is the default.
14288 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14289 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14290 If the number of parameter specifications is greater than @var{nnn}
14291 (or equal to @var{nnn} in case of a function), start each specification from
14292 a new line. The default for @var{nnn} is 3.
14293 @end table
14295 @node Setting the Source Search Path
14296 @subsection Setting the Source Search Path
14298 @noindent
14299 To define the search path for the input source file, @command{gnatpp}
14300 uses the same switches as the GNAT compiler, with the same effects.
14302 @table @option
14303 @item ^-I^/SEARCH=^@var{dir}
14304 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14305 The same as the corresponding gcc switch
14307 @item ^-I-^/NOCURRENT_DIRECTORY^
14308 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14309 The same as the corresponding gcc switch
14311 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14312 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14313 The same as the corresponding gcc switch
14315 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14316 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14317 The same as the corresponding gcc switch
14319 @end table
14321 @node Output File Control
14322 @subsection Output File Control
14324 @noindent
14325 By default the output is sent to the file whose name is obtained by appending
14326 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14327 (if the file with this name already exists, it is unconditionally overwritten).
14328 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14329 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14330 as output file.
14331 The output may be redirected by the following switches:
14333 @table @option
14334 @item ^-pipe^/STANDARD_OUTPUT^
14335 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14336 Send the output to @code{Standard_Output}
14338 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14339 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14340 Write the output into @var{output_file}.
14341 If @var{output_file} already exists, @command{gnatpp} terminates without
14342 reading or processing the input file.
14344 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14345 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14346 Write the output into @var{output_file}, overwriting the existing file
14347 (if one is present).
14349 @item ^-r^/REPLACE^
14350 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14351 Replace the input source file with the reformatted output, and copy the
14352 original input source into the file whose name is obtained by appending the
14353 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14354 If a file with this name already exists, @command{gnatpp} terminates without
14355 reading or processing the input file.
14357 @item ^-rf^/OVERRIDING_REPLACE^
14358 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14359 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14360 already exists, it is overwritten.
14362 @item ^-rnb^/REPLACE_NO_BACKUP^
14363 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
14364 Replace the input source file with the reformatted output without
14365 creating any backup copy of the input source.
14367 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14368 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14369 Specifies the format of the reformatted output file. The @var{xxx}
14370 ^string specified with the switch^option^ may be either
14371 @itemize @bullet
14372 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14373 @item ``@option{^crlf^CRLF^}''
14374 the same as @option{^crlf^CRLF^}
14375 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14376 @item ``@option{^lf^LF^}''
14377 the same as @option{^unix^UNIX^}
14378 @end itemize
14380 @item ^-W^/RESULT_ENCODING=^@var{e}
14381 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14382 Specify the wide character encoding method used to write the code in the
14383 result file
14384 @var{e} is one of the following:
14386 @itemize @bullet
14388 @item ^h^HEX^
14389 Hex encoding
14391 @item ^u^UPPER^
14392 Upper half encoding
14394 @item ^s^SHIFT_JIS^
14395 Shift/JIS encoding
14397 @item ^e^EUC^
14398 EUC encoding
14400 @item ^8^UTF8^
14401 UTF-8 encoding
14403 @item ^b^BRACKETS^
14404 Brackets encoding (default value)
14405 @end itemize
14407 @end table
14409 @noindent
14410 Options @option{^-pipe^/STANDARD_OUTPUT^},
14411 @option{^-o^/OUTPUT^} and
14412 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14413 contains only one file to reformat.
14414 Option
14415 @option{^--eol^/END_OF_LINE^}
14417 @option{^-W^/RESULT_ENCODING^}
14418 cannot be used together
14419 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14421 @node Other gnatpp Switches
14422 @subsection Other @code{gnatpp} Switches
14424 @noindent
14425 The additional @command{gnatpp} switches are defined in this subsection.
14427 @table @option
14428 @item --version
14429 @cindex @option{--version} @command{gnatpp}
14430 Display Copyright and version, then exit disregarding all other options.
14432 @item --help
14433 @cindex @option{--help} @command{gnatpp}
14434 Display usage, then exit disregarding all other options.
14436 @item --pp-new
14437 @cindex @option{--pp-new} @command{gnatpp}
14438 Use the new experimental formatting algorithms.
14440 @item --pp-old
14441 @cindex @option{--pp-old} @command{gnatpp}
14442 Use the old formatting algorithms. This is the default.
14444 @item ^-files @var{filename}^/FILES=@var{filename}^
14445 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14446 Take the argument source files from the specified file. This file should be an
14447 ordinary text file containing file names separated by spaces or
14448 line breaks. You can use this switch more than once in the same call to
14449 @command{gnatpp}. You also can combine this switch with an explicit list of
14450 files.
14452 @item ^-v^/VERBOSE^
14453 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14454 Verbose mode;
14455 @command{gnatpp} generates version information and then
14456 a trace of the actions it takes to produce or obtain the ASIS tree.
14458 @item ^-w^/WARNINGS^
14459 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14460 Warning mode;
14461 @command{gnatpp} generates a warning whenever it cannot provide
14462 a required layout in the result source.
14463 @end table
14465 @node Formatting Rules
14466 @section Formatting Rules
14468 @noindent
14469 The following subsections show how @command{gnatpp} treats ``white space'',
14470 comments, program layout, and name casing.
14471 They provide the detailed descriptions of the switches shown above.
14473 @menu
14474 * White Space and Empty Lines::
14475 * Formatting Comments::
14476 * Construct Layout::
14477 * Name Casing::
14478 @end menu
14480 @node White Space and Empty Lines
14481 @subsection White Space and Empty Lines
14483 @noindent
14484 @command{gnatpp} does not have an option to control space characters.
14485 It will add or remove spaces according to the style illustrated by the
14486 examples in the @cite{Ada Reference Manual}.
14488 The only format effectors
14489 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14490 that will appear in the output file are platform-specific line breaks,
14491 and also format effectors within (but not at the end of) comments.
14492 In particular, each horizontal tab character that is not inside
14493 a comment will be treated as a space and thus will appear in the
14494 output file as zero or more spaces depending on
14495 the reformatting of the line in which it appears.
14496 The only exception is a Form Feed character, which is inserted after a
14497 pragma @code{Page} when @option{-ff} is set.
14499 The output file will contain no lines with trailing ``white space'' (spaces,
14500 format effectors).
14502 Empty lines in the original source are preserved
14503 only if they separate declarations or statements.
14504 In such contexts, a
14505 sequence of two or more empty lines is replaced by exactly one empty line.
14506 Note that a blank line will be removed if it separates two ``comment blocks''
14507 (a comment block is a sequence of whole-line comments).
14508 In order to preserve a visual separation between comment blocks, use an
14509 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14510 Likewise, if for some reason you wish to have a sequence of empty lines,
14511 use a sequence of empty comments instead.
14513 @node Formatting Comments
14514 @subsection Formatting Comments
14516 @noindent
14517 Comments in Ada code are of two kinds:
14518 @itemize @bullet
14519 @item
14520 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14521 ``white space'') on a line
14523 @item
14524 an @emph{end-of-line comment}, which follows some other Ada lexical element
14525 on the same line.
14526 @end itemize
14528 @noindent
14529 The indentation of a whole-line comment is that of either
14530 the preceding or following line in
14531 the formatted source, depending on switch settings as will be described below.
14533 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14534 between the end of the preceding Ada lexical element and the beginning
14535 of the comment as appear in the original source,
14536 unless either the comment has to be split to
14537 satisfy the line length limitation, or else the next line contains a
14538 whole line comment that is considered a continuation of this end-of-line
14539 comment (because it starts at the same position).
14540 In the latter two
14541 cases, the start of the end-of-line comment is moved right to the nearest
14542 multiple of the indentation level.
14543 This may result in a ``line overflow'' (the right-shifted comment extending
14544 beyond the maximum line length), in which case the comment is split as
14545 described below.
14547 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14548 (GNAT-style comment line indentation)
14549 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14550 (reference-manual comment line indentation).
14551 With reference-manual style, a whole-line comment is indented as if it
14552 were a declaration or statement at the same place
14553 (i.e., according to the indentation of the preceding line(s)).
14554 With GNAT style, a whole-line comment that is immediately followed by an
14555 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14556 word @b{begin}, is indented based on the construct that follows it.
14558 For example:
14559 @smallexample @c ada
14560 @cartouche
14561 if A then
14562     null;
14563        -- some comment
14564 else
14565    null;
14566 end if;
14567 @end cartouche
14568 @end smallexample
14570 @noindent
14571 Reference-manual indentation produces:
14573 @smallexample @c ada
14574 @cartouche
14575 if A then
14576    null;
14577    --  some comment
14578 else
14579    null;
14580 end if;
14581 @end cartouche
14582 @end smallexample
14584 @noindent
14585 while GNAT-style indentation produces:
14587 @smallexample @c ada
14588 @cartouche
14589 if A then
14590    null;
14591 --  some comment
14592 else
14593    null;
14594 end if;
14595 @end cartouche
14596 @end smallexample
14598 @noindent
14599 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14600 (GNAT style comment beginning) has the following
14601 effect:
14603 @itemize @bullet
14604 @item
14605 For each whole-line comment that does not end with two hyphens,
14606 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14607 to ensure that there are at least two spaces between these hyphens and the
14608 first non-blank character of the comment.
14609 @end itemize
14611 @noindent
14612 For an end-of-line comment, if in the original source the next line is a
14613 whole-line comment that starts at the same position
14614 as the end-of-line comment,
14615 then the whole-line comment (and all whole-line comments
14616 that follow it and that start at the same position)
14617 will start at this position in the output file.
14619 @noindent
14620 That is, if in the original source we have:
14622 @smallexample @c ada
14623 @cartouche
14624 begin
14625 A := B + C;            --  B must be in the range Low1..High1
14626                        --  C must be in the range Low2..High2
14627              --B+C will be in the range Low1+Low2..High1+High2
14628 X := X + 1;
14629 @end cartouche
14630 @end smallexample
14632 @noindent
14633 Then in the formatted source we get
14635 @smallexample @c ada
14636 @cartouche
14637 begin
14638    A := B + C;            --  B must be in the range Low1..High1
14639                           --  C must be in the range Low2..High2
14640    --  B+C will be in the range Low1+Low2..High1+High2
14641    X := X + 1;
14642 @end cartouche
14643 @end smallexample
14645 @noindent
14646 A comment that exceeds the line length limit will be split.
14647 Unless switch
14648 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14649 the line belongs to a reformattable block, splitting the line generates a
14650 @command{gnatpp} warning.
14651 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14652 comments may be reformatted in typical
14653 word processor style (that is, moving words between lines and putting as
14654 many words in a line as possible).
14656 @noindent
14657 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
14658 that has a special format (that is, a character that is neither a letter nor digit
14659 not white space nor line break immediately following the leading @code{--} of
14660 the comment) should be without any change moved from the argument source
14661 into reformatted source. This switch allows to preserve comments that are used
14662 as a special marks in the code (e.g.@: SPARK annotation).
14664 @node Construct Layout
14665 @subsection Construct Layout
14667 @noindent
14668 In several cases the suggested layout in the Ada Reference Manual includes
14669 an extra level of indentation that many programmers prefer to avoid. The
14670 affected cases include:
14672 @itemize @bullet
14674 @item Record type declaration (RM 3.8)
14676 @item Record representation clause (RM 13.5.1)
14678 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
14680 @item Block statement in case if a block has a statement identifier (RM 5.6)
14681 @end itemize
14683 @noindent
14684 In compact mode (when GNAT style layout or compact layout is set),
14685 the pretty printer uses one level of indentation instead
14686 of two. This is achieved in the record definition and record representation
14687 clause cases by putting the @code{record} keyword on the same line as the
14688 start of the declaration or representation clause, and in the block and loop
14689 case by putting the block or loop header on the same line as the statement
14690 identifier.
14692 @noindent
14693 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14694 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14695 layout on the one hand, and uncompact layout
14696 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14697 can be illustrated by the following examples:
14699 @iftex
14700 @cartouche
14701 @multitable @columnfractions .5 .5
14702 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14704 @item
14705 @smallexample @c ada
14706 type q is record
14707    a : integer;
14708    b : integer;
14709 end record;
14710 @end smallexample
14711 @tab
14712 @smallexample @c ada
14713 type q is
14714    record
14715       a : integer;
14716       b : integer;
14717    end record;
14718 @end smallexample
14720 @item
14721 @smallexample @c ada
14722 for q use record
14723    a at 0 range  0 .. 31;
14724    b at 4 range  0 .. 31;
14725 end record;
14726 @end smallexample
14727 @tab
14728 @smallexample @c ada
14729 for q use
14730    record
14731       a at 0 range  0 .. 31;
14732       b at 4 range  0 .. 31;
14733    end record;
14734 @end smallexample
14736 @item
14737 @smallexample @c ada
14738 Block : declare
14739    A : Integer := 3;
14740 begin
14741    Proc (A, A);
14742 end Block;
14743 @end smallexample
14744 @tab
14745 @smallexample @c ada
14746 Block :
14747    declare
14748       A : Integer := 3;
14749    begin
14750       Proc (A, A);
14751    end Block;
14752 @end smallexample
14754 @item
14755 @smallexample @c ada
14756 Clear : for J in 1 .. 10 loop
14757    A (J) := 0;
14758 end loop Clear;
14759 @end smallexample
14760 @tab
14761 @smallexample @c ada
14762 Clear :
14763    for J in 1 .. 10 loop
14764       A (J) := 0;
14765    end loop Clear;
14766 @end smallexample
14767 @end multitable
14768 @end cartouche
14769 @end iftex
14771 @ifnottex
14772 @smallexample
14773 @cartouche
14774 GNAT style, compact layout              Uncompact layout
14776 type q is record                        type q is
14777    a : integer;                            record
14778    b : integer;                               a : integer;
14779 end record;                                   b : integer;
14780                                            end record;
14782 for q use record                        for q use
14783    a at 0 range  0 .. 31;                  record
14784    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
14785 end record;                                   b at 4 range  0 .. 31;
14786                                            end record;
14788 Block : declare                         Block :
14789    A : Integer := 3;                       declare
14790 begin                                         A : Integer := 3;
14791    Proc (A, A);                            begin
14792 end Block;                                    Proc (A, A);
14793                                            end Block;
14795 Clear : for J in 1 .. 10 loop           Clear :
14796    A (J) := 0;                             for J in 1 .. 10 loop
14797 end loop Clear;                               A (J) := 0;
14798                                            end loop Clear;
14799 @end cartouche
14800 @end smallexample
14801 @end ifnottex
14803 @noindent
14804 A further difference between GNAT style layout and compact layout is that
14805 GNAT style layout inserts empty lines as separation for
14806 compound statements, return statements and bodies.
14808 Note that the layout specified by
14809 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14810 for named block and loop statements overrides the layout defined by these
14811 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14812 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14813 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14815 @node Name Casing
14816 @subsection Name Casing
14818 @noindent
14819 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14820 the same casing as the corresponding defining identifier.
14822 You control the casing for defining occurrences via the
14823 @option{^-n^/NAME_CASING^} switch.
14824 @ifclear vms
14825 With @option{-nD} (``as declared'', which is the default),
14826 @end ifclear
14827 @ifset vms
14828 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14829 @end ifset
14830 defining occurrences appear exactly as in the source file
14831 where they are declared.
14832 The other ^values for this switch^options for this qualifier^ ---
14833 @option{^-nU^UPPER_CASE^},
14834 @option{^-nL^LOWER_CASE^},
14835 @option{^-nM^MIXED_CASE^} ---
14836 result in
14837 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14838 If @command{gnatpp} changes the casing of a defining
14839 occurrence, it analogously changes the casing of all the
14840 usage occurrences of this name.
14842 If the defining occurrence of a name is not in the source compilation unit
14843 currently being processed by @command{gnatpp}, the casing of each reference to
14844 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14845 switch (subject to the dictionary file mechanism described below).
14846 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14847 had affected the
14848 casing for the defining occurrence of the name.
14850 Some names may need to be spelled with casing conventions that are not
14851 covered by the upper-, lower-, and mixed-case transformations.
14852 You can arrange correct casing by placing such names in a
14853 @emph{dictionary file},
14854 and then supplying a @option{^-D^/DICTIONARY^} switch.
14855 The casing of names from dictionary files overrides
14856 any @option{^-n^/NAME_CASING^} switch.
14858 To handle the casing of Ada predefined names and the names from GNAT libraries,
14859 @command{gnatpp} assumes a default dictionary file.
14860 The name of each predefined entity is spelled with the same casing as is used
14861 for the entity in the @cite{Ada Reference Manual}.
14862 The name of each entity in the GNAT libraries is spelled with the same casing
14863 as is used in the declaration of that entity.
14865 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14866 default dictionary file.
14867 Instead, the casing for predefined and GNAT-defined names will be established
14868 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14869 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14870 will appear as just shown,
14871 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14872 To ensure that even such names are rendered in uppercase,
14873 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14874 (or else, less conveniently, place these names in upper case in a dictionary
14875 file).
14877 A dictionary file is
14878 a plain text file; each line in this file can be either a blank line
14879 (containing only space characters and ASCII.HT characters), an Ada comment
14880 line, or the specification of exactly one @emph{casing schema}.
14882 A casing schema is a string that has the following syntax:
14884 @smallexample
14885 @cartouche
14886   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14888   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14889 @end cartouche
14890 @end smallexample
14892 @noindent
14893 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14894 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14896 The casing schema string can be followed by white space and/or an Ada-style
14897 comment; any amount of white space is allowed before the string.
14899 If a dictionary file is passed as
14900 @ifclear vms
14901 the value of a @option{-D@var{file}} switch
14902 @end ifclear
14903 @ifset vms
14904 an option to the @option{/DICTIONARY} qualifier
14905 @end ifset
14906 then for every
14907 simple name and every identifier, @command{gnatpp} checks if the dictionary
14908 defines the casing for the name or for some of its parts (the term ``subword''
14909 is used below to denote the part of a name which is delimited by ``_'' or by
14910 the beginning or end of the word and which does not contain any ``_'' inside):
14912 @itemize @bullet
14913 @item
14914 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14915 the casing defined by the dictionary; no subwords are checked for this word
14917 @item
14918 for every subword @command{gnatpp} checks if the dictionary contains the
14919 corresponding string of the form @code{*@var{simple_identifier}*},
14920 and if it does, the casing of this @var{simple_identifier} is used
14921 for this subword
14923 @item
14924 if the whole name does not contain any ``_'' inside, and if for this name
14925 the dictionary contains two entries - one of the form @var{identifier},
14926 and another - of the form *@var{simple_identifier}*, then the first one
14927 is applied to define the casing of this name
14929 @item
14930 if more than one dictionary file is passed as @command{gnatpp} switches, each
14931 dictionary adds new casing exceptions and overrides all the existing casing
14932 exceptions set by the previous dictionaries
14934 @item
14935 when @command{gnatpp} checks if the word or subword is in the dictionary,
14936 this check is not case sensitive
14937 @end itemize
14939 @noindent
14940 For example, suppose we have the following source to reformat:
14942 @smallexample @c ada
14943 @cartouche
14944 procedure test is
14945    name1 : integer := 1;
14946    name4_name3_name2 : integer := 2;
14947    name2_name3_name4 : Boolean;
14948    name1_var : Float;
14949 begin
14950    name2_name3_name4 := name4_name3_name2 > name1;
14951 end;
14952 @end cartouche
14953 @end smallexample
14955 @noindent
14956 And suppose we have two dictionaries:
14958 @smallexample
14959 @cartouche
14960 @i{dict1:}
14961    NAME1
14962    *NaMe3*
14963    *Name1*
14964 @end cartouche
14966 @cartouche
14967 @i{dict2:}
14968   *NAME3*
14969 @end cartouche
14970 @end smallexample
14972 @noindent
14973 If @command{gnatpp} is called with the following switches:
14975 @smallexample
14976 @ifclear vms
14977 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14978 @end ifclear
14979 @ifset vms
14980 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14981 @end ifset
14982 @end smallexample
14984 @noindent
14985 then we will get the following name casing in the @command{gnatpp} output:
14987 @smallexample @c ada
14988 @cartouche
14989 procedure Test is
14990    NAME1             : Integer := 1;
14991    Name4_NAME3_Name2 : Integer := 2;
14992    Name2_NAME3_Name4 : Boolean;
14993    Name1_Var         : Float;
14994 begin
14995    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14996 end Test;
14997 @end cartouche
14998 @end smallexample
15000 @ifclear vms
15001 @c *********************************
15002 @node The Ada-to-XML converter gnat2xml
15003 @chapter The Ada-to-XML converter @command{gnat2xml}
15004 @findex gnat2xml
15005 @cindex XML generation
15007 @noindent
15008 The @command{gnat2xml} tool is an ASIS-based utility that converts
15009 Ada source code into XML.
15011 @menu
15012 * Switches for gnat2xml::
15013 * Driving gnat2xml with gnatmake or gprbuild::
15014 * Other Programs::
15015 * Structure of the XML::
15016 @end menu
15018 @node Switches for gnat2xml
15019 @section Switches for @command{gnat2xml}
15021 @noindent
15022 @command{gnat2xml} takes Ada source code as input, and produces XML
15023 that conforms to the schema.
15025 Usage:
15027 @smallexample
15028 gnat2xml [options] files
15029 @end smallexample
15031 ``files'' are the Ada source file names.
15033 @noindent
15034 Options:
15035 @smallexample
15037 --help -- generate usage information and quit, ignoring all other options
15039 -mdir -- generate one .xml file for each Ada source file, in directory
15040          @file{dir}. (Default is to generate the XML to standard output.)
15042 -q -- debugging version, with interspersed source, and a more
15043       compact representation of "sloc". This version does not conform
15044       to any schema.
15046 -I <include-dir>
15047     directories to search for dependencies
15048     You can also set the ADA_INCLUDE_PATH environment variable for this.
15050 -v -- verbose (print out the command line options, and the names of
15051       output files as they are generated).
15053 -t -- do not delete tree files when done (they are deleted by default).
15055 -cargs ... -- options to pass to gcc
15056 @end smallexample
15058 @noindent
15059 You can generate the ``tree files'' ahead of time using the -gnatct switch:
15061 @smallexample
15062 gnatmake -gnat2012 -gnatct *.ad[sb]
15063 @end smallexample
15065 @noindent
15066 If tree files do not exist, @command{gnat2xml} will create them by running gcc.
15067 See the ASIS documentation for more information on tree files.
15069 Example:
15071 @smallexample
15072 mkdir xml-files
15073 gnat2xml -v -mxml-files *.ad[sb] -cargs -gnat2012
15074 @end smallexample
15076 @noindent
15077 The above will create *.xml files in the @file{xml-files} subdirectory.
15078 For example, if there is an Ada package Mumble.Dumble, whose spec and
15079 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
15080 the above will produce xml-files/mumble-dumble.ads.xml and
15081 xml-files/mumble-dumble.adb.xml.
15083 @node Driving gnat2xml with gnatmake or gprbuild
15084 @section Driving @command{gnat2xml} with @command{gnatmake} or @command{gprbuild}
15086 @noindent
15087 You can use gnatmake or gprbuild to drive @command{gnat2xml} to get
15088 incremental updates of the XML files on a per-source-file basis. For
15089 example, if you already have a bunch of XML files, and then you change
15090 one source file, it will regenerate XML files only for that source
15091 file, and other source files that depend on it. Gnatmake and gprbuild
15092 take care of tracking inter-file dependencies. For example, if
15093 this.adb says @code{with That;}, then this.adb depends on that.ads.
15095 To do this, you tell gnatmake/gprbuild to pretend that
15096 @command{gnat2xml} is the Ada compiler (instead of using gcc as the
15097 Ada compiler, as is normal).
15099 To tell gnatmake to use @command{gnat2xml} instead of gcc as the
15100 ``compiler'', for example:
15102 @smallexample
15103 gnatmake -gnatc *.adb --GCC="gnat2xml -t -mxml"
15104 @end smallexample
15106 @noindent
15107 The @option{--GCC=} switch tells gnatmake that the ``compiler'' to run
15108 is @command{gnat2xml -t -mxml}. The @option{-t} switch means to keep the tree
15109 files, so they can be reused on the next run. (@command{gnat2xml}
15110 deletes them by default.) As usual, @option{-mxml} means to put the
15111 XML files in the @file{xml} subdirectory.
15113 You must give the @option{-gnatc} switch to gnatmake, which means
15114 ``compile only; do not generate object code''. Otherwise, gnatmake will
15115 complain about missing object (*.o) files; @command{gnat2xml} of
15116 course does not generate *.o files.
15118 Using gprbuild is similar: you tell it to use @command{gnat2xml}
15119 instead of gcc. First write a project file, such as my_project.gpr:
15121 @smallexample @c projectfile
15122 project My_Project is
15124    package Compiler is
15125       for Driver ("ada") use "gnat2xml";
15126       --  Use gnat2xml instead of the usual gcc.
15128       for Default_Switches ("ada") use ("-t", "-mxml");
15129       --  Same switches as in the gnatmake case.
15130    end Compiler;
15132 end My_Project;
15133 @end smallexample
15135 @noindent
15136 Then:
15138 @smallexample @c projectfile
15139 gprbuild --no-object-check -P my_project.gpr
15140 @end smallexample
15142 @noindent
15143 The @option{--no-object-check} switch serves the same purpose as
15144 @option{-gnatc} in the gnatmake case --- it tells gprbuild not to
15145 expect that the ``compiler'' (really @command{gnat2xml}) will produce
15146 *.o files.
15148 See the gprbuild documentation for information on many other things
15149 you can put in the project file, such as telling it where to find
15150 the source files.
15152 @node Other Programs
15153 @section Other Programs
15155 @noindent
15156 The distribution includes two other programs that are related to
15157 @command{gnat2xml}:
15159 @command{gnat2xsd} is the schema generator, which generates the schema
15160 to standard output, based on the structure of Ada as encoded by
15161 ASIS. You don't need to run @command{gnat2xsd} in order to use
15162 @command{gnat2xml}. To generate the schema, type:
15164 @smallexample
15165 gnat2xsd > ada-schema.xsd
15166 @end smallexample
15168 @noindent
15169 @command{gnat2xml} generates XML files that will validate against
15170 @file{ada-schema.xsd}.
15172 @command{xml2gnat} is a back-translator that translates the XML back
15173 into Ada source code. The Ada generated by @command{xml2gnat} has
15174 identical semantics to the original Ada code passed to
15175 @command{gnat2xml}. It is not textually identical, however --- for
15176 example, no attempt is made to preserve the original indentation.
15178 @node Structure of the XML
15179 @section Structure of the XML
15181 @noindent
15182 The primary documentation for the structure of the XML generated by
15183 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
15184 following documentation gives additional details needed to understand
15185 the schema and therefore the XML.
15187 The elements listed under Defining Occurrences, Usage Occurrences, and
15188 Other Elements represent the syntactic structure of the Ada program.
15189 Element names are given in lower case, with the corresponding element
15190 type Capitalized_Like_This. The element and element type names are
15191 derived directly from the ASIS enumeration type Flat_Element_Kinds,
15192 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
15193 removed. For example, the ASIS enumeration literal
15194 An_Assignment_Statement corresponds to the XML element
15195 assignment_statement of XML type Assignment_Statement.
15197 To understand the details of the schema and the corresponding XML, it is
15198 necessary to understand the ASIS standard, as well as the GNAT-specific
15199 extension to ASIS.
15201 A defining occurrence is an identifier (or character literal or operator
15202 symbol) declared by a declaration. A usage occurrence is an identifier
15203 (or ...) that references such a declared entity. For example, in:
15205 @smallexample
15206 type T is range 1..10;
15207 X, Y : constant T := 1;
15208 @end smallexample
15210 @noindent
15211 The first ``T'' is the defining occurrence of a type. The ``X'' is the
15212 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
15213 a usage occurrence referring to the defining occurrence of T.
15215 Each element has a 'sloc' (source location), and subelements for each
15216 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
15217 The types of subelements are as defined in the ASIS standard. For
15218 example, for the right-hand side of an assignment_statement we have
15219 the following comment in asis-statements.ads:
15221 @smallexample
15222 ------------------------------------------------------------------------------
15223 --  18.3  function Assignment_Expression
15224 ------------------------------------------------------------------------------
15226    function Assignment_Expression
15227      (Statement : Asis.Statement)
15228       return      Asis.Expression;
15230 ------------------------------------------------------------------------------
15232 --  Returns the expression from the right hand side of the assignment.
15234 --  Returns Element_Kinds:
15235 --       An_Expression
15236 @end smallexample
15238 @noindent
15239 The corresponding sub-element of type Assignment_Statement is:
15241 @smallexample
15242 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
15243 @end smallexample
15245 @noindent
15246 where Expression_Class is defined by an xsd:choice of all the
15247 various kinds of expression.
15249 The 'sloc' of each element indicates the starting and ending line and
15250 column numbers. Column numbers are character counts; that is, a tab
15251 counts as 1, not as however many spaces it might expand to.
15253 Subelements of type Element have names ending in ``_q'' (for ASIS
15254 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
15255 List'').
15257 Some subelements are ``Boolean''. For example, Private_Type_Definition
15258 has has_abstract_q and has_limited_q, to indicate whether those
15259 keywords are present, as in @code{type T is abstract limited
15260 private;}. False is represented by a Nil_Element. True is represented
15261 by an element type specific to that query (for example, Abstract and
15262 Limited).
15264 The root of the tree is a Compilation_Unit, with attributes:
15266 @itemize @bullet
15267 @item
15268 unit_kind, unit_class, and unit_origin. These are strings that match the
15269 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
15270 in package Asis.
15272 @item
15273 unit_full_name is the full expanded name of the unit, starting from a
15274 root library unit. So for @code{package P.Q.R is ...},
15275 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
15277 @item
15278 def_name is the same as unit_full_name for library units; for subunits,
15279 it is just the simple name.
15281 @item
15282 source_file is the name of the Ada source file. For example, for
15283 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
15284 interpret the source locations --- the ``sloc'' of all elements
15285 within this Compilation_Unit refers to line and column numbers
15286 within the named file.
15287 @end itemize
15289 @noindent
15290 Defining occurrences have these attributes:
15292 @itemize @bullet
15293 @item
15294 def_name is the simple name of the declared entity, as written in the Ada
15295 source code.
15297 @item
15298 def is a unique URI of the form:
15300  ada://kind/fully/qualified/name
15302 where:
15304  kind indicates the kind of Ada entity being declared (see below), and
15306  fully/qualified/name, is the fully qualified name of the Ada
15307  entity, with each of ``fully'', ``qualified'', and ``name'' being
15308  mangled for uniqueness. We do not document the mangling
15309  algorithm, which is subject to change; we just guarantee that the
15310  names are unique in the face of overloading.
15312 @item
15313 type is the type of the declared object, or @code{null} for
15314 declarations of things other than objects.
15315 @end itemize
15317 @noindent
15318 Usage occurrences have these attributes:
15320 @itemize @bullet
15321 @item
15322 ref_name is the same as the def_name of the corresponding defining
15323 occurrence. This attribute is not of much use, because of
15324 overloading; use ref for lookups, instead.
15326 @item
15327 ref is the same as the def of the corresponding defining
15328 occurrence.
15329 @end itemize
15331 @noindent
15332 In summary, @code{def_name} and @code{ref_name} are as in the source
15333 code of the declaration, possibly overloaded, whereas @code{def} and
15334 @code{ref} are unique-ified.
15336 Literal elements have this attribute:
15338 @itemize @bullet
15339 @item
15340 lit_val is the value of the literal as written in the source text,
15341 appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
15342 only to numeric and string literals. Enumeration literals in Ada are
15343 not really "literals" in the usual sense; they are usage occurrences,
15344 and have ref_name and ref as described above. Note also that string
15345 literals used as operator symbols are treated as defining or usage
15346 occurrences, not as literals.
15347 @end itemize
15349 @noindent
15350 Elements that can syntactically represent names and expressions (which
15351 includes usage occurrences, plus function calls and so forth) have this
15352 attribute:
15354 @itemize @bullet
15355 @item
15356 type. If the element represents an expression or the name of an object,
15357 'type' is the 'def' for the defining occurrence of the type of that
15358 expression or name. Names of other kinds of entities, such as package
15359 names and type names, do not have a type in Ada; these have type="null"
15360 in the XML.
15361 @end itemize
15363 @noindent
15364 Pragma elements have this attribute:
15366 @itemize @bullet
15367 @item
15368 pragma_name is the name of the pragma. For language-defined pragmas, the
15369 pragma name is redundant with the element kind (for example, an
15370 assert_pragma element necessarily has pragma_name="Assert"). However, all
15371 implementation-defined pragmas are lumped together in ASIS as a single
15372 element kind (for example, the GNAT-specific pragma Unreferenced is
15373 represented by an implementation_defined_pragma element with
15374 pragma_name="Unreferenced").
15375 @end itemize
15377 @noindent
15378 Defining occurrences of formal parameters and generic formal objects have this
15379 attribute:
15381 @itemize @bullet
15382 @item
15383 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
15384 @end itemize
15386 @noindent
15387 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
15388 enumeration type Flat_Declaration_Kinds, declared in
15389 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
15390 any trailing "_Declaration" or "_Specification" removed. Thus, the
15391 possible kinds are as follows:
15393 @smallexample
15394 ordinary_type
15395 task_type
15396 protected_type
15397 incomplete_type
15398 tagged_incomplete_type
15399 private_type
15400 private_extension
15401 subtype
15402 variable
15403 constant
15404 deferred_constant
15405 single_task
15406 single_protected
15407 integer_number
15408 real_number
15409 enumeration_literal
15410 discriminant
15411 component
15412 loop_parameter
15413 generalized_iterator
15414 element_iterator
15415 procedure
15416 function
15417 parameter
15418 procedure_body
15419 function_body
15420 return_variable
15421 return_constant
15422 null_procedure
15423 expression_function
15424 package
15425 package_body
15426 object_renaming
15427 exception_renaming
15428 package_renaming
15429 procedure_renaming
15430 function_renaming
15431 generic_package_renaming
15432 generic_procedure_renaming
15433 generic_function_renaming
15434 task_body
15435 protected_body
15436 entry
15437 entry_body
15438 entry_index
15439 procedure_body_stub
15440 function_body_stub
15441 package_body_stub
15442 task_body_stub
15443 protected_body_stub
15444 exception
15445 choice_parameter
15446 generic_procedure
15447 generic_function
15448 generic_package
15449 package_instantiation
15450 procedure_instantiation
15451 function_instantiation
15452 formal_object
15453 formal_type
15454 formal_incomplete_type
15455 formal_procedure
15456 formal_function
15457 formal_package
15458 formal_package_declaration_with_box
15459 @end smallexample
15460 @end ifclear
15462 @c *********************************
15463 @node The GNAT Metrics Tool gnatmetric
15464 @chapter The GNAT Metrics Tool @command{gnatmetric}
15465 @findex gnatmetric
15466 @cindex Metric tool
15468 @noindent
15469 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15470 for computing various program metrics.
15471 It takes an Ada source file as input and generates a file containing the
15472 metrics data as output. Various switches control which
15473 metrics are computed and output.
15475 @menu
15476 * Switches for gnatmetric::
15477 @end menu
15479 @command{gnatmetric} generates and uses the ASIS
15480 tree for the input source and thus requires the input to be syntactically and
15481 semantically legal.
15482 If this condition is not met, @command{gnatmetric} will generate
15483 an error message; no metric information for this file will be
15484 computed and reported.
15486 If the compilation unit contained in the input source depends semantically
15487 upon units in files located outside the current directory, you have to provide
15488 the source search path when invoking @command{gnatmetric}.
15489 If it depends semantically upon units that are contained
15490 in files with names that do not follow the GNAT file naming rules, you have to
15491 provide the configuration file describing the corresponding naming scheme (see
15492 the description of the @command{gnatmetric} switches below.)
15493 Alternatively, you may use a project file and invoke @command{gnatmetric}
15494 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15496 The @command{gnatmetric} command has the form
15498 @smallexample
15499 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15500 @c Expanding @ovar macro inline (explanation in macro def comments)
15501 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15502 @end smallexample
15504 @noindent
15505 where
15506 @itemize @bullet
15507 @item
15508 @var{switches} specify the metrics to compute and define the destination for
15509 the output
15511 @item
15512 Each @var{filename} is the name (including the extension) of a source
15513 file to process. ``Wildcards'' are allowed, and
15514 the file name may contain path information.
15515 If no @var{filename} is supplied, then the @var{switches} list must contain
15516 at least one
15517 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15518 Including both a @option{-files} switch and one or more
15519 @var{filename} arguments is permitted.
15521 @item
15522 @samp{@var{gcc_switches}} is a list of switches for
15523 @command{gcc}. They will be passed on to all compiler invocations made by
15524 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15525 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15526 and use the @option{-gnatec} switch to set the configuration file,
15527 use the @option{-gnat05} switch if sources should be compiled in
15528 Ada 2005 mode etc.
15529 @end itemize
15531 @node Switches for gnatmetric
15532 @section Switches for @command{gnatmetric}
15534 @noindent
15535 The following subsections describe the various switches accepted by
15536 @command{gnatmetric}, organized by category.
15538 @menu
15539 * Output Files Control::
15540 * Disable Metrics For Local Units::
15541 * Specifying a set of metrics to compute::
15542 * Other gnatmetric Switches::
15543 * Generate project-wide metrics::
15544 @end menu
15546 @node Output Files Control
15547 @subsection Output File Control
15548 @cindex Output file control in @command{gnatmetric}
15550 @noindent
15551 @command{gnatmetric} has two output formats. It can generate a
15552 textual (human-readable) form, and also XML. By default only textual
15553 output is generated.
15555 When generating the output in textual form, @command{gnatmetric} creates
15556 for each Ada source file a corresponding text file
15557 containing the computed metrics, except for the case when the set of metrics
15558 specified by gnatmetric parameters consists only of metrics that are computed
15559 for the whole set of analyzed sources, but not for each Ada source.
15560 By default, this file is placed in the same directory as where the source
15561 file is located, and its name is obtained
15562 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15563 input file.
15565 All the output information generated in XML format is placed in a single
15566 file. By default this file is placed in the current directory and has the
15567 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15569 Some of the computed metrics are summed over the units passed to
15570 @command{gnatmetric}; for example, the total number of lines of code.
15571 By default this information is sent to @file{stdout}, but a file
15572 can be specified with the @option{-og} switch.
15574 The following switches control the @command{gnatmetric} output:
15576 @table @option
15577 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15578 @item ^-x^/XML^
15579 Generate the XML output
15581 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15582 @item ^-xs^/XSD^
15583 Generate the XML output and the XML schema file that describes the structure
15584 of the XML metric report, this schema is assigned to the XML file. The schema
15585 file has the same name as the XML output file with @file{.xml} suffix replaced
15586 with @file{.xsd}
15588 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15589 @item ^-nt^/NO_TEXT^
15590 Do not generate the output in text form (implies @option{^-x^/XML^})
15592 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15593 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15594 Put text files with detailed metrics into @var{output_dir}
15596 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15597 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15598 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15599 in the name of the output file.
15601 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15602 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15603 Put global metrics into @var{file_name}
15605 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15606 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15607 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15609 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15610 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15611 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15612 output includes the name(s) of the Ada source file(s) from which the metrics
15613 are computed.  By default each name includes the absolute path. The
15614 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15615 to exclude all directory information from the file names that are output.)
15617 @end table
15619 @node Disable Metrics For Local Units
15620 @subsection Disable Metrics For Local Units
15621 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15623 @noindent
15624 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15625 one compilation
15626 unit per one source file. It computes line metrics for the whole source
15627 file, and it also computes syntax
15628 and complexity metrics for the file's outermost unit.
15630 By default, @command{gnatmetric} will also compute all metrics for certain
15631 kinds of locally declared program units:
15633 @itemize @bullet
15634 @item
15635 subprogram (and generic subprogram) bodies;
15637 @item
15638 package (and generic package) specs and bodies;
15640 @item
15641 task object and type specifications and bodies;
15643 @item
15644 protected object and type specifications and bodies.
15645 @end itemize
15647 @noindent
15648 These kinds of entities will be referred to as
15649 @emph{eligible local program units}, or simply @emph{eligible local units},
15650 @cindex Eligible local unit (for @command{gnatmetric})
15651 in the discussion below.
15653 Note that a subprogram declaration, generic instantiation,
15654 or renaming declaration only receives metrics
15655 computation when it appear as the outermost entity
15656 in a source file.
15658 Suppression of metrics computation for eligible local units can be
15659 obtained via the following switch:
15661 @table @option
15662 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15663 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15664 Do not compute detailed metrics for eligible local program units
15666 @end table
15668 @node Specifying a set of metrics to compute
15669 @subsection Specifying a set of metrics to compute
15671 @noindent
15672 By default all the metrics are computed and reported. The switches
15673 described in this subsection allow you to control, on an individual
15674 basis, whether metrics are computed and
15675 reported. If at least one positive metric
15676 switch is specified (that is, a switch that defines that a given
15677 metric or set of metrics is to be computed), then only
15678 explicitly specified metrics are reported.
15680 @menu
15681 * Line Metrics Control::
15682 * Syntax Metrics Control::
15683 * Complexity Metrics Control::
15684 * Coupling Metrics Control::
15685 @end menu
15687 @node Line Metrics Control
15688 @subsubsection Line Metrics Control
15689 @cindex Line metrics control in @command{gnatmetric}
15691 @noindent
15692 For any (legal) source file, and for each of its
15693 eligible local program units, @command{gnatmetric} computes the following
15694 metrics:
15696 @itemize @bullet
15697 @item
15698 the total number of lines;
15700 @item
15701 the total number of code lines (i.e., non-blank lines that are not comments)
15703 @item
15704 the number of comment lines
15706 @item
15707 the number of code lines containing end-of-line comments;
15709 @item
15710 the comment percentage: the ratio between the number of lines that contain
15711 comments and the number of all non-blank lines, expressed as a percentage;
15713 @item
15714 the number of empty lines and lines containing only space characters and/or
15715 format effectors (blank lines)
15717 @item
15718 the average number of code lines in subprogram bodies, task bodies, entry
15719 bodies and statement sequences in package bodies (this metric is only computed
15720 across the whole set of the analyzed units)
15722 @end itemize
15724 @noindent
15725 @command{gnatmetric} sums the values of the line metrics for all the
15726 files being processed and then generates the cumulative results. The tool
15727 also computes for all the files being processed the average number of code
15728 lines in bodies.
15730 You can use the following switches to select the specific line metrics
15731 to be computed and reported.
15733 @table @option
15734 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15736 @ifclear vms
15737 @cindex @option{--no-lines@var{x}}
15738 @end ifclear
15740 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15741 Report all the line metrics
15743 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15744 Do not report any of line metrics
15746 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15747 Report the number of all lines
15749 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15750 Do not report the number of all lines
15752 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15753 Report the number of code lines
15755 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15756 Do not report the number of code lines
15758 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15759 Report the number of comment lines
15761 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15762 Do not report the number of comment lines
15764 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15765 Report the number of code lines containing
15766 end-of-line comments
15768 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15769 Do not report the number of code lines containing
15770 end-of-line comments
15772 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15773 Report the comment percentage in the program text
15775 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15776 Do not report the comment percentage in the program text
15778 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15779 Report the number of blank lines
15781 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15782 Do not report the number of blank lines
15784 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15785 Report the average number of code lines in subprogram bodies, task bodies,
15786 entry bodies and statement sequences in package bodies. The metric is computed
15787 and reported for the whole set of processed Ada sources only.
15789 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15790 Do not report the average number of code lines in subprogram bodies,
15791 task bodies, entry bodies and statement sequences in package bodies.
15793 @end table
15795 @node Syntax Metrics Control
15796 @subsubsection Syntax Metrics Control
15797 @cindex Syntax metrics control in @command{gnatmetric}
15799 @noindent
15800 @command{gnatmetric} computes various syntactic metrics for the
15801 outermost unit and for each eligible local unit:
15803 @table @emph
15804 @item LSLOC (``Logical Source Lines Of Code'')
15805 The total number of declarations and the total number of statements. Note
15806 that the definition of declarations is the one given in the reference
15807 manual:
15809 @noindent
15810 ``Each of the following is defined to be a declaration: any basic_declaration;
15811 an enumeration_literal_specification; a discriminant_specification;
15812 a component_declaration; a loop_parameter_specification; a
15813 parameter_specification; a subprogram_body; an entry_declaration;
15814 an entry_index_specification; a choice_parameter_specification;
15815 a generic_formal_parameter_declaration.''
15817 This means for example that each enumeration literal adds one to the count,
15818 as well as each subprogram parameter.
15820 Thus the results from this metric will be significantly greater than might
15821 be expected from a naive view of counting semicolons.
15823 @item Maximal static nesting level of inner program units
15824 According to
15825 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15826 package, a task unit, a protected unit, a
15827 protected entry, a generic unit, or an explicitly declared subprogram other
15828 than an enumeration literal.''
15830 @item Maximal nesting level of composite syntactic constructs
15831 This corresponds to the notion of the
15832 maximum nesting level in the GNAT built-in style checks
15833 (@pxref{Style Checking})
15834 @end table
15836 @noindent
15837 For the outermost unit in the file, @command{gnatmetric} additionally computes
15838 the following metrics:
15840 @table @emph
15841 @item Public subprograms
15842 This metric is computed for package specs. It is the
15843 number of subprograms and generic subprograms declared in the visible
15844 part (including the visible part of nested packages, protected objects, and
15845 protected types).
15847 @item All subprograms
15848 This metric is computed for bodies and subunits. The
15849 metric is equal to a total number of subprogram bodies in the compilation
15850 unit.
15851 Neither generic instantiations nor renamings-as-a-body nor body stubs
15852 are counted. Any subprogram body is counted, independently of its nesting
15853 level and enclosing constructs. Generic bodies and bodies of protected
15854 subprograms are counted in the same way as ``usual'' subprogram bodies.
15856 @item Public types
15857 This metric is computed for package specs and
15858 generic package declarations. It is the total number of types
15859 that can be referenced from outside this compilation unit, plus the
15860 number of types from all the visible parts of all the visible generic
15861 packages. Generic formal types are not counted.  Only types, not subtypes,
15862 are included.
15864 @noindent
15865 Along with the total number of public types, the following
15866 types are counted and reported separately:
15868 @itemize @bullet
15869 @item
15870 Abstract types
15872 @item
15873 Root tagged types (abstract, non-abstract, private, non-private). Type
15874 extensions are @emph{not} counted
15876 @item
15877 Private types (including private extensions)
15879 @item
15880 Task types
15882 @item
15883 Protected types
15885 @end itemize
15887 @item All types
15888 This metric is computed for any compilation unit. It is equal to the total
15889 number of the declarations of different types given in the compilation unit.
15890 The private and the corresponding full type declaration are counted as one
15891 type declaration. Incomplete type declarations and generic formal types
15892 are not counted.
15893 No distinction is made among different kinds of types (abstract,
15894 private etc.); the total number of types is computed and reported.
15896 @end table
15898 @noindent
15899 By default, all the syntax metrics are computed and reported. You can use the
15900 following switches to select specific syntax metrics.
15902 @table @option
15904 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
15906 @ifclear vms
15907 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15908 @end ifclear
15910 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
15911 Report all the syntax metrics
15913 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
15914 Do not report any of syntax metrics
15916 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
15917 Report the total number of declarations
15919 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
15920 Do not report the total number of declarations
15922 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
15923 Report the total number of statements
15925 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
15926 Do not report the total number of statements
15928 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
15929 Report the number of public subprograms in a compilation unit
15931 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
15932 Do not report the number of public subprograms in a compilation unit
15934 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
15935 Report the number of all the subprograms in a compilation unit
15937 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
15938 Do not report the number of all the subprograms in a compilation unit
15940 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
15941 Report the number of public types in a compilation unit
15943 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
15944 Do not report the number of public types in a compilation unit
15946 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
15947 Report the number of all the types in a compilation unit
15949 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
15950 Do not report the number of all the types in a compilation unit
15952 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
15953 Report the maximal program unit nesting level
15955 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
15956 Do not report the maximal program unit nesting level
15958 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
15959 Report the maximal construct nesting level
15961 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
15962 Do not report the maximal construct nesting level
15964 @end table
15966 @node Complexity Metrics Control
15967 @subsubsection Complexity Metrics Control
15968 @cindex Complexity metrics control in @command{gnatmetric}
15970 @noindent
15971 For a program unit that is an executable body (a subprogram body (including
15972 generic bodies), task body, entry body or a package body containing
15973 its own statement sequence) @command{gnatmetric} computes the following
15974 complexity metrics:
15976 @itemize @bullet
15977 @item
15978 McCabe cyclomatic complexity;
15980 @item
15981 McCabe essential complexity;
15983 @item
15984 maximal loop nesting level;
15986 @item
15987 extra exit points (for subprograms);
15988 @end itemize
15990 @noindent
15991 The McCabe cyclomatic complexity metric is defined
15992 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15994 According to McCabe, both control statements and short-circuit control forms
15995 should be taken into account when computing cyclomatic complexity.
15996 For Ada 2012 we have also take into account conditional expressions
15997 and quantified expressions. For each body, we compute three metric values:
15999 @itemize @bullet
16000 @item
16001 the complexity introduced by control
16002 statements only, without taking into account short-circuit forms,
16004 @item
16005 the complexity introduced by short-circuit control forms only, and
16007 @item
16008 the total
16009 cyclomatic complexity, which is the sum of these two values.
16010 @end itemize
16012 @noindent
16014 The cyclomatic complexity is also computed for Ada 2012 expression functions.
16015 An expression function cannot have statements as its components, so only one
16016 metric value is computed as a cyclomatic complexity of an expression function.
16018 The origin of cyclomatic complexity metric is the need to estimate the number
16019 of independent paths in the control flow graph that in turn gives the number
16020 of tests needed to satisfy paths coverage testing completeness criterion.
16021 Considered from the testing point of view, a static Ada @code{loop} (that is,
16022 the @code{loop} statement having static subtype in loop parameter
16023 specification) does not add to cyclomatic complexity. By providing
16024 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
16025 may specify that such loops should not be counted when computing the
16026 cyclomatic complexity metric
16028 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
16029 counted for the code that is reduced by excluding all the pure structural Ada
16030 control statements. An compound statement is considered as a non-structural
16031 if it contains a @code{raise} or @code{return} statement as it subcomponent,
16032 or if it contains a @code{goto} statement that transfers the control outside
16033 the operator. A selective accept statement with @code{terminate} alternative
16034 is considered as non-structural statement. When computing this metric,
16035 @code{exit} statements are treated in the same way as @code{goto}
16036 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
16038 The Ada essential complexity metric defined here is intended to quantify
16039 the extent to which the software is unstructured. It is adapted from
16040 the McCabe essential complexity metric defined in
16041 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
16042 suitable for typical Ada usage. For example, short circuit forms
16043 are not penalized as unstructured in the Ada essential complexity metric.
16045 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16046 the code in the exception handlers and in all the nested program units. The
16047 code of assertions and predicates (that is, subprogram preconditions and
16048 postconditions, subtype predicates and type invariants) is also skipped.
16050 By default, all the complexity metrics are computed and reported.
16051 For more fine-grained control you can use
16052 the following switches:
16054 @table @option
16055 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16057 @ifclear vms
16058 @cindex @option{--no-complexity@var{x}}
16059 @end ifclear
16061 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
16062 Report all the complexity metrics
16064 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
16065 Do not report any of complexity metrics
16067 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
16068 Report the McCabe Cyclomatic Complexity
16070 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
16071 Do not report the McCabe Cyclomatic Complexity
16073 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
16074 Report the Essential Complexity
16076 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
16077 Do not report the Essential Complexity
16079 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16080 Report maximal loop nesting level
16082 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
16083 Do not report maximal loop nesting level
16085 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
16086 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16087 task bodies, entry bodies and statement sequences in package bodies.
16088 The metric is computed and reported for whole set of processed Ada sources
16089 only.
16091 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
16092 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16093 bodies, task bodies, entry bodies and statement sequences in package bodies
16095 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16096 @item ^-ne^/NO_EXITS_AS_GOTOS^
16097 Do not consider @code{exit} statements as @code{goto}s when
16098 computing Essential Complexity
16100 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
16101 @item ^--no-static-loop^/NO_STATIC_LOOP^
16102 Do not consider static loops when computing cyclomatic complexity
16104 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
16105 Report the extra exit points for subprogram bodies. As an exit point, this
16106 metric counts @code{return} statements and raise statements in case when the
16107 raised exception is not handled in the same body. In case of a function this
16108 metric subtracts 1 from the number of exit points, because a function body
16109 must contain at least one @code{return} statement.
16111 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
16112 Do not report the extra exit points for subprogram bodies
16113 @end table
16116 @node Coupling Metrics Control
16117 @subsubsection Coupling Metrics Control
16118 @cindex Coupling metrics control in @command{gnatmetric}
16120 @noindent
16121 @cindex Coupling metrics (in in @command{gnatmetric})
16122 Coupling metrics measure the dependencies between a given entity and other
16123 entities the program consists of. The goal of these metrics is to estimate the
16124 stability of the whole program considered as the collection of entities
16125 (modules, classes etc.).
16127 Gnatmetric computes the following coupling metrics:
16129 @itemize @bullet
16131 @item
16132 @emph{object-oriented coupling} - for classes in traditional object-oriented
16133 sense;
16135 @item
16136 @emph{unit coupling} - for all the program units making up a program;
16138 @item
16139 @emph{control coupling} - this metric counts dependencies between a unit and
16140 only those units that define subprograms;
16141 @end itemize
16143 @noindent
16144 Two kinds of coupling metrics are computed:
16146 @table @asis
16147 @item fan-out coupling (efferent coupling)
16148 @cindex fan-out coupling
16149 @cindex efferent coupling
16150 the number of entities the given entity depends upon. It
16151 estimates in what extent the given entity depends on the changes in
16152 ``external world''
16154 @item fan-in coupling (afferent coupling)
16155 @cindex fan-in coupling
16156 @cindex afferent coupling
16157 the number of entities that depend on a given entity.
16158 It estimates in what extent the ``external world'' depends on the changes in a
16159 given entity
16160 @end table
16162 @noindent
16164 Object-oriented coupling metrics are metrics that measure the dependencies
16165 between a given class (or a group of classes) and the other classes in the
16166 program. In this subsection the term ``class'' is used in its traditional
16167 object-oriented programming sense (an instantiable module that contains data
16168 and/or method members). A @emph{category} (of classes) is a group of closely
16169 related classes that are reused and/or modified together.
16171 A class @code{K}'s fan-out coupling is the number of classes
16172 that @code{K} depends upon.
16173 A category's fan-out coupling is the number of classes outside the
16174 category that the classes inside the category depend upon.
16176 A class @code{K}'s fan-in coupling is the number of classes
16177 that depend upon @code{K}.
16178 A category's fan-in coupling is the number of classes outside the
16179 category that depend on classes belonging to the category.
16181 Ada's implementation of the object-oriented paradigm does not use the
16182 traditional class notion, so the definition of the coupling
16183 metrics for Ada maps the class and class category notions
16184 onto Ada constructs.
16186 For the coupling metrics, several kinds of modules -- a library package,
16187 a library generic package, and a library generic package instantiation --
16188 that define a tagged type or an interface type are
16189 considered to be a class. A category consists of a library package (or
16190 a library generic package) that defines a tagged or an interface type,
16191 together with all its descendant (generic) packages that define tagged
16192 or interface types. That is a
16193 category is an Ada hierarchy of library-level program units. So class coupling
16194 in case of Ada is called as tagged coupling, and category coupling - as
16195 hierarchy coupling.
16197 For any package counted as a class, its body and subunits (if any) are
16198 considered together with its spec when counting the dependencies, and coupling
16199 metrics are reported for spec units only. For dependencies between classes,
16200 the Ada semantic dependencies are considered. For object-oriented coupling
16201 metrics, only dependencies on units that are considered as classes, are
16202 considered.
16204 For unit and control coupling also not compilation units but program units are
16205 counted. That is, for a package, its spec, its body and its subunits (if any)
16206 are considered as making up one unit, and the dependencies that are counted
16207 are the dependencies of all these compilation units collected together as
16208 the dependencies as a (whole) unit. And metrics are reported for spec
16209 compilation units only (or for a subprogram body unit in case if there is no
16210 separate spec for the given subprogram).
16212 For unit coupling, dependencies between all kinds of program units are
16213 considered. For control coupling, for each unit the dependencies of this unit
16214 upon units that define subprograms are counted, so control fan-out coupling
16215 is reported for all units, but control fan-in coupling - only for the units
16216 that define subprograms.
16218 The following simple example illustrates the difference between unit coupling
16219 and control coupling metrics:
16221 @smallexample @c ada
16222 package Lib_1 is
16223     function F_1 (I : Integer) return Integer;
16224 end Lib_1;
16226 package Lib_2 is
16227     type T_2 is new Integer;
16228 end Lib_2;
16230 package body Lib_1 is
16231     function F_1 (I : Integer) return Integer is
16232     begin
16233        return I + 1;
16234     end F_1;
16235 end Lib_1;
16237 with Lib_2; use Lib_2;
16238 package Pack is
16239     Var : T_2;
16240     function Fun (I : Integer) return Integer;
16241 end Pack;
16243 with Lib_1; use Lib_1;
16244 package body Pack is
16245     function Fun (I : Integer) return Integer is
16246     begin
16247        return F_1 (I);
16248     end Fun;
16249 end Pack;
16250 @end smallexample
16252 @noindent
16253 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
16254 units, the result will be:
16256 @smallexample
16257 Coupling metrics:
16258 =================
16259     Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16260        control fan-out coupling  : 0
16261        control fan-in coupling   : 1
16262        unit fan-out coupling     : 0
16263        unit fan-in coupling      : 1
16265     Unit Pack (C:\customers\662\L406-007\pack.ads)
16266        control fan-out coupling  : 1
16267        control fan-in coupling   : 0
16268        unit fan-out coupling     : 2
16269        unit fan-in coupling      : 0
16271     Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16272        control fan-out coupling  : 0
16273        unit fan-out coupling     : 0
16274        unit fan-in coupling      : 1
16275 @end smallexample
16277 @noindent
16278 The result does not contain values for object-oriented
16279 coupling because none of the argument unit contains a tagged type and
16280 therefore none of these units can be treated as a class.
16282 @code{Pack} (considered as a program unit, that is spec+body) depends on two
16283 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
16284 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
16285 well as control fan-in coupling. Only one of the units @code{Pack} depends
16286 upon defines a subprogram, so its control fan-out coupling is 1.
16288 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
16289 not define a subprogram, so control fan-in metric cannot be applied to it,
16290 and there is one unit that depends on it (@code{Pack}), so it has
16291 unit fan-in coupling equals to 1.
16293 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16294 So it has control fan-in coupling equals to 1 (because there is a unit
16295 depending on it).
16297 When computing coupling metrics, @command{gnatmetric} counts only
16298 dependencies between units that are arguments of the @command{gnatmetric}
16299 call. Coupling metrics are program-wide (or project-wide) metrics, so to
16300 get a valid result, you should call @command{gnatmetric} for
16301 the whole set of sources that make up your program. It can be done
16302 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
16303 option (see @ref{The GNAT Driver and Project Files} for details).
16305 By default, all the coupling metrics are disabled. You can use the following
16306 switches to specify the coupling metrics to be computed and reported:
16308 @table @option
16310 @ifclear vms
16311 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16312 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16313 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16314 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16315 @end ifclear
16317 @ifset vms
16318 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16319 @end ifset
16321 @item ^--coupling-all^/COUPLING_METRICS=ALL^
16322 Report all the coupling metrics
16324 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16325 Report tagged (class) fan-out coupling
16327 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16328 Report tagged (class) fan-in coupling
16330 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16331 Report hierarchy (category) fan-out coupling
16333 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16334 Report hierarchy (category) fan-in coupling
16336 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16337 Report unit fan-out coupling
16339 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16340 Report unit fan-in coupling
16342 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16343 Report control fan-out coupling
16345 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16346 Report control fan-in coupling
16347 @end table
16349 @node Other gnatmetric Switches
16350 @subsection Other @code{gnatmetric} Switches
16352 @noindent
16353 Additional @command{gnatmetric} switches are as follows:
16355 @table @option
16356 @item --version
16357 @cindex @option{--version} @command{gnatmetric}
16358 Display Copyright and version, then exit disregarding all other options.
16360 @item --help
16361 @cindex @option{--help} @command{gnatmetric}
16362 Display usage, then exit disregarding all other options.
16364 @item ^-files @var{filename}^/FILES=@var{filename}^
16365 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16366 Take the argument source files from the specified file. This file should be an
16367 ordinary text file containing file names separated by spaces or
16368 line breaks. You can use this switch more than once in the same call to
16369 @command{gnatmetric}. You also can combine this switch with
16370 an explicit list of files.
16372 @item ^-v^/VERBOSE^
16373 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16374 Verbose mode;
16375 @command{gnatmetric} generates version information and then
16376 a trace of sources being processed.
16378 @item ^-q^/QUIET^
16379 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16380 Quiet mode.
16381 @end table
16383 @node Generate project-wide metrics
16384 @subsection Generate project-wide metrics
16386 In order to compute metrics on all units of a given project, you can use
16387 the @command{gnat} driver along with the @option{-P} option:
16388 @smallexample
16389    gnat metric -Pproj
16390 @end smallexample
16392 @noindent
16393 If the project @code{proj} depends upon other projects, you can compute
16394 the metrics on the project closure using the @option{-U} option:
16395 @smallexample
16396    gnat metric -Pproj -U
16397 @end smallexample
16399 @noindent
16400 Finally, if not all the units are relevant to a particular main
16401 program in the project closure, you can generate metrics for the set
16402 of units needed to create a given main program (unit closure) using
16403 the @option{-U} option followed by the name of the main unit:
16404 @smallexample
16405    gnat metric -Pproj -U main
16406 @end smallexample
16409 @c ***********************************
16410 @node File Name Krunching with gnatkr
16411 @chapter File Name Krunching with @code{gnatkr}
16412 @findex gnatkr
16414 @noindent
16415 This chapter discusses the method used by the compiler to shorten
16416 the default file names chosen for Ada units so that they do not
16417 exceed the maximum length permitted. It also describes the
16418 @code{gnatkr} utility that can be used to determine the result of
16419 applying this shortening.
16420 @menu
16421 * About gnatkr::
16422 * Using gnatkr::
16423 * Krunching Method::
16424 * Examples of gnatkr Usage::
16425 @end menu
16427 @node About gnatkr
16428 @section About @code{gnatkr}
16430 @noindent
16431 The default file naming rule in GNAT
16432 is that the file name must be derived from
16433 the unit name. The exact default rule is as follows:
16434 @itemize @bullet
16435 @item
16436 Take the unit name and replace all dots by hyphens.
16437 @item
16438 If such a replacement occurs in the
16439 second character position of a name, and the first character is
16440 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16441 then replace the dot by the character
16442 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
16443 instead of a minus.
16444 @end itemize
16445 The reason for this exception is to avoid clashes
16446 with the standard names for children of System, Ada, Interfaces,
16447 and GNAT, which use the prefixes
16448 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16449 respectively.
16451 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16452 switch of the compiler activates a ``krunching''
16453 circuit that limits file names to nn characters (where nn is a decimal
16454 integer). For example, using OpenVMS,
16455 where the maximum file name length is
16456 39, the value of nn is usually set to 39, but if you want to generate
16457 a set of files that would be usable if ported to a system with some
16458 different maximum file length, then a different value can be specified.
16459 The default value of 39 for OpenVMS need not be specified.
16461 The @code{gnatkr} utility can be used to determine the krunched name for
16462 a given file, when krunched to a specified maximum length.
16464 @node Using gnatkr
16465 @section Using @code{gnatkr}
16467 @noindent
16468 The @code{gnatkr} command has the form
16470 @ifclear vms
16471 @smallexample
16472 @c $ gnatkr @var{name} @ovar{length}
16473 @c Expanding @ovar macro inline (explanation in macro def comments)
16474 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16475 @end smallexample
16476 @end ifclear
16478 @ifset vms
16479 @smallexample
16480 $ gnatkr @var{name} /COUNT=nn
16481 @end smallexample
16482 @end ifset
16484 @noindent
16485 @var{name} is the uncrunched file name, derived from the name of the unit
16486 in the standard manner described in the previous section (i.e., in particular
16487 all dots are replaced by hyphens). The file name may or may not have an
16488 extension (defined as a suffix of the form period followed by arbitrary
16489 characters other than period). If an extension is present then it will
16490 be preserved in the output. For example, when krunching @file{hellofile.ads}
16491 to eight characters, the result will be hellofil.ads.
16493 Note: for compatibility with previous versions of @code{gnatkr} dots may
16494 appear in the name instead of hyphens, but the last dot will always be
16495 taken as the start of an extension. So if @code{gnatkr} is given an argument
16496 such as @file{Hello.World.adb} it will be treated exactly as if the first
16497 period had been a hyphen, and for example krunching to eight characters
16498 gives the result @file{hellworl.adb}.
16500 Note that the result is always all lower case (except on OpenVMS where it is
16501 all upper case). Characters of the other case are folded as required.
16503 @var{length} represents the length of the krunched name. The default
16504 when no argument is given is ^8^39^ characters. A length of zero stands for
16505 unlimited, in other words do not chop except for system files where the
16506 implied crunching length is always eight characters.
16508 @noindent
16509 The output is the krunched name. The output has an extension only if the
16510 original argument was a file name with an extension.
16512 @node Krunching Method
16513 @section Krunching Method
16515 @noindent
16516 The initial file name is determined by the name of the unit that the file
16517 contains. The name is formed by taking the full expanded name of the
16518 unit and replacing the separating dots with hyphens and
16519 using ^lowercase^uppercase^
16520 for all letters, except that a hyphen in the second character position is
16521 replaced by a ^tilde^dollar sign^ if the first character is
16522 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16523 The extension is @code{.ads} for a
16524 spec and @code{.adb} for a body.
16525 Krunching does not affect the extension, but the file name is shortened to
16526 the specified length by following these rules:
16528 @itemize @bullet
16529 @item
16530 The name is divided into segments separated by hyphens, tildes or
16531 underscores and all hyphens, tildes, and underscores are
16532 eliminated. If this leaves the name short enough, we are done.
16534 @item
16535 If the name is too long, the longest segment is located (left-most
16536 if there are two of equal length), and shortened by dropping
16537 its last character. This is repeated until the name is short enough.
16539 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16540 to fit the name into 8 characters as required by some operating systems.
16542 @smallexample
16543 our-strings-wide_fixed 22
16544 our strings wide fixed 19
16545 our string  wide fixed 18
16546 our strin   wide fixed 17
16547 our stri    wide fixed 16
16548 our stri    wide fixe  15
16549 our str     wide fixe  14
16550 our str     wid  fixe  13
16551 our str     wid  fix   12
16552 ou  str     wid  fix   11
16553 ou  st      wid  fix   10
16554 ou  st      wi   fix   9
16555 ou  st      wi   fi    8
16556 Final file name: oustwifi.adb
16557 @end smallexample
16559 @item
16560 The file names for all predefined units are always krunched to eight
16561 characters. The krunching of these predefined units uses the following
16562 special prefix replacements:
16564 @table @file
16565 @item ada-
16566 replaced by @file{^a^A^-}
16568 @item gnat-
16569 replaced by @file{^g^G^-}
16571 @item interfaces-
16572 replaced by @file{^i^I^-}
16574 @item system-
16575 replaced by @file{^s^S^-}
16576 @end table
16578 These system files have a hyphen in the second character position. That
16579 is why normal user files replace such a character with a
16580 ^tilde^dollar sign^, to
16581 avoid confusion with system file names.
16583 As an example of this special rule, consider
16584 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16586 @smallexample
16587 ada-strings-wide_fixed 22
16588 a-  strings wide fixed 18
16589 a-  string  wide fixed 17
16590 a-  strin   wide fixed 16
16591 a-  stri    wide fixed 15
16592 a-  stri    wide fixe  14
16593 a-  str     wide fixe  13
16594 a-  str     wid  fixe  12
16595 a-  str     wid  fix   11
16596 a-  st      wid  fix   10
16597 a-  st      wi   fix   9
16598 a-  st      wi   fi    8
16599 Final file name: a-stwifi.adb
16600 @end smallexample
16601 @end itemize
16603 Of course no file shortening algorithm can guarantee uniqueness over all
16604 possible unit names, and if file name krunching is used then it is your
16605 responsibility to ensure that no name clashes occur. The utility
16606 program @code{gnatkr} is supplied for conveniently determining the
16607 krunched name of a file.
16609 @node Examples of gnatkr Usage
16610 @section Examples of @code{gnatkr} Usage
16612 @smallexample
16613 @iftex
16614 @leftskip=0cm
16615 @end iftex
16616 @ifclear vms
16617 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16618 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16619 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16620 $ gnatkr grandparent-parent-child     --> grparchi
16621 @end ifclear
16622 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16623 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16624 @end smallexample
16626 @node Preprocessing with gnatprep
16627 @chapter Preprocessing with @code{gnatprep}
16628 @findex gnatprep
16630 @noindent
16631 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16632 preprocessing.
16633 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16634 special GNAT features.
16635 For further discussion of conditional compilation in general, see
16636 @ref{Conditional Compilation}.
16638 @menu
16639 * Preprocessing Symbols::
16640 * Using gnatprep::
16641 * Switches for gnatprep::
16642 * Form of Definitions File::
16643 * Form of Input Text for gnatprep::
16644 @end menu
16646 @node Preprocessing Symbols
16647 @section Preprocessing Symbols
16649 @noindent
16650 Preprocessing symbols are defined in definition files and referred to in
16651 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16652 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16653 all characters need to be in the ASCII set (no accented letters).
16655 @node Using gnatprep
16656 @section Using @code{gnatprep}
16658 @noindent
16659 To call @code{gnatprep} use
16661 @smallexample
16662 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16663 @c Expanding @ovar macro inline (explanation in macro def comments)
16664 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16665 @end smallexample
16667 @noindent
16668 where
16669 @table @var
16670 @item switches
16671 is an optional sequence of switches as described in the next section.
16673 @item infile
16674 is the full name of the input file, which is an Ada source
16675 file containing preprocessor directives.
16677 @item outfile
16678 is the full name of the output file, which is an Ada source
16679 in standard Ada form. When used with GNAT, this file name will
16680 normally have an ads or adb suffix.
16682 @item deffile
16683 is the full name of a text file containing definitions of
16684 preprocessing symbols to be referenced by the preprocessor. This argument is
16685 optional, and can be replaced by the use of the @option{-D} switch.
16687 @end table
16689 @node Switches for gnatprep
16690 @section Switches for @code{gnatprep}
16692 @table @option
16693 @c !sort!
16695 @item ^-b^/BLANK_LINES^
16696 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16697 Causes both preprocessor lines and the lines deleted by
16698 preprocessing to be replaced by blank lines in the output source file,
16699 preserving line numbers in the output file.
16701 @item ^-c^/COMMENTS^
16702 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16703 Causes both preprocessor lines and the lines deleted
16704 by preprocessing to be retained in the output source as comments marked
16705 with the special string @code{"--! "}. This option will result in line numbers
16706 being preserved in the output file.
16708 @item ^-C^/REPLACE_IN_COMMENTS^
16709 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16710 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16711 If this option is specified, then comments are scanned and any $symbol
16712 substitutions performed as in program text. This is particularly useful
16713 when structured comments are used (e.g., when writing programs in the
16714 SPARK dialect of Ada). Note that this switch is not available when
16715 doing integrated preprocessing (it would be useless in this context
16716 since comments are ignored by the compiler in any case).
16718 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16719 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16720 Defines a new preprocessing symbol, associated with value. If no value is given
16721 on the command line, then symbol is considered to be @code{True}. This switch
16722 can be used in place of a definition file.
16724 @ifset vms
16725 @item /REMOVE
16726 @cindex @option{/REMOVE} (@command{gnatprep})
16727 This is the default setting which causes lines deleted by preprocessing
16728 to be entirely removed from the output file.
16729 @end ifset
16731 @item ^-r^/REFERENCE^
16732 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16733 Causes a @code{Source_Reference} pragma to be generated that
16734 references the original input file, so that error messages will use
16735 the file name of this original file. The use of this switch implies
16736 that preprocessor lines are not to be removed from the file, so its
16737 use will force @option{^-b^/BLANK_LINES^} mode if
16738 @option{^-c^/COMMENTS^}
16739 has not been specified explicitly.
16741 Note that if the file to be preprocessed contains multiple units, then
16742 it will be necessary to @code{gnatchop} the output file from
16743 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16744 in the preprocessed file, it will be respected by
16745 @code{gnatchop ^-r^/REFERENCE^}
16746 so that the final chopped files will correctly refer to the original
16747 input source file for @code{gnatprep}.
16749 @item ^-s^/SYMBOLS^
16750 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16751 Causes a sorted list of symbol names and values to be
16752 listed on the standard output file.
16754 @item ^-u^/UNDEFINED^
16755 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16756 Causes undefined symbols to be treated as having the value FALSE in the context
16757 of a preprocessor test. In the absence of this option, an undefined symbol in
16758 a @code{#if} or @code{#elsif} test will be treated as an error.
16760 @end table
16762 @ifclear vms
16763 @noindent
16764 Note: if neither @option{-b} nor @option{-c} is present,
16765 then preprocessor lines and
16766 deleted lines are completely removed from the output, unless -r is
16767 specified, in which case -b is assumed.
16768 @end ifclear
16770 @node Form of Definitions File
16771 @section Form of Definitions File
16773 @noindent
16774 The definitions file contains lines of the form
16776 @smallexample
16777 symbol := value
16778 @end smallexample
16780 @noindent
16781 where symbol is a preprocessing symbol, and value is one of the following:
16783 @itemize @bullet
16784 @item
16785 Empty, corresponding to a null substitution
16786 @item
16787 A string literal using normal Ada syntax
16788 @item
16789 Any sequence of characters from the set
16790 (letters, digits, period, underline).
16791 @end itemize
16793 @noindent
16794 Comment lines may also appear in the definitions file, starting with
16795 the usual @code{--},
16796 and comments may be added to the definitions lines.
16798 @node Form of Input Text for gnatprep
16799 @section Form of Input Text for @code{gnatprep}
16801 @noindent
16802 The input text may contain preprocessor conditional inclusion lines,
16803 as well as general symbol substitution sequences.
16805 The preprocessor conditional inclusion commands have the form
16807 @smallexample
16808 @group
16809 @cartouche
16810 #if @i{expression} @r{[}then@r{]}
16811    lines
16812 #elsif @i{expression} @r{[}then@r{]}
16813    lines
16814 #elsif @i{expression} @r{[}then@r{]}
16815    lines
16816 @dots{}
16817 #else
16818    lines
16819 #end if;
16820 @end cartouche
16821 @end group
16822 @end smallexample
16824 @noindent
16825 In this example, @i{expression} is defined by the following grammar:
16826 @smallexample
16827 @i{expression} ::=  <symbol>
16828 @i{expression} ::=  <symbol> = "<value>"
16829 @i{expression} ::=  <symbol> = <symbol>
16830 @i{expression} ::=  <symbol> = <integer>
16831 @i{expression} ::=  <symbol> > <integer>
16832 @i{expression} ::=  <symbol> >= <integer>
16833 @i{expression} ::=  <symbol> < <integer>
16834 @i{expression} ::=  <symbol> <= <integer>
16835 @i{expression} ::=  <symbol> 'Defined
16836 @i{expression} ::=  not @i{expression}
16837 @i{expression} ::=  @i{expression} and @i{expression}
16838 @i{expression} ::=  @i{expression} or @i{expression}
16839 @i{expression} ::=  @i{expression} and then @i{expression}
16840 @i{expression} ::=  @i{expression} or else @i{expression}
16841 @i{expression} ::=  ( @i{expression} )
16842 @end smallexample
16844 The following restriction exists: it is not allowed to have "and" or "or"
16845 following "not" in the same expression without parentheses. For example, this
16846 is not allowed:
16848 @smallexample
16849    not X or Y
16850 @end smallexample
16852 This should be one of the following:
16854 @smallexample
16855    (not X) or Y
16856    not (X or Y)
16857 @end smallexample
16859 @noindent
16860 For the first test (@i{expression} ::= <symbol>) the symbol must have
16861 either the value true or false, that is to say the right-hand of the
16862 symbol definition must be one of the (case-insensitive) literals
16863 @code{True} or @code{False}. If the value is true, then the
16864 corresponding lines are included, and if the value is false, they are
16865 excluded.
16867 When comparing a symbol to an integer, the integer is any non negative
16868 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
16869 2#11#. The symbol value must also be a non negative integer. Integer values
16870 in the range 0 .. 2**31-1 are supported.
16872 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16873 the symbol has been defined in the definition file or by a @option{-D}
16874 switch on the command line. Otherwise, the test is false.
16876 The equality tests are case insensitive, as are all the preprocessor lines.
16878 If the symbol referenced is not defined in the symbol definitions file,
16879 then the effect depends on whether or not switch @option{-u}
16880 is specified. If so, then the symbol is treated as if it had the value
16881 false and the test fails. If this switch is not specified, then
16882 it is an error to reference an undefined symbol. It is also an error to
16883 reference a symbol that is defined with a value other than @code{True}
16884 or @code{False}.
16886 The use of the @code{not} operator inverts the sense of this logical test.
16887 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16888 operators, without parentheses. For example, "if not X or Y then" is not
16889 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16891 The @code{then} keyword is optional as shown
16893 The @code{#} must be the first non-blank character on a line, but
16894 otherwise the format is free form. Spaces or tabs may appear between
16895 the @code{#} and the keyword. The keywords and the symbols are case
16896 insensitive as in normal Ada code. Comments may be used on a
16897 preprocessor line, but other than that, no other tokens may appear on a
16898 preprocessor line. Any number of @code{elsif} clauses can be present,
16899 including none at all. The @code{else} is optional, as in Ada.
16901 The @code{#} marking the start of a preprocessor line must be the first
16902 non-blank character on the line, i.e., it must be preceded only by
16903 spaces or horizontal tabs.
16905 Symbol substitution outside of preprocessor lines is obtained by using
16906 the sequence
16908 @smallexample
16909 $symbol
16910 @end smallexample
16912 @noindent
16913 anywhere within a source line, except in a comment or within a
16914 string literal. The identifier
16915 following the @code{$} must match one of the symbols defined in the symbol
16916 definition file, and the result is to substitute the value of the
16917 symbol in place of @code{$symbol} in the output file.
16919 Note that although the substitution of strings within a string literal
16920 is not possible, it is possible to have a symbol whose defined value is
16921 a string literal. So instead of setting XYZ to @code{hello} and writing:
16923 @smallexample
16924 Header : String := "$XYZ";
16925 @end smallexample
16927 @noindent
16928 you should set XYZ to @code{"hello"} and write:
16930 @smallexample
16931 Header : String := $XYZ;
16932 @end smallexample
16934 @noindent
16935 and then the substitution will occur as desired.
16937 @node The GNAT Library Browser gnatls
16938 @chapter The GNAT Library Browser @code{gnatls}
16939 @findex gnatls
16940 @cindex Library browser
16942 @noindent
16943 @code{gnatls} is a tool that outputs information about compiled
16944 units. It gives the relationship between objects, unit names and source
16945 files. It can also be used to check the source dependencies of a unit
16946 as well as various characteristics.
16948 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16949 driver (see @ref{The GNAT Driver and Project Files}).
16951 @menu
16952 * Running gnatls::
16953 * Switches for gnatls::
16954 * Examples of gnatls Usage::
16955 @end menu
16957 @node Running gnatls
16958 @section Running @code{gnatls}
16960 @noindent
16961 The @code{gnatls} command has the form
16963 @smallexample
16964 $ gnatls switches @var{object_or_ali_file}
16965 @end smallexample
16967 @noindent
16968 The main argument is the list of object or @file{ali} files
16969 (@pxref{The Ada Library Information Files})
16970 for which information is requested.
16972 In normal mode, without additional option, @code{gnatls} produces a
16973 four-column listing. Each line represents information for a specific
16974 object. The first column gives the full path of the object, the second
16975 column gives the name of the principal unit in this object, the third
16976 column gives the status of the source and the fourth column gives the
16977 full path of the source representing this unit.
16978 Here is a simple example of use:
16980 @smallexample
16981 $ gnatls *.o
16982 ^./^[]^demo1.o            demo1            DIF demo1.adb
16983 ^./^[]^demo2.o            demo2             OK demo2.adb
16984 ^./^[]^hello.o            h1                OK hello.adb
16985 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
16986 ^./^[]^instr.o            instr             OK instr.adb
16987 ^./^[]^tef.o              tef              DIF tef.adb
16988 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
16989 ^./^[]^tgef.o             tgef             DIF tgef.adb
16990 @end smallexample
16992 @noindent
16993 The first line can be interpreted as follows: the main unit which is
16994 contained in
16995 object file @file{demo1.o} is demo1, whose main source is in
16996 @file{demo1.adb}. Furthermore, the version of the source used for the
16997 compilation of demo1 has been modified (DIF). Each source file has a status
16998 qualifier which can be:
17000 @table @code
17001 @item OK (unchanged)
17002 The version of the source file used for the compilation of the
17003 specified unit corresponds exactly to the actual source file.
17005 @item MOK (slightly modified)
17006 The version of the source file used for the compilation of the
17007 specified unit differs from the actual source file but not enough to
17008 require recompilation. If you use gnatmake with the qualifier
17009 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17010 MOK will not be recompiled.
17012 @item DIF (modified)
17013 No version of the source found on the path corresponds to the source
17014 used to build this object.
17016 @item ??? (file not found)
17017 No source file was found for this unit.
17019 @item HID (hidden,  unchanged version not first on PATH)
17020 The version of the source that corresponds exactly to the source used
17021 for compilation has been found on the path but it is hidden by another
17022 version of the same source that has been modified.
17024 @end table
17026 @node Switches for gnatls
17027 @section Switches for @code{gnatls}
17029 @noindent
17030 @code{gnatls} recognizes the following switches:
17032 @table @option
17033 @c !sort!
17034 @cindex @option{--version} @command{gnatls}
17035 Display Copyright and version, then exit disregarding all other options.
17037 @item --help
17038 @cindex @option{--help} @command{gnatls}
17039 If @option{--version} was not used, display usage, then exit disregarding
17040 all other options.
17042 @item ^-a^/ALL_UNITS^
17043 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17044 Consider all units, including those of the predefined Ada library.
17045 Especially useful with @option{^-d^/DEPENDENCIES^}.
17047 @item ^-d^/DEPENDENCIES^
17048 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17049 List sources from which specified units depend on.
17051 @item ^-h^/OUTPUT=OPTIONS^
17052 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17053 Output the list of options.
17055 @item ^-o^/OUTPUT=OBJECTS^
17056 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17057 Only output information about object files.
17059 @item ^-s^/OUTPUT=SOURCES^
17060 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17061 Only output information about source files.
17063 @item ^-u^/OUTPUT=UNITS^
17064 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17065 Only output information about compilation units.
17067 @item ^-files^/FILES^=@var{file}
17068 @cindex @option{^-files^/FILES^} (@code{gnatls})
17069 Take as arguments the files listed in text file @var{file}.
17070 Text file @var{file} may contain empty lines that are ignored.
17071 Each nonempty line should contain the name of an existing file.
17072 Several such switches may be specified simultaneously.
17074 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17075 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17076 @itemx ^-I^/SEARCH=^@var{dir}
17077 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
17078 @itemx -nostdinc
17079 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17080 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17081 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17082 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17083 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17084 flags (@pxref{Switches for gnatmake}).
17086 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
17087 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
17088 Add @var{dir} at the beginning of the project search dir.
17090 @item --RTS=@var{rts-path}
17091 @cindex @option{--RTS} (@code{gnatls})
17092 Specifies the default location of the runtime library. Same meaning as the
17093 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17095 @item ^-v^/OUTPUT=VERBOSE^
17096 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17097 Verbose mode. Output the complete source, object and project paths. Do not use
17098 the default column layout but instead use long format giving as much as
17099 information possible on each requested units, including special
17100 characteristics such as:
17102 @table @code
17103 @item  Preelaborable
17104 The unit is preelaborable in the Ada sense.
17106 @item No_Elab_Code
17107 No elaboration code has been produced by the compiler for this unit.
17109 @item Pure
17110 The unit is pure in the Ada sense.
17112 @item Elaborate_Body
17113 The unit contains a pragma Elaborate_Body.
17115 @item Remote_Types
17116 The unit contains a pragma Remote_Types.
17118 @item Shared_Passive
17119 The unit contains a pragma Shared_Passive.
17121 @item Predefined
17122 This unit is part of the predefined environment and cannot be modified
17123 by the user.
17125 @item Remote_Call_Interface
17126 The unit contains a pragma Remote_Call_Interface.
17128 @end table
17130 @end table
17132 @node Examples of gnatls Usage
17133 @section Example of @code{gnatls} Usage
17134 @ifclear vms
17136 @noindent
17137 Example of using the verbose switch. Note how the source and
17138 object paths are affected by the -I switch.
17140 @smallexample
17141 $ gnatls -v -I.. demo1.o
17143 GNATLS 5.03w (20041123-34)
17144 Copyright 1997-2004 Free Software Foundation, Inc.
17146 Source Search Path:
17147    <Current_Directory>
17148    ../
17149    /home/comar/local/adainclude/
17151 Object Search Path:
17152    <Current_Directory>
17153    ../
17154    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17156 Project Search Path:
17157    <Current_Directory>
17158    /home/comar/local/lib/gnat/
17160 ./demo1.o
17161    Unit =>
17162      Name   => demo1
17163      Kind   => subprogram body
17164      Flags  => No_Elab_Code
17165      Source => demo1.adb    modified
17166 @end smallexample
17168 @noindent
17169 The following is an example of use of the dependency list.
17170 Note the use of the -s switch
17171 which gives a straight list of source files. This can be useful for
17172 building specialized scripts.
17174 @smallexample
17175 $ gnatls -d demo2.o
17176 ./demo2.o   demo2        OK demo2.adb
17177                          OK gen_list.ads
17178                          OK gen_list.adb
17179                          OK instr.ads
17180                          OK instr-child.ads
17182 $ gnatls -d -s -a demo1.o
17183 demo1.adb
17184 /home/comar/local/adainclude/ada.ads
17185 /home/comar/local/adainclude/a-finali.ads
17186 /home/comar/local/adainclude/a-filico.ads
17187 /home/comar/local/adainclude/a-stream.ads
17188 /home/comar/local/adainclude/a-tags.ads
17189 gen_list.ads
17190 gen_list.adb
17191 /home/comar/local/adainclude/gnat.ads
17192 /home/comar/local/adainclude/g-io.ads
17193 instr.ads
17194 /home/comar/local/adainclude/system.ads
17195 /home/comar/local/adainclude/s-exctab.ads
17196 /home/comar/local/adainclude/s-finimp.ads
17197 /home/comar/local/adainclude/s-finroo.ads
17198 /home/comar/local/adainclude/s-secsta.ads
17199 /home/comar/local/adainclude/s-stalib.ads
17200 /home/comar/local/adainclude/s-stoele.ads
17201 /home/comar/local/adainclude/s-stratt.ads
17202 /home/comar/local/adainclude/s-tasoli.ads
17203 /home/comar/local/adainclude/s-unstyp.ads
17204 /home/comar/local/adainclude/unchconv.ads
17205 @end smallexample
17206 @end ifclear
17208 @ifset vms
17209 @smallexample
17210 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17212 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17213 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17214 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17215 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17216 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17217 demo1.adb
17218 gen_list.ads
17219 gen_list.adb
17220 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17221 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17222 instr.ads
17223 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17224 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17225 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17226 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17227 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17228 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17229 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17230 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17231 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17232 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17233 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17234 @end smallexample
17235 @end ifset
17237 @node Cleaning Up with gnatclean
17238 @chapter Cleaning Up with @code{gnatclean}
17239 @findex gnatclean
17240 @cindex Cleaning tool
17242 @noindent
17243 @code{gnatclean} is a tool that allows the deletion of files produced by the
17244 compiler, binder and linker, including ALI files, object files, tree files,
17245 expanded source files, library files, interface copy source files, binder
17246 generated files and executable files.
17248 @menu
17249 * Running gnatclean::
17250 * Switches for gnatclean::
17251 @c * Examples of gnatclean Usage::
17252 @end menu
17254 @node Running gnatclean
17255 @section Running @code{gnatclean}
17257 @noindent
17258 The @code{gnatclean} command has the form:
17260 @smallexample
17261 $ gnatclean switches @var{names}
17262 @end smallexample
17264 @noindent
17265 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17266 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17267 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17269 @noindent
17270 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17271 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17272 the linker. In informative-only mode, specified by switch
17273 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17274 normal mode is listed, but no file is actually deleted.
17276 @node Switches for gnatclean
17277 @section Switches for @code{gnatclean}
17279 @noindent
17280 @code{gnatclean} recognizes the following switches:
17282 @table @option
17283 @c !sort!
17284 @cindex @option{--version} @command{gnatclean}
17285 Display Copyright and version, then exit disregarding all other options.
17287 @item --help
17288 @cindex @option{--help} @command{gnatclean}
17289 If @option{--version} was not used, display usage, then exit disregarding
17290 all other options.
17292 @item ^--subdirs^/SUBDIRS^=subdir
17293 Actual object directory of each project file is the subdirectory subdir of the
17294 object directory specified or defaulted in the project file.
17296 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17297 By default, shared library projects are not allowed to import static library
17298 projects. When this switch is used on the command line, this restriction is
17299 relaxed.
17301 @item ^-c^/COMPILER_FILES_ONLY^
17302 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17303 Only attempt to delete the files produced by the compiler, not those produced
17304 by the binder or the linker. The files that are not to be deleted are library
17305 files, interface copy files, binder generated files and executable files.
17307 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17308 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17309 Indicate that ALI and object files should normally be found in directory
17310 @var{dir}.
17312 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17313 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17314 When using project files, if some errors or warnings are detected during
17315 parsing and verbose mode is not in effect (no use of switch
17316 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17317 file, rather than its simple file name.
17319 @item ^-h^/HELP^
17320 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17321 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17323 @item ^-n^/NODELETE^
17324 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17325 Informative-only mode. Do not delete any files. Output the list of the files
17326 that would have been deleted if this switch was not specified.
17328 @item ^-P^/PROJECT_FILE=^@var{project}
17329 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17330 Use project file @var{project}. Only one such switch can be used.
17331 When cleaning a project file, the files produced by the compilation of the
17332 immediate sources or inherited sources of the project files are to be
17333 deleted. This is not depending on the presence or not of executable names
17334 on the command line.
17336 @item ^-q^/QUIET^
17337 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17338 Quiet output. If there are no errors, do not output anything, except in
17339 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17340 (switch ^-n^/NODELETE^).
17342 @item ^-r^/RECURSIVE^
17343 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17344 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17345 clean all imported and extended project files, recursively. If this switch
17346 is not specified, only the files related to the main project file are to be
17347 deleted. This switch has no effect if no project file is specified.
17349 @item ^-v^/VERBOSE^
17350 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17351 Verbose mode.
17353 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17354 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17355 Indicates the verbosity of the parsing of GNAT project files.
17356 @xref{Switches Related to Project Files}.
17358 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17359 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17360 Indicates that external variable @var{name} has the value @var{value}.
17361 The Project Manager will use this value for occurrences of
17362 @code{external(name)} when parsing the project file.
17363 @xref{Switches Related to Project Files}.
17365 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17366 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17367 When searching for ALI and object files, look in directory
17368 @var{dir}.
17370 @item ^-I^/SEARCH=^@var{dir}
17371 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17372 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17374 @item ^-I-^/NOCURRENT_DIRECTORY^
17375 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17376 @cindex Source files, suppressing search
17377 Do not look for ALI or object files in the directory
17378 where @code{gnatclean} was invoked.
17380 @end table
17382 @c @node Examples of gnatclean Usage
17383 @c @section Examples of @code{gnatclean} Usage
17385 @ifclear vms
17386 @node GNAT and Libraries
17387 @chapter GNAT and Libraries
17388 @cindex Library, building, installing, using
17390 @noindent
17391 This chapter describes how to build and use libraries with GNAT, and also shows
17392 how to recompile the GNAT run-time library. You should be familiar with the
17393 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17394 chapter.
17396 @menu
17397 * Introduction to Libraries in GNAT::
17398 * General Ada Libraries::
17399 * Stand-alone Ada Libraries::
17400 * Rebuilding the GNAT Run-Time Library::
17401 @end menu
17403 @node Introduction to Libraries in GNAT
17404 @section Introduction to Libraries in GNAT
17406 @noindent
17407 A library is, conceptually, a collection of objects which does not have its
17408 own main thread of execution, but rather provides certain services to the
17409 applications that use it. A library can be either statically linked with the
17410 application, in which case its code is directly included in the application,
17411 or, on platforms that support it, be dynamically linked, in which case
17412 its code is shared by all applications making use of this library.
17414 GNAT supports both types of libraries.
17415 In the static case, the compiled code can be provided in different ways. The
17416 simplest approach is to provide directly the set of objects resulting from
17417 compilation of the library source files. Alternatively, you can group the
17418 objects into an archive using whatever commands are provided by the operating
17419 system. For the latter case, the objects are grouped into a shared library.
17421 In the GNAT environment, a library has three types of components:
17422 @itemize @bullet
17423 @item
17424 Source files.
17425 @item
17426 @file{ALI} files.
17427 @xref{The Ada Library Information Files}.
17428 @item
17429 Object files, an archive or a shared library.
17430 @end itemize
17432 @noindent
17433 A GNAT library may expose all its source files, which is useful for
17434 documentation purposes. Alternatively, it may expose only the units needed by
17435 an external user to make use of the library. That is to say, the specs
17436 reflecting the library services along with all the units needed to compile
17437 those specs, which can include generic bodies or any body implementing an
17438 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17439 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17441 All compilation units comprising an application, including those in a library,
17442 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17443 computes the elaboration order from the @file{ALI} files and this is why they
17444 constitute a mandatory part of GNAT libraries.
17445 @emph{Stand-alone libraries} are the exception to this rule because a specific
17446 library elaboration routine is produced independently of the application(s)
17447 using the library.
17449 @node General Ada Libraries
17450 @section General Ada Libraries
17452 @menu
17453 * Building a library::
17454 * Installing a library::
17455 * Using a library::
17456 @end menu
17458 @node Building a library
17459 @subsection Building a library
17461 @noindent
17462 The easiest way to build a library is to use the Project Manager,
17463 which supports a special type of project called a @emph{Library Project}
17464 (@pxref{Library Projects}).
17466 A project is considered a library project, when two project-level attributes
17467 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17468 control different aspects of library configuration, additional optional
17469 project-level attributes can be specified:
17470 @table @code
17471 @item Library_Kind
17472 This attribute controls whether the library is to be static or dynamic
17474 @item Library_Version
17475 This attribute specifies the library version; this value is used
17476 during dynamic linking of shared libraries to determine if the currently
17477 installed versions of the binaries are compatible.
17479 @item Library_Options
17480 @item Library_GCC
17481 These attributes specify additional low-level options to be used during
17482 library generation, and redefine the actual application used to generate
17483 library.
17484 @end table
17486 @noindent
17487 The GNAT Project Manager takes full care of the library maintenance task,
17488 including recompilation of the source files for which objects do not exist
17489 or are not up to date, assembly of the library archive, and installation of
17490 the library (i.e., copying associated source, object and @file{ALI} files
17491 to the specified location).
17493 Here is a simple library project file:
17494 @smallexample @c ada
17495 project My_Lib is
17496    for Source_Dirs use ("src1", "src2");
17497    for Object_Dir use "obj";
17498    for Library_Name use "mylib";
17499    for Library_Dir use "lib";
17500    for Library_Kind use "dynamic";
17501 end My_lib;
17502 @end smallexample
17504 @noindent
17505 and the compilation command to build and install the library:
17507 @smallexample @c ada
17508   $ gnatmake -Pmy_lib
17509 @end smallexample
17511 @noindent
17512 It is not entirely trivial to perform manually all the steps required to
17513 produce a library. We recommend that you use the GNAT Project Manager
17514 for this task. In special cases where this is not desired, the necessary
17515 steps are discussed below.
17517 There are various possibilities for compiling the units that make up the
17518 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17519 with a conventional script. For simple libraries, it is also possible to create
17520 a dummy main program which depends upon all the packages that comprise the
17521 interface of the library. This dummy main program can then be given to
17522 @command{gnatmake}, which will ensure that all necessary objects are built.
17524 After this task is accomplished, you should follow the standard procedure
17525 of the underlying operating system to produce the static or shared library.
17527 Here is an example of such a dummy program:
17528 @smallexample @c ada
17529 @group
17530 with My_Lib.Service1;
17531 with My_Lib.Service2;
17532 with My_Lib.Service3;
17533 procedure My_Lib_Dummy is
17534 begin
17535    null;
17536 end;
17537 @end group
17538 @end smallexample
17540 @noindent
17541 Here are the generic commands that will build an archive or a shared library.
17543 @smallexample
17544 # compiling the library
17545 $ gnatmake -c my_lib_dummy.adb
17547 # we don't need the dummy object itself
17548 $ rm my_lib_dummy.o my_lib_dummy.ali
17550 # create an archive with the remaining objects
17551 $ ar rc libmy_lib.a *.o
17552 # some systems may require "ranlib" to be run as well
17554 # or create a shared library
17555 $ gcc -shared -o libmy_lib.so *.o
17556 # some systems may require the code to have been compiled with -fPIC
17558 # remove the object files that are now in the library
17559 $ rm *.o
17561 # Make the ALI files read-only so that gnatmake will not try to
17562 # regenerate the objects that are in the library
17563 $ chmod -w *.ali
17564 @end smallexample
17566 @noindent
17567 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17568 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17569 be accessed by the directive @option{-l@var{xxx}} at link time.
17571 @node Installing a library
17572 @subsection Installing a library
17573 @cindex @code{ADA_PROJECT_PATH}
17574 @cindex @code{GPR_PROJECT_PATH}
17576 @noindent
17577 If you use project files, library installation is part of the library build
17578 process (@pxref{Installing a library with project files}).
17580 When project files are not an option, it is also possible, but not recommended,
17581 to install the library so that the sources needed to use the library are on the
17582 Ada source path and the ALI files & libraries be on the Ada Object path (see
17583 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17584 administrator can place general-purpose libraries in the default compiler
17585 paths, by specifying the libraries' location in the configuration files
17586 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17587 must be located in the GNAT installation tree at the same place as the gcc spec
17588 file. The location of the gcc spec file can be determined as follows:
17589 @smallexample
17590 $ gcc -v
17591 @end smallexample
17593 @noindent
17594 The configuration files mentioned above have a simple format: each line
17595 must contain one unique directory name.
17596 Those names are added to the corresponding path
17597 in their order of appearance in the file. The names can be either absolute
17598 or relative; in the latter case, they are relative to where theses files
17599 are located.
17601 The files @file{ada_source_path} and @file{ada_object_path} might not be
17602 present in a
17603 GNAT installation, in which case, GNAT will look for its run-time library in
17604 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17605 objects and @file{ALI} files). When the files exist, the compiler does not
17606 look in @file{adainclude} and @file{adalib}, and thus the
17607 @file{ada_source_path} file
17608 must contain the location for the GNAT run-time sources (which can simply
17609 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17610 contain the location for the GNAT run-time objects (which can simply
17611 be @file{adalib}).
17613 You can also specify a new default path to the run-time library at compilation
17614 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17615 the run-time library you want your program to be compiled with. This switch is
17616 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17617 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17619 It is possible to install a library before or after the standard GNAT
17620 library, by reordering the lines in the configuration files. In general, a
17621 library must be installed before the GNAT library if it redefines
17622 any part of it.
17624 @node Using a library
17625 @subsection Using a library
17627 @noindent Once again, the project facility greatly simplifies the use of
17628 libraries. In this context, using a library is just a matter of adding a
17629 @code{with} clause in the user project. For instance, to make use of the
17630 library @code{My_Lib} shown in examples in earlier sections, you can
17631 write:
17633 @smallexample @c projectfile
17634 with "my_lib";
17635 project My_Proj is
17636   @dots{}
17637 end My_Proj;
17638 @end smallexample
17640 Even if you have a third-party, non-Ada library, you can still use GNAT's
17641 Project Manager facility to provide a wrapper for it. For example, the
17642 following project, when @code{with}ed by your main project, will link with the
17643 third-party library @file{liba.a}:
17645 @smallexample @c projectfile
17646 @group
17647 project Liba is
17648    for Externally_Built use "true";
17649    for Source_Files use ();
17650    for Library_Dir use "lib";
17651    for Library_Name use "a";
17652    for Library_Kind use "static";
17653 end Liba;
17654 @end group
17655 @end smallexample
17656 This is an alternative to the use of @code{pragma Linker_Options}. It is
17657 especially interesting in the context of systems with several interdependent
17658 static libraries where finding a proper linker order is not easy and best be
17659 left to the tools having visibility over project dependence information.
17661 @noindent
17662 In order to use an Ada library manually, you need to make sure that this
17663 library is on both your source and object path
17664 (see @ref{Search Paths and the Run-Time Library (RTL)}
17665 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17666 in an archive or a shared library, you need to specify the desired
17667 library at link time.
17669 For example, you can use the library @file{mylib} installed in
17670 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17672 @smallexample
17673 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17674   -largs -lmy_lib
17675 @end smallexample
17677 @noindent
17678 This can be expressed more simply:
17679 @smallexample
17680 $ gnatmake my_appl
17681 @end smallexample
17682 @noindent
17683 when the following conditions are met:
17684 @itemize @bullet
17685 @item
17686 @file{/dir/my_lib_src} has been added by the user to the environment
17687 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17688 @file{ada_source_path}
17689 @item
17690 @file{/dir/my_lib_obj} has been added by the user to the environment
17691 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17692 @file{ada_object_path}
17693 @item
17694 a pragma @code{Linker_Options} has been added to one of the sources.
17695 For example:
17697 @smallexample @c ada
17698 pragma Linker_Options ("-lmy_lib");
17699 @end smallexample
17700 @end itemize
17702 @node Stand-alone Ada Libraries
17703 @section Stand-alone Ada Libraries
17704 @cindex Stand-alone library, building, using
17706 @menu
17707 * Introduction to Stand-alone Libraries::
17708 * Building a Stand-alone Library::
17709 * Creating a Stand-alone Library to be used in a non-Ada context::
17710 * Restrictions in Stand-alone Libraries::
17711 @end menu
17713 @node Introduction to Stand-alone Libraries
17714 @subsection Introduction to Stand-alone Libraries
17716 @noindent
17717 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17718 necessary code to
17719 elaborate the Ada units that are included in the library. In contrast with
17720 an ordinary library, which consists of all sources, objects and @file{ALI}
17721 files of the
17722 library, a SAL may specify a restricted subset of compilation units
17723 to serve as a library interface. In this case, the fully
17724 self-sufficient set of files will normally consist of an objects
17725 archive, the sources of interface units' specs, and the @file{ALI}
17726 files of interface units.
17727 If an interface spec contains a generic unit or an inlined subprogram,
17728 the body's
17729 source must also be provided; if the units that must be provided in the source
17730 form depend on other units, the source and @file{ALI} files of those must
17731 also be provided.
17733 The main purpose of a SAL is to minimize the recompilation overhead of client
17734 applications when a new version of the library is installed. Specifically,
17735 if the interface sources have not changed, client applications do not need to
17736 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17737 version, controlled by @code{Library_Version} attribute, is not changed,
17738 then the clients do not need to be relinked.
17740 SALs also allow the library providers to minimize the amount of library source
17741 text exposed to the clients.  Such ``information hiding'' might be useful or
17742 necessary for various reasons.
17744 Stand-alone libraries are also well suited to be used in an executable whose
17745 main routine is not written in Ada.
17747 @node Building a Stand-alone Library
17748 @subsection Building a Stand-alone Library
17750 @noindent
17751 GNAT's Project facility provides a simple way of building and installing
17752 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17753 To be a Stand-alone Library Project, in addition to the two attributes
17754 that make a project a Library Project (@code{Library_Name} and
17755 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17756 @code{Library_Interface} must be defined.  For example:
17758 @smallexample @c projectfile
17759 @group
17760    for Library_Dir use "lib_dir";
17761    for Library_Name use "dummy";
17762    for Library_Interface use ("int1", "int1.child");
17763 @end group
17764 @end smallexample
17766 @noindent
17767 Attribute @code{Library_Interface} has a non-empty string list value,
17768 each string in the list designating a unit contained in an immediate source
17769 of the project file.
17771 When a Stand-alone Library is built, first the binder is invoked to build
17772 a package whose name depends on the library name
17773 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17774 This binder-generated package includes initialization and
17775 finalization procedures whose
17776 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17777 in the example
17778 above). The object corresponding to this package is included in the library.
17780 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17781 calling of these procedures if a static SAL is built, or if a shared SAL
17782 is built
17783 with the project-level attribute @code{Library_Auto_Init} set to
17784 @code{"false"}.
17786 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17787 (those that are listed in attribute @code{Library_Interface}) are copied to
17788 the Library Directory. As a consequence, only the Interface Units may be
17789 imported from Ada units outside of the library. If other units are imported,
17790 the binding phase will fail.
17792 @noindent
17793 It is also possible to build an encapsulated library where not only
17794 the code to elaborate and finalize the library is embedded but also
17795 ensuring that the library is linked only against static
17796 libraries. So an encapsulated library only depends on system
17797 libraries, all other code, including the GNAT runtime, is embedded. To
17798 build an encapsulated library the attribute
17799 @code{Library_Standalone} must be set to @code{encapsulated}:
17801 @smallexample @c projectfile
17802 @group
17803    for Library_Dir use "lib_dir";
17804    for Library_Name use "dummy";
17805    for Library_Kind use "dynamic";
17806    for Library_Interface use ("int1", "int1.child");
17807    for Library_Standalone use "encapsulated";
17808 @end group
17809 @end smallexample
17811 @noindent
17812 The default value for this attribute is @code{standard} in which case
17813 a stand-alone library is built.
17815 The attribute @code{Library_Src_Dir} may be specified for a
17816 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17817 single string value. Its value must be the path (absolute or relative to the
17818 project directory) of an existing directory. This directory cannot be the
17819 object directory or one of the source directories, but it can be the same as
17820 the library directory. The sources of the Interface
17821 Units of the library that are needed by an Ada client of the library will be
17822 copied to the designated directory, called the Interface Copy directory.
17823 These sources include the specs of the Interface Units, but they may also
17824 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17825 are used, or when there is a generic unit in the spec. Before the sources
17826 are copied to the Interface Copy directory, an attempt is made to delete all
17827 files in the Interface Copy directory.
17829 Building stand-alone libraries by hand is somewhat tedious, but for those
17830 occasions when it is necessary here are the steps that you need to perform:
17831 @itemize @bullet
17832 @item
17833 Compile all library sources.
17835 @item
17836 Invoke the binder with the switch @option{-n} (No Ada main program),
17837 with all the @file{ALI} files of the interfaces, and
17838 with the switch @option{-L} to give specific names to the @code{init}
17839 and @code{final} procedures.  For example:
17840 @smallexample
17841   gnatbind -n int1.ali int2.ali -Lsal1
17842 @end smallexample
17844 @item
17845 Compile the binder generated file:
17846 @smallexample
17847   gcc -c b~int2.adb
17848 @end smallexample
17850 @item
17851 Link the dynamic library with all the necessary object files,
17852 indicating to the linker the names of the @code{init} (and possibly
17853 @code{final}) procedures for automatic initialization (and finalization).
17854 The built library should be placed in a directory different from
17855 the object directory.
17857 @item
17858 Copy the @code{ALI} files of the interface to the library directory,
17859 add in this copy an indication that it is an interface to a SAL
17860 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17861 with letter ``P'') and make the modified copy of the @file{ALI} file
17862 read-only.
17863 @end itemize
17865 @noindent
17866 Using SALs is not different from using other libraries
17867 (see @ref{Using a library}).
17869 @node Creating a Stand-alone Library to be used in a non-Ada context
17870 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17872 @noindent
17873 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17874 a non-Ada context.
17876 The only extra step required is to ensure that library interface subprograms
17877 are compatible with the main program, by means of @code{pragma Export}
17878 or @code{pragma Convention}.
17880 Here is an example of simple library interface for use with C main program:
17882 @smallexample @c ada
17883 package My_Package is
17885    procedure Do_Something;
17886    pragma Export (C, Do_Something, "do_something");
17888    procedure Do_Something_Else;
17889    pragma Export (C, Do_Something_Else, "do_something_else");
17891 end My_Package;
17892 @end smallexample
17894 @noindent
17895 On the foreign language side, you must provide a ``foreign'' view of the
17896 library interface; remember that it should contain elaboration routines in
17897 addition to interface subprograms.
17899 The example below shows the content of @code{mylib_interface.h} (note
17900 that there is no rule for the naming of this file, any name can be used)
17901 @smallexample
17902 /* the library elaboration procedure */
17903 extern void mylibinit (void);
17905 /* the library finalization procedure */
17906 extern void mylibfinal (void);
17908 /* the interface exported by the library */
17909 extern void do_something (void);
17910 extern void do_something_else (void);
17911 @end smallexample
17913 @noindent
17914 Libraries built as explained above can be used from any program, provided
17915 that the elaboration procedures (named @code{mylibinit} in the previous
17916 example) are called before the library services are used. Any number of
17917 libraries can be used simultaneously, as long as the elaboration
17918 procedure of each library is called.
17920 Below is an example of a C program that uses the @code{mylib} library.
17922 @smallexample
17923 #include "mylib_interface.h"
17926 main (void)
17928    /* First, elaborate the library before using it */
17929    mylibinit ();
17931    /* Main program, using the library exported entities */
17932    do_something ();
17933    do_something_else ();
17935    /* Library finalization at the end of the program */
17936    mylibfinal ();
17937    return 0;
17939 @end smallexample
17941 @noindent
17942 Note that invoking any library finalization procedure generated by
17943 @code{gnatbind} shuts down the Ada run-time environment.
17944 Consequently, the
17945 finalization of all Ada libraries must be performed at the end of the program.
17946 No call to these libraries or to the Ada run-time library should be made
17947 after the finalization phase.
17949 @node Restrictions in Stand-alone Libraries
17950 @subsection Restrictions in Stand-alone Libraries
17952 @noindent
17953 The pragmas listed below should be used with caution inside libraries,
17954 as they can create incompatibilities with other Ada libraries:
17955 @itemize @bullet
17956 @item pragma @code{Locking_Policy}
17957 @item pragma @code{Partition_Elaboration_Policy}
17958 @item pragma @code{Queuing_Policy}
17959 @item pragma @code{Task_Dispatching_Policy}
17960 @item pragma @code{Unreserve_All_Interrupts}
17961 @end itemize
17963 @noindent
17964 When using a library that contains such pragmas, the user must make sure
17965 that all libraries use the same pragmas with the same values. Otherwise,
17966 @code{Program_Error} will
17967 be raised during the elaboration of the conflicting
17968 libraries. The usage of these pragmas and its consequences for the user
17969 should therefore be well documented.
17971 Similarly, the traceback in the exception occurrence mechanism should be
17972 enabled or disabled in a consistent manner across all libraries.
17973 Otherwise, Program_Error will be raised during the elaboration of the
17974 conflicting libraries.
17976 If the @code{Version} or @code{Body_Version}
17977 attributes are used inside a library, then you need to
17978 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17979 libraries, so that version identifiers can be properly computed.
17980 In practice these attributes are rarely used, so this is unlikely
17981 to be a consideration.
17983 @node  Rebuilding the GNAT Run-Time Library
17984 @section Rebuilding the GNAT Run-Time Library
17985 @cindex GNAT Run-Time Library, rebuilding
17986 @cindex Building the GNAT Run-Time Library
17987 @cindex Rebuilding the GNAT Run-Time Library
17988 @cindex Run-Time Library, rebuilding
17990 @noindent
17991 It may be useful to recompile the GNAT library in various contexts, the
17992 most important one being the use of partition-wide configuration pragmas
17993 such as @code{Normalize_Scalars}. A special Makefile called
17994 @code{Makefile.adalib} is provided to that effect and can be found in
17995 the directory containing the GNAT library. The location of this
17996 directory depends on the way the GNAT environment has been installed and can
17997 be determined by means of the command:
17999 @smallexample
18000 $ gnatls -v
18001 @end smallexample
18003 @noindent
18004 The last entry in the object search path usually contains the
18005 gnat library. This Makefile contains its own documentation and in
18006 particular the set of instructions needed to rebuild a new library and
18007 to use it.
18009 @node Using the GNU make Utility
18010 @chapter Using the GNU @code{make} Utility
18011 @findex make
18013 @noindent
18014 This chapter offers some examples of makefiles that solve specific
18015 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
18016 make, make, GNU @code{make}}), nor does it try to replace the
18017 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
18019 All the examples in this section are specific to the GNU version of
18020 make. Although @command{make} is a standard utility, and the basic language
18021 is the same, these examples use some advanced features found only in
18022 @code{GNU make}.
18024 @menu
18025 * Using gnatmake in a Makefile::
18026 * Automatically Creating a List of Directories::
18027 * Generating the Command Line Switches::
18028 * Overcoming Command Line Length Limits::
18029 @end menu
18031 @node Using gnatmake in a Makefile
18032 @section Using gnatmake in a Makefile
18033 @findex makefile
18034 @cindex GNU make
18036 @noindent
18037 Complex project organizations can be handled in a very powerful way by
18038 using GNU make combined with gnatmake. For instance, here is a Makefile
18039 which allows you to build each subsystem of a big project into a separate
18040 shared library. Such a makefile allows you to significantly reduce the link
18041 time of very big applications while maintaining full coherence at
18042 each step of the build process.
18044 The list of dependencies are handled automatically by
18045 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18046 the appropriate directories.
18048 Note that you should also read the example on how to automatically
18049 create the list of directories
18050 (@pxref{Automatically Creating a List of Directories})
18051 which might help you in case your project has a lot of subdirectories.
18053 @smallexample
18054 @iftex
18055 @leftskip=0cm
18056 @font@heightrm=cmr8
18057 @heightrm
18058 @end iftex
18059 ## This Makefile is intended to be used with the following directory
18060 ## configuration:
18061 ##  - The sources are split into a series of csc (computer software components)
18062 ##    Each of these csc is put in its own directory.
18063 ##    Their name are referenced by the directory names.
18064 ##    They will be compiled into shared library (although this would also work
18065 ##    with static libraries
18066 ##  - The main program (and possibly other packages that do not belong to any
18067 ##    csc is put in the top level directory (where the Makefile is).
18068 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
18069 ##                    \_ second_csc (sources) __ lib (will contain the library)
18070 ##                    \_ @dots{}
18071 ## Although this Makefile is build for shared library, it is easy to modify
18072 ## to build partial link objects instead (modify the lines with -shared and
18073 ## gnatlink below)
18075 ## With this makefile, you can change any file in the system or add any new
18076 ## file, and everything will be recompiled correctly (only the relevant shared
18077 ## objects will be recompiled, and the main program will be re-linked).
18079 # The list of computer software component for your project. This might be
18080 # generated automatically.
18081 CSC_LIST=aa bb cc
18083 # Name of the main program (no extension)
18084 MAIN=main
18086 # If we need to build objects with -fPIC, uncomment the following line
18087 #NEED_FPIC=-fPIC
18089 # The following variable should give the directory containing libgnat.so
18090 # You can get this directory through 'gnatls -v'. This is usually the last
18091 # directory in the Object_Path.
18092 GLIB=@dots{}
18094 # The directories for the libraries
18095 # (This macro expands the list of CSC to the list of shared libraries, you
18096 # could simply use the expanded form:
18097 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18098 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18100 $@{MAIN@}: objects $@{LIB_DIR@}
18101     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18102     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18104 objects::
18105     # recompile the sources
18106     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18108 # Note: In a future version of GNAT, the following commands will be simplified
18109 # by a new tool, gnatmlib
18110 $@{LIB_DIR@}:
18111     mkdir -p $@{dir $@@ @}
18112     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18113     cd $@{dir $@@ @} && cp -f ../*.ali .
18115 # The dependencies for the modules
18116 # Note that we have to force the expansion of *.o, since in some cases
18117 # make won't be able to do it itself.
18118 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18119 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18120 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18122 # Make sure all of the shared libraries are in the path before starting the
18123 # program
18124 run::
18125     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18127 clean::
18128     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18129     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18130     $@{RM@} $@{CSC_LIST:%=%/*.o@}
18131     $@{RM@} *.o *.ali $@{MAIN@}
18132 @end smallexample
18134 @node Automatically Creating a List of Directories
18135 @section Automatically Creating a List of Directories
18137 @noindent
18138 In most makefiles, you will have to specify a list of directories, and
18139 store it in a variable. For small projects, it is often easier to
18140 specify each of them by hand, since you then have full control over what
18141 is the proper order for these directories, which ones should be
18142 included.
18144 However, in larger projects, which might involve hundreds of
18145 subdirectories, it might be more convenient to generate this list
18146 automatically.
18148 The example below presents two methods. The first one, although less
18149 general, gives you more control over the list. It involves wildcard
18150 characters, that are automatically expanded by @command{make}. Its
18151 shortcoming is that you need to explicitly specify some of the
18152 organization of your project, such as for instance the directory tree
18153 depth, whether some directories are found in a separate tree, @enddots{}
18155 The second method is the most general one. It requires an external
18156 program, called @command{find}, which is standard on all Unix systems. All
18157 the directories found under a given root directory will be added to the
18158 list.
18160 @smallexample
18161 @iftex
18162 @leftskip=0cm
18163 @font@heightrm=cmr8
18164 @heightrm
18165 @end iftex
18166 # The examples below are based on the following directory hierarchy:
18167 # All the directories can contain any number of files
18168 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
18169 #                       ->  ab
18170 #                       ->  ac
18171 #                ->  b  ->  ba  ->  baa
18172 #                       ->  bb
18173 #                       ->  bc
18174 # This Makefile creates a variable called DIRS, that can be reused any time
18175 # you need this list (see the other examples in this section)
18177 # The root of your project's directory hierarchy
18178 ROOT_DIRECTORY=.
18180 ####
18181 # First method: specify explicitly the list of directories
18182 # This allows you to specify any subset of all the directories you need.
18183 ####
18185 DIRS := a/aa/ a/ab/ b/ba/
18187 ####
18188 # Second method: use wildcards
18189 # Note that the argument(s) to wildcard below should end with a '/'.
18190 # Since wildcards also return file names, we have to filter them out
18191 # to avoid duplicate directory names.
18192 # We thus use make's @code{dir} and @code{sort} functions.
18193 # It sets DIRs to the following value (note that the directories aaa and baa
18194 # are not given, unless you change the arguments to wildcard).
18195 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18196 ####
18198 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18199                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18201 ####
18202 # Third method: use an external program
18203 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18204 # This is the most complete command: it sets DIRs to the following value:
18205 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18206 ####
18208 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18210 @end smallexample
18212 @node Generating the Command Line Switches
18213 @section Generating the Command Line Switches
18215 @noindent
18216 Once you have created the list of directories as explained in the
18217 previous section (@pxref{Automatically Creating a List of Directories}),
18218 you can easily generate the command line arguments to pass to gnatmake.
18220 For the sake of completeness, this example assumes that the source path
18221 is not the same as the object path, and that you have two separate lists
18222 of directories.
18224 @smallexample
18225 # see "Automatically creating a list of directories" to create
18226 # these variables
18227 SOURCE_DIRS=
18228 OBJECT_DIRS=
18230 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18231 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18233 all:
18234         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18235 @end smallexample
18237 @node Overcoming Command Line Length Limits
18238 @section Overcoming Command Line Length Limits
18240 @noindent
18241 One problem that might be encountered on big projects is that many
18242 operating systems limit the length of the command line. It is thus hard to give
18243 gnatmake the list of source and object directories.
18245 This example shows how you can set up environment variables, which will
18246 make @command{gnatmake} behave exactly as if the directories had been
18247 specified on the command line, but have a much higher length limit (or
18248 even none on most systems).
18250 It assumes that you have created a list of directories in your Makefile,
18251 using one of the methods presented in
18252 @ref{Automatically Creating a List of Directories}.
18253 For the sake of completeness, we assume that the object
18254 path (where the ALI files are found) is different from the sources patch.
18256 Note a small trick in the Makefile below: for efficiency reasons, we
18257 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18258 expanded immediately by @code{make}. This way we overcome the standard
18259 make behavior which is to expand the variables only when they are
18260 actually used.
18262 On Windows, if you are using the standard Windows command shell, you must
18263 replace colons with semicolons in the assignments to these variables.
18265 @smallexample
18266 @iftex
18267 @leftskip=0cm
18268 @font@heightrm=cmr8
18269 @heightrm
18270 @end iftex
18271 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
18272 # This is the same thing as putting the -I arguments on the command line.
18273 # (the equivalent of using -aI on the command line would be to define
18274 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18275 # You can of course have different values for these variables.
18277 # Note also that we need to keep the previous values of these variables, since
18278 # they might have been set before running 'make' to specify where the GNAT
18279 # library is installed.
18281 # see "Automatically creating a list of directories" to create these
18282 # variables
18283 SOURCE_DIRS=
18284 OBJECT_DIRS=
18286 empty:=
18287 space:=$@{empty@} $@{empty@}
18288 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18289 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18290 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18291 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18292 export ADA_INCLUDE_PATH
18293 export ADA_OBJECTS_PATH
18295 all:
18296         gnatmake main_unit
18297 @end smallexample
18298 @end ifclear
18300 @node Memory Management Issues
18301 @chapter Memory Management Issues
18303 @noindent
18304 This chapter describes some useful memory pools provided in the GNAT library
18305 and in particular the GNAT Debug Pool facility, which can be used to detect
18306 incorrect uses of access values (including ``dangling references'').
18307 @ifclear vms
18308 It also describes the @command{gnatmem} tool, which can be used to track down
18309 ``memory leaks''.
18310 @end ifclear
18312 @menu
18313 * Some Useful Memory Pools::
18314 * The GNAT Debug Pool Facility::
18315 @ifclear vms
18316 * The gnatmem Tool::
18317 @end ifclear
18318 @end menu
18320 @node Some Useful Memory Pools
18321 @section Some Useful Memory Pools
18322 @findex Memory Pool
18323 @cindex storage, pool
18325 @noindent
18326 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18327 storage pool. Allocations use the standard system call @code{malloc} while
18328 deallocations use the standard system call @code{free}. No reclamation is
18329 performed when the pool goes out of scope. For performance reasons, the
18330 standard default Ada allocators/deallocators do not use any explicit storage
18331 pools but if they did, they could use this storage pool without any change in
18332 behavior. That is why this storage pool is used  when the user
18333 manages to make the default implicit allocator explicit as in this example:
18334 @smallexample @c ada
18335    type T1 is access Something;
18336     -- no Storage pool is defined for T2
18337    type T2 is access Something_Else;
18338    for T2'Storage_Pool use T1'Storage_Pool;
18339    -- the above is equivalent to
18340    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18341 @end smallexample
18343 @noindent
18344 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18345 pool. The allocation strategy is similar to @code{Pool_Local}'s
18346 except that the all
18347 storage allocated with this pool is reclaimed when the pool object goes out of
18348 scope. This pool provides a explicit mechanism similar to the implicit one
18349 provided by several Ada 83 compilers for allocations performed through a local
18350 access type and whose purpose was to reclaim memory when exiting the
18351 scope of a given local access. As an example, the following program does not
18352 leak memory even though it does not perform explicit deallocation:
18354 @smallexample @c ada
18355 with System.Pool_Local;
18356 procedure Pooloc1 is
18357    procedure Internal is
18358       type A is access Integer;
18359       X : System.Pool_Local.Unbounded_Reclaim_Pool;
18360       for A'Storage_Pool use X;
18361       v : A;
18362    begin
18363       for I in  1 .. 50 loop
18364          v := new Integer;
18365       end loop;
18366    end Internal;
18367 begin
18368    for I in  1 .. 100 loop
18369       Internal;
18370    end loop;
18371 end Pooloc1;
18372 @end smallexample
18374 @noindent
18375 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18376 @code{Storage_Size} is specified for an access type.
18377 The whole storage for the pool is
18378 allocated at once, usually on the stack at the point where the access type is
18379 elaborated. It is automatically reclaimed when exiting the scope where the
18380 access type is defined. This package is not intended to be used directly by the
18381 user and it is implicitly used for each such declaration:
18383 @smallexample @c ada
18384    type T1 is access Something;
18385    for T1'Storage_Size use 10_000;
18386 @end smallexample
18388 @node The GNAT Debug Pool Facility
18389 @section The GNAT Debug Pool Facility
18390 @findex Debug Pool
18391 @cindex storage, pool, memory corruption
18393 @noindent
18394 The use of unchecked deallocation and unchecked conversion can easily
18395 lead to incorrect memory references. The problems generated by such
18396 references are usually difficult to tackle because the symptoms can be
18397 very remote from the origin of the problem. In such cases, it is
18398 very helpful to detect the problem as early as possible. This is the
18399 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18401 In order to use the GNAT specific debugging pool, the user must
18402 associate a debug pool object with each of the access types that may be
18403 related to suspected memory problems. See Ada Reference Manual 13.11.
18404 @smallexample @c ada
18405 type Ptr is access Some_Type;
18406 Pool : GNAT.Debug_Pools.Debug_Pool;
18407 for Ptr'Storage_Pool use Pool;
18408 @end smallexample
18410 @noindent
18411 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18412 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18413 allow the user to redefine allocation and deallocation strategies. They
18414 also provide a checkpoint for each dereference, through the use of
18415 the primitive operation @code{Dereference} which is implicitly called at
18416 each dereference of an access value.
18418 Once an access type has been associated with a debug pool, operations on
18419 values of the type may raise four distinct exceptions,
18420 which correspond to four potential kinds of memory corruption:
18421 @itemize @bullet
18422 @item
18423 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18424 @item
18425 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18426 @item
18427 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18428 @item
18429 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18430 @end itemize
18432 @noindent
18433 For types associated with a Debug_Pool, dynamic allocation is performed using
18434 the standard GNAT allocation routine. References to all allocated chunks of
18435 memory are kept in an internal dictionary. Several deallocation strategies are
18436 provided, whereupon the user can choose to release the memory to the system,
18437 keep it allocated for further invalid access checks, or fill it with an easily
18438 recognizable pattern for debug sessions. The memory pattern is the old IBM
18439 hexadecimal convention: @code{16#DEADBEEF#}.
18441 See the documentation in the file g-debpoo.ads for more information on the
18442 various strategies.
18444 Upon each dereference, a check is made that the access value denotes a
18445 properly allocated memory location. Here is a complete example of use of
18446 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18447 @smallexample @c ada
18448 @iftex
18449 @leftskip=0cm
18450 @end iftex
18451 with Gnat.Io; use Gnat.Io;
18452 with Unchecked_Deallocation;
18453 with Unchecked_Conversion;
18454 with GNAT.Debug_Pools;
18455 with System.Storage_Elements;
18456 with Ada.Exceptions; use Ada.Exceptions;
18457 procedure Debug_Pool_Test is
18459    type T is access Integer;
18460    type U is access all T;
18462    P : GNAT.Debug_Pools.Debug_Pool;
18463    for T'Storage_Pool use P;
18465    procedure Free is new Unchecked_Deallocation (Integer, T);
18466    function UC is new Unchecked_Conversion (U, T);
18467    A, B : aliased T;
18469    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18471 begin
18472    Info (P);
18473    A := new Integer;
18474    B := new Integer;
18475    B := A;
18476    Info (P);
18477    Free (A);
18478    begin
18479       Put_Line (Integer'Image(B.all));
18480    exception
18481       when E : others => Put_Line ("raised: " & Exception_Name (E));
18482    end;
18483    begin
18484       Free (B);
18485    exception
18486       when E : others => Put_Line ("raised: " & Exception_Name (E));
18487    end;
18488    B := UC(A'Access);
18489    begin
18490       Put_Line (Integer'Image(B.all));
18491    exception
18492       when E : others => Put_Line ("raised: " & Exception_Name (E));
18493    end;
18494    begin
18495       Free (B);
18496    exception
18497       when E : others => Put_Line ("raised: " & Exception_Name (E));
18498    end;
18499    Info (P);
18500 end Debug_Pool_Test;
18501 @end smallexample
18503 @noindent
18504 The debug pool mechanism provides the following precise diagnostics on the
18505 execution of this erroneous program:
18506 @smallexample
18507 Debug Pool info:
18508   Total allocated bytes :  0
18509   Total deallocated bytes :  0
18510   Current Water Mark:  0
18511   High Water Mark:  0
18513 Debug Pool info:
18514   Total allocated bytes :  8
18515   Total deallocated bytes :  0
18516   Current Water Mark:  8
18517   High Water Mark:  8
18519 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18520 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18521 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18522 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18523 Debug Pool info:
18524   Total allocated bytes :  8
18525   Total deallocated bytes :  4
18526   Current Water Mark:  4
18527   High Water Mark:  8
18528 @end smallexample
18530 @ifclear vms
18531 @node The gnatmem Tool
18532 @section The @command{gnatmem} Tool
18533 @findex gnatmem
18535 @noindent
18536 The @code{gnatmem} utility monitors dynamic allocation and
18537 deallocation activity in a program, and displays information about
18538 incorrect deallocations and possible sources of memory leaks.
18539 It is designed to work in association with a static runtime library
18540 only and in this context provides three types of information:
18541 @itemize @bullet
18542 @item
18543 General information concerning memory management, such as the total
18544 number of allocations and deallocations, the amount of allocated
18545 memory and the high water mark, i.e.@: the largest amount of allocated
18546 memory in the course of program execution.
18548 @item
18549 Backtraces for all incorrect deallocations, that is to say deallocations
18550 which do not correspond to a valid allocation.
18552 @item
18553 Information on each allocation that is potentially the origin of a memory
18554 leak.
18555 @end itemize
18557 @menu
18558 * Running gnatmem::
18559 * Switches for gnatmem::
18560 * Example of gnatmem Usage::
18561 @end menu
18563 @node Running gnatmem
18564 @subsection Running @code{gnatmem}
18566 @noindent
18567 @code{gnatmem} makes use of the output created by the special version of
18568 allocation and deallocation routines that record call information. This
18569 allows to obtain accurate dynamic memory usage history at a minimal cost to
18570 the execution speed. Note however, that @code{gnatmem} is not supported on
18571 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
18572 Solaris and Windows NT/2000/XP (x86).
18574 @noindent
18575 The @code{gnatmem} command has the form
18577 @smallexample
18578 @c    $ gnatmem @ovar{switches} user_program
18579 @c Expanding @ovar macro inline (explanation in macro def comments)
18580       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18581 @end smallexample
18583 @noindent
18584 The program must have been linked with the instrumented version of the
18585 allocation and deallocation routines. This is done by linking with the
18586 @file{libgmem.a} library. For correct symbolic backtrace information,
18587 the user program should be compiled with debugging options
18588 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18590 @smallexample
18591 $ gnatmake -g my_program -largs -lgmem
18592 @end smallexample
18594 @noindent
18595 As library @file{libgmem.a} contains an alternate body for package
18596 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18597 when an executable is linked with library @file{libgmem.a}. It is then not
18598 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18600 @noindent
18601 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18602 This file contains information about all allocations and deallocations
18603 performed by the program. It is produced by the instrumented allocations and
18604 deallocations routines and will be used by @code{gnatmem}.
18606 In order to produce symbolic backtrace information for allocations and
18607 deallocations performed by the GNAT run-time library, you need to use a
18608 version of that library that has been compiled with the @option{-g} switch
18609 (see @ref{Rebuilding the GNAT Run-Time Library}).
18611 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18612 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18613 @option{-i} switch, gnatmem will assume that this file can be found in the
18614 current directory. For example, after you have executed @file{my_program},
18615 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18617 @smallexample
18618 $ gnatmem my_program
18619 @end smallexample
18621 @noindent
18622 This will produce the output with the following format:
18624 *************** debut cc
18625 @smallexample
18626 $ gnatmem my_program
18628 Global information
18629 ------------------
18630    Total number of allocations        :  45
18631    Total number of deallocations      :   6
18632    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18633    High Water Mark                    :  11.40 Kilobytes
18638 Allocation Root # 2
18639 -------------------
18640  Number of non freed allocations    :  11
18641  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18642  High Water Mark                    :   1.27 Kilobytes
18643  Backtrace                          :
18644    my_program.adb:23 my_program.alloc
18648 @end smallexample
18650 The first block of output gives general information. In this case, the
18651 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18652 Unchecked_Deallocation routine occurred.
18654 @noindent
18655 Subsequent paragraphs display  information on all allocation roots.
18656 An allocation root is a specific point in the execution of the program
18657 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18658 construct. This root is represented by an execution backtrace (or subprogram
18659 call stack). By default the backtrace depth for allocations roots is 1, so
18660 that a root corresponds exactly to a source location. The backtrace can
18661 be made deeper, to make the root more specific.
18663 @node Switches for gnatmem
18664 @subsection Switches for @code{gnatmem}
18666 @noindent
18667 @code{gnatmem} recognizes the following switches:
18669 @table @option
18671 @item -q
18672 @cindex @option{-q} (@code{gnatmem})
18673 Quiet. Gives the minimum output needed to identify the origin of the
18674 memory leaks. Omits statistical information.
18676 @item @var{N}
18677 @cindex @var{N} (@code{gnatmem})
18678 N is an integer literal (usually between 1 and 10) which controls the
18679 depth of the backtraces defining allocation root. The default value for
18680 N is 1. The deeper the backtrace, the more precise the localization of
18681 the root. Note that the total number of roots can depend on this
18682 parameter. This parameter must be specified @emph{before} the name of the
18683 executable to be analyzed, to avoid ambiguity.
18685 @item -b n
18686 @cindex @option{-b} (@code{gnatmem})
18687 This switch has the same effect as just depth parameter.
18689 @item -i @var{file}
18690 @cindex @option{-i} (@code{gnatmem})
18691 Do the @code{gnatmem} processing starting from @file{file}, rather than
18692 @file{gmem.out} in the current directory.
18694 @item -m n
18695 @cindex @option{-m} (@code{gnatmem})
18696 This switch causes @code{gnatmem} to mask the allocation roots that have less
18697 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18698 examine even the roots that didn't result in leaks.
18700 @item -s order
18701 @cindex @option{-s} (@code{gnatmem})
18702 This switch causes @code{gnatmem} to sort the allocation roots according to the
18703 specified order of sort criteria, each identified by a single letter. The
18704 currently supported criteria are @code{n, h, w} standing respectively for
18705 number of unfreed allocations, high watermark, and final watermark
18706 corresponding to a specific root. The default order is @code{nwh}.
18708 @end table
18710 @node Example of gnatmem Usage
18711 @subsection Example of @code{gnatmem} Usage
18713 @noindent
18714 The following example shows the use of @code{gnatmem}
18715 on a simple memory-leaking program.
18716 Suppose that we have the following Ada program:
18718 @smallexample @c ada
18719 @group
18720 @cartouche
18721 with Unchecked_Deallocation;
18722 procedure Test_Gm is
18724    type T is array (1..1000) of Integer;
18725    type Ptr is access T;
18726    procedure Free is new Unchecked_Deallocation (T, Ptr);
18727    A : Ptr;
18729    procedure My_Alloc is
18730    begin
18731       A := new T;
18732    end My_Alloc;
18734    procedure My_DeAlloc is
18735       B : Ptr := A;
18736    begin
18737       Free (B);
18738    end My_DeAlloc;
18740 begin
18741    My_Alloc;
18742    for I in 1 .. 5 loop
18743       for J in I .. 5 loop
18744          My_Alloc;
18745       end loop;
18746       My_Dealloc;
18747    end loop;
18748 end;
18749 @end cartouche
18750 @end group
18751 @end smallexample
18753 @noindent
18754 The program needs to be compiled with debugging option and linked with
18755 @code{gmem} library:
18757 @smallexample
18758 $ gnatmake -g test_gm -largs -lgmem
18759 @end smallexample
18761 @noindent
18762 Then we execute the program as usual:
18764 @smallexample
18765 $ test_gm
18766 @end smallexample
18768 @noindent
18769 Then @code{gnatmem} is invoked simply with
18770 @smallexample
18771 $ gnatmem test_gm
18772 @end smallexample
18774 @noindent
18775 which produces the following output (result may vary on different platforms):
18777 @smallexample
18778 Global information
18779 ------------------
18780    Total number of allocations        :  18
18781    Total number of deallocations      :   5
18782    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18783    High Water Mark                    :  56.90 Kilobytes
18785 Allocation Root # 1
18786 -------------------
18787  Number of non freed allocations    :  11
18788  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18789  High Water Mark                    :  46.88 Kilobytes
18790  Backtrace                          :
18791    test_gm.adb:11 test_gm.my_alloc
18793 Allocation Root # 2
18794 -------------------
18795  Number of non freed allocations    :   1
18796  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18797  High Water Mark                    :  10.02 Kilobytes
18798  Backtrace                          :
18799    s-secsta.adb:81 system.secondary_stack.ss_init
18801 Allocation Root # 3
18802 -------------------
18803  Number of non freed allocations    :   1
18804  Final Water Mark (non freed mem)   :  12 Bytes
18805  High Water Mark                    :  12 Bytes
18806  Backtrace                          :
18807    s-secsta.adb:181 system.secondary_stack.ss_init
18808 @end smallexample
18810 @noindent
18811 Note that the GNAT run time contains itself a certain number of
18812 allocations that have no  corresponding deallocation,
18813 as shown here for root #2 and root
18814 #3. This is a normal behavior when the number of non-freed allocations
18815 is one, it allocates dynamic data structures that the run time needs for
18816 the complete lifetime of the program. Note also that there is only one
18817 allocation root in the user program with a single line back trace:
18818 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18819 program shows that 'My_Alloc' is called at 2 different points in the
18820 source (line 21 and line 24). If those two allocation roots need to be
18821 distinguished, the backtrace depth parameter can be used:
18823 @smallexample
18824 $ gnatmem 3 test_gm
18825 @end smallexample
18827 @noindent
18828 which will give the following output:
18830 @smallexample
18831 Global information
18832 ------------------
18833    Total number of allocations        :  18
18834    Total number of deallocations      :   5
18835    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18836    High Water Mark                    :  56.90 Kilobytes
18838 Allocation Root # 1
18839 -------------------
18840  Number of non freed allocations    :  10
18841  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18842  High Water Mark                    :  42.97 Kilobytes
18843  Backtrace                          :
18844    test_gm.adb:11 test_gm.my_alloc
18845    test_gm.adb:24 test_gm
18846    b_test_gm.c:52 main
18848 Allocation Root # 2
18849 -------------------
18850  Number of non freed allocations    :   1
18851  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18852  High Water Mark                    :  10.02 Kilobytes
18853  Backtrace                          :
18854    s-secsta.adb:81  system.secondary_stack.ss_init
18855    s-secsta.adb:283 <system__secondary_stack___elabb>
18856    b_test_gm.c:33   adainit
18858 Allocation Root # 3
18859 -------------------
18860  Number of non freed allocations    :   1
18861  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18862  High Water Mark                    :   3.91 Kilobytes
18863  Backtrace                          :
18864    test_gm.adb:11 test_gm.my_alloc
18865    test_gm.adb:21 test_gm
18866    b_test_gm.c:52 main
18868 Allocation Root # 4
18869 -------------------
18870  Number of non freed allocations    :   1
18871  Final Water Mark (non freed mem)   :  12 Bytes
18872  High Water Mark                    :  12 Bytes
18873  Backtrace                          :
18874    s-secsta.adb:181 system.secondary_stack.ss_init
18875    s-secsta.adb:283 <system__secondary_stack___elabb>
18876    b_test_gm.c:33   adainit
18877 @end smallexample
18879 @noindent
18880 The allocation root #1 of the first example has been split in 2 roots #1
18881 and #3 thanks to the more precise associated backtrace.
18883 @end ifclear
18885 @node Stack Related Facilities
18886 @chapter Stack Related Facilities
18888 @noindent
18889 This chapter describes some useful tools associated with stack
18890 checking and analysis. In
18891 particular, it deals with dynamic and static stack usage measurements.
18893 @menu
18894 * Stack Overflow Checking::
18895 * Static Stack Usage Analysis::
18896 * Dynamic Stack Usage Analysis::
18897 @end menu
18899 @node Stack Overflow Checking
18900 @section Stack Overflow Checking
18901 @cindex Stack Overflow Checking
18902 @cindex -fstack-check
18904 @noindent
18905 For most operating systems, @command{gcc} does not perform stack overflow
18906 checking by default. This means that if the main environment task or
18907 some other task exceeds the available stack space, then unpredictable
18908 behavior will occur. Most native systems offer some level of protection by
18909 adding a guard page at the end of each task stack. This mechanism is usually
18910 not enough for dealing properly with stack overflow situations because
18911 a large local variable could ``jump'' above the guard page.
18912 Furthermore, when the
18913 guard page is hit, there may not be any space left on the stack for executing
18914 the exception propagation code. Enabling stack checking avoids
18915 such situations.
18917 To activate stack checking, compile all units with the gcc option
18918 @option{-fstack-check}. For example:
18920 @smallexample
18921 gcc -c -fstack-check package1.adb
18922 @end smallexample
18924 @noindent
18925 Units compiled with this option will generate extra instructions to check
18926 that any use of the stack (for procedure calls or for declaring local
18927 variables in declare blocks) does not exceed the available stack space.
18928 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18930 For declared tasks, the stack size is controlled by the size
18931 given in an applicable @code{Storage_Size} pragma or by the value specified
18932 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18933 the default size as defined in the GNAT runtime otherwise.
18935 For the environment task, the stack size depends on
18936 system defaults and is unknown to the compiler. Stack checking
18937 may still work correctly if a fixed
18938 size stack is allocated, but this cannot be guaranteed.
18939 @ifclear vms
18940 To ensure that a clean exception is signalled for stack
18941 overflow, set the environment variable
18942 @env{GNAT_STACK_LIMIT} to indicate the maximum
18943 stack area that can be used, as in:
18944 @cindex GNAT_STACK_LIMIT
18946 @smallexample
18947 SET GNAT_STACK_LIMIT 1600
18948 @end smallexample
18950 @noindent
18951 The limit is given in kilobytes, so the above declaration would
18952 set the stack limit of the environment task to 1.6 megabytes.
18953 Note that the only purpose of this usage is to limit the amount
18954 of stack used by the environment task. If it is necessary to
18955 increase the amount of stack for the environment task, then this
18956 is an operating systems issue, and must be addressed with the
18957 appropriate operating systems commands.
18958 @end ifclear
18959 @ifset vms
18960 To have a fixed size stack in the environment task, the stack must be put
18961 in the P0 address space and its size specified.  Use these switches to
18962 create a p0 image:
18964 @smallexample
18965 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
18966 @end smallexample
18968 @noindent
18969 The quotes are required to keep case.  The number after @samp{STACK=} is the
18970 size of the environmental task stack in pagelets (512 bytes).  In this example
18971 the stack size is about 2 megabytes.
18973 @noindent
18974 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
18975 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
18976 more details about the @option{/p0image} qualifier and the @option{stack}
18977 option.
18979 @noindent
18980 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
18981 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
18982 stack in kilobytes.  For example:
18984 @smallexample
18985 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
18986 @end smallexample
18987 @end ifset
18989 @node Static Stack Usage Analysis
18990 @section Static Stack Usage Analysis
18991 @cindex Static Stack Usage Analysis
18992 @cindex -fstack-usage
18994 @noindent
18995 A unit compiled with @option{-fstack-usage} will generate an extra file
18996 that specifies
18997 the maximum amount of stack used, on a per-function basis.
18998 The file has the same
18999 basename as the target object file with a @file{.su} extension.
19000 Each line of this file is made up of three fields:
19002 @itemize
19003 @item
19004 The name of the function.
19005 @item
19006 A number of bytes.
19007 @item
19008 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19009 @end itemize
19011 The second field corresponds to the size of the known part of the function
19012 frame.
19014 The qualifier @code{static} means that the function frame size
19015 is purely static.
19016 It usually means that all local variables have a static size.
19017 In this case, the second field is a reliable measure of the function stack
19018 utilization.
19020 The qualifier @code{dynamic} means that the function frame size is not static.
19021 It happens mainly when some local variables have a dynamic size. When this
19022 qualifier appears alone, the second field is not a reliable measure
19023 of the function stack analysis. When it is qualified with  @code{bounded}, it
19024 means that the second field is a reliable maximum of the function stack
19025 utilization.
19027 A unit compiled with @option{-Wstack-usage} will issue a warning for each
19028 subprogram whose stack usage might be larger than the specified amount of
19029 bytes.  The wording is in keeping with the qualifier documented above.
19031 @node Dynamic Stack Usage Analysis
19032 @section Dynamic Stack Usage Analysis
19034 @noindent
19035 It is possible to measure the maximum amount of stack used by a task, by
19036 adding a switch to @command{gnatbind}, as:
19038 @smallexample
19039 $ gnatbind -u0 file
19040 @end smallexample
19042 @noindent
19043 With this option, at each task termination, its stack usage is  output on
19044 @file{stderr}.
19045 It is not always convenient to output the stack usage when the program
19046 is still running. Hence, it is possible to delay this output until program
19047 termination. for a given number of tasks specified as the argument of the
19048 @option{-u} option. For instance:
19050 @smallexample
19051 $ gnatbind -u100 file
19052 @end smallexample
19054 @noindent
19055 will buffer the stack usage information of the first 100 tasks to terminate and
19056 output this info at program termination. Results are displayed in four
19057 columns:
19059 @noindent
19060 Index | Task Name | Stack Size | Stack Usage
19062 @noindent
19063 where:
19065 @table @emph
19066 @item Index
19067 is a number associated with each task.
19069 @item Task Name
19070 is the name of the task analyzed.
19072 @item Stack Size
19073 is the maximum size for the stack.
19075 @item Stack Usage
19076 is the measure done by the stack analyzer. In order to prevent overflow, the stack
19077 is not entirely analyzed, and it's not possible to know exactly how
19078 much has actually been used.
19080 @end table
19082 @noindent
19083 The environment task stack, e.g., the stack that contains the main unit, is
19084 only processed when the environment variable GNAT_STACK_LIMIT is set.
19086 @noindent
19087 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
19088 stack usage reports at run-time. See its body for the details.
19090 @c *********************************
19091 @c *            GNATCHECK          *
19092 @c *********************************
19093 @node Verifying Properties with gnatcheck
19094 @chapter Verifying Properties with @command{gnatcheck}
19095 @findex gnatcheck
19096 @cindex @command{gnatcheck}
19098 @noindent
19099 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19100 of Ada source files according to a given set of semantic rules.
19101 @cindex ASIS
19103 In order to check compliance with a given rule, @command{gnatcheck} has to
19104 semantically analyze the Ada sources.
19105 Therefore, checks can only be performed on
19106 legal Ada units. Moreover, when a unit depends semantically upon units located
19107 outside the current directory, the source search path has to be provided when
19108 calling @command{gnatcheck}, either through a specified project file or
19109 through @command{gnatcheck} switches.
19111 For full details, refer to @cite{GNATcheck Reference Manual} document.
19114 @c *********************************
19115 @node Creating Sample Bodies with gnatstub
19116 @chapter Creating Sample Bodies with @command{gnatstub}
19117 @findex gnatstub
19119 @noindent
19120 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
19121 for library unit declarations.
19123 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
19124 driver (see @ref{The GNAT Driver and Project Files}).
19126 To create a body stub, @command{gnatstub} has to compile the library
19127 unit declaration. Therefore, bodies can be created only for legal
19128 library units. Moreover, if a library unit depends semantically upon
19129 units located outside the current directory, you have to provide
19130 the source search path when calling @command{gnatstub}, see the description
19131 of @command{gnatstub} switches below.
19133 By default, all the program unit body stubs generated by @code{gnatstub}
19134 raise the predefined @code{Program_Error} exception, which will catch
19135 accidental calls of generated stubs. This behavior can be changed with
19136 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
19138 @menu
19139 * Running gnatstub::
19140 * Switches for gnatstub::
19141 @end menu
19143 @node Running gnatstub
19144 @section Running @command{gnatstub}
19146 @noindent
19147 @command{gnatstub} has a command-line interface of the form:
19149 @smallexample
19150 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
19151 @c Expanding @ovar macro inline (explanation in macro def comments)
19152 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19153 @end smallexample
19155 @noindent
19156 where
19157 @table @var
19158 @item filename
19159 is the name of the source file that contains a library unit declaration
19160 for which a body must be created. The file name may contain the path
19161 information.
19162 The file name does not have to follow the GNAT file name conventions. If the
19163 name
19164 does not follow GNAT file naming conventions, the name of the body file must
19165 be provided
19166 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19167 If the file name follows the GNAT file naming
19168 conventions and the name of the body file is not provided,
19169 @command{gnatstub}
19170 creates the name
19171 of the body file from the argument file name by replacing the @file{.ads}
19172 suffix
19173 with the @file{.adb} suffix.
19175 @item directory
19176 indicates the directory in which the body stub is to be placed (the default
19177 is the
19178 current directory)
19180 @item @samp{@var{gcc_switches}} is a list of switches for
19181 @command{gcc}. They will be passed on to all compiler invocations made by
19182 @command{gnatstub} to generate the ASIS trees. Here you can provide
19183 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19184 use the @option{-gnatec} switch to set the configuration file,
19185 use the @option{-gnat05} switch if sources should be compiled in
19186 Ada 2005 mode etc.
19188 @item switches
19189 is an optional sequence of switches as described in the next section
19190 @end table
19192 @node Switches for gnatstub
19193 @section Switches for @command{gnatstub}
19195 @table @option
19196 @c !sort!
19198 @item --version
19199 @cindex @option{--version} @command{gnatstub}
19200 Display Copyright and version, then exit disregarding all other options.
19202 @item --help
19203 @cindex @option{--help} @command{gnatstub}
19204 Display usage, then exit disregarding all other options.
19206 @item ^-f^/FULL^
19207 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19208 If the destination directory already contains a file with the name of the
19209 body file
19210 for the argument spec file, replace it with the generated body stub.
19212 @item ^-hs^/HEADER=SPEC^
19213 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19214 Put the comment header (i.e., all the comments preceding the
19215 compilation unit) from the source of the library unit declaration
19216 into the body stub.
19218 @item ^-hg^/HEADER=GENERAL^
19219 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19220 Put a sample comment header into the body stub.
19222 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
19223 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
19224 Use the content of the file as the comment header for a generated body stub.
19226 @ifclear vms
19227 @item -IDIR
19228 @cindex @option{-IDIR} (@command{gnatstub})
19229 @itemx -I-
19230 @cindex @option{-I-} (@command{gnatstub})
19231 @end ifclear
19232 @ifset vms
19233 @item /NOCURRENT_DIRECTORY
19234 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19235 @end ifset
19236 ^These switches have ^This switch has^ the same meaning as in calls to
19237 @command{gcc}.
19238 ^They define ^It defines ^ the source search path in the call to
19239 @command{gcc} issued
19240 by @command{gnatstub} to compile an argument source file.
19242 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19243 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19244 This switch has the same meaning as in calls to @command{gcc}.
19245 It defines the additional configuration file to be passed to the call to
19246 @command{gcc} issued
19247 by @command{gnatstub} to compile an argument source file.
19249 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19250 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19251 (@var{n} is a non-negative integer). Set the maximum line length that is
19252 allowed in a source file. The default is 79. The maximum value that can be
19253 specified is 32767. Note that in the special case of configuration
19254 pragma files, the maximum is always 32767 regardless of whether or
19255 not this switch appears.
19257 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19258 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19259 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19260 the generated body sample to @var{n}.
19261 The default indentation is 3.
19263 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19264 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19265 Order local bodies alphabetically. (By default local bodies are ordered
19266 in the same way as the corresponding local specs in the argument spec file.)
19268 @item ^-i^/INDENTATION=^@var{n}
19269 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19270 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19272 @item ^-k^/TREE_FILE=SAVE^
19273 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19274 Do not remove the tree file (i.e., the snapshot of the compiler internal
19275 structures used by @command{gnatstub}) after creating the body stub.
19277 @item ^-l^/LINE_LENGTH=^@var{n}
19278 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19279 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19281 @item ^--no-exception^/NO_EXCEPTION^
19282 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19283 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19284 This is not always possible for function stubs.
19286 @item ^--no-local-header^/NO_LOCAL_HEADER^
19287 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19288 Do not place local comment header with unit name before body stub for a
19289 unit.
19291 @item ^-o ^/BODY=^@var{body-name}
19292 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19293 Body file name.  This should be set if the argument file name does not
19294 follow
19295 the GNAT file naming
19296 conventions. If this switch is omitted the default name for the body will be
19297 obtained
19298 from the argument file name according to the GNAT file naming conventions.
19300 @item ^-q^/QUIET^
19301 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19302 Quiet mode: do not generate a confirmation when a body is
19303 successfully created, and do not generate a message when a body is not
19304 required for an
19305 argument unit.
19307 @item ^-r^/TREE_FILE=REUSE^
19308 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19309 Reuse the tree file (if it exists) instead of creating it.  Instead of
19310 creating the tree file for the library unit declaration, @command{gnatstub}
19311 tries to find it in the current directory and use it for creating
19312 a body. If the tree file is not found, no body is created. This option
19313 also implies @option{^-k^/SAVE^}, whether or not
19314 the latter is set explicitly.
19316 @item ^-t^/TREE_FILE=OVERWRITE^
19317 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19318 Overwrite the existing tree file.  If the current directory already
19319 contains the file which, according to the GNAT file naming rules should
19320 be considered as a tree file for the argument source file,
19321 @command{gnatstub}
19322 will refuse to create the tree file needed to create a sample body
19323 unless this option is set.
19325 @item ^-v^/VERBOSE^
19326 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19327 Verbose mode: generate version information.
19329 @end table
19331 @c *********************************
19332 @node Creating Unit Tests with gnattest
19333 @chapter Creating Unit Tests with @command{gnattest}
19334 @findex gnattest
19336 @noindent
19337 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19338 as well as a test driver infrastructure (harness). @command{gnattest} creates
19339 a skeleton for each visible subprogram in the packages under consideration when
19340 they do not exist already.
19342 In order to process source files from a project, @command{gnattest} has to
19343 semantically analyze the sources. Therefore, test skeletons can only be
19344 generated for legal Ada units. If a unit is dependent on other units,
19345 those units should be among the source files of the project or of other projects
19346 imported by this one.
19348 Generated skeletons and harnesses are based on the AUnit testing framework.
19349 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19350 for Java or CppUnit for C++. While it is advised that gnattest users read
19351 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19352 For correct operation of @command{gnattest}, AUnit should be installed and
19353 aunit.gpr must be on the project path. This happens automatically when Aunit
19354 is installed at its default location.
19355 @menu
19356 * Running gnattest::
19357 * Switches for gnattest::
19358 * Project Attributes for gnattest::
19359 * Simple Example::
19360 * Setting Up and Tearing Down the Testing Environment::
19361 * Regenerating Tests::
19362 * Default Test Behavior::
19363 * Testing Primitive Operations of Tagged Types::
19364 * Testing Inheritance::
19365 * Tagged Types Substitutability Testing::
19366 * Testing with Contracts::
19367 * Additional Tests::
19368 @ifclear vms
19369 * Support for other platforms/run-times::
19370 @end ifclear
19371 * Current Limitations::
19372 @end menu
19374 @node Running gnattest
19375 @section Running @command{gnattest}
19377 @noindent
19378 @command{gnattest} has a command-line interface of the form
19380 @smallexample
19381 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19382 @c Expanding @ovar macro inline (explanation in macro def comments)
19383 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19384 @end smallexample
19386 @noindent
19387 where
19388 @table @var
19390 @item -Pprojname
19391 specifies the project defining the location of source files. When no
19392 file names are provided on the command line, all sources in the project
19393 are used as input. This switch is required.
19395 @item filename
19396 is the name of the source file containing the library unit package declaration
19397 for which a test package will be created. The file name may be given with a
19398 path.
19400 @item @samp{@var{gcc_switches}}
19401 is a list of switches for
19402 @command{gcc}. These switches will be passed on to all compiler invocations
19403 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19404 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19405 use the @option{-gnatec} switch to set the configuration file,
19406 use the @option{-gnat05} switch if sources should be compiled in
19407 Ada 2005 mode, etc.
19409 @item switches
19410 is an optional sequence of switches as described in the next section.
19412 @end table
19414 @command{gnattest} results can be found in two different places.
19416 @itemize @bullet
19417 @item automatic harness:
19418 the harness code, which is located by default in "gnattest/harness" directory
19419 that is created in the object directory of corresponding project file. All of
19420 this code is generated completely automatically and can be destroyed and
19421 regenerated at will. It is not recommended to modify this code manually, since
19422 it could easily be overridden by mistake. The entry point in the harness code is
19423 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19424 using a command such as:
19426 @smallexample
19427 gnatmake -P<harness-dir>/test_driver
19428 test_runner
19429 @end smallexample
19431 Note that you might need to specify the necessary values of scenario variables
19432 when you are not using the AUnit defaults.
19434 @item actual unit test skeletons:
19435 a test skeleton for each visible subprogram is created in a separate file, if it
19436 doesn't exist already. By default, those separate test files are located in a
19437 "gnattest/tests" directory that is created in the object directory of
19438 corresponding project file. For example, if a source file my_unit.ads in
19439 directory src contains a visible subprogram Proc, then the corresponding unit
19440 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19441 <code> is a signature encoding used to differentiate test names in case of
19442 overloading.
19444 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19445 this will cause a name conflict with the generated test package.
19446 @end itemize
19448 @node Switches for gnattest
19449 @section Switches for @command{gnattest}
19451 @table @option
19452 @c !sort!
19454 @item --harness-only
19455 @cindex @option{--harness-only} (@command{gnattest})
19456 When this option is given, @command{gnattest} creates a harness for all
19457 sources, treating them as test packages.
19459 @item --additional-tests=@var{projname}
19460 @cindex @option{--additional-tests} (@command{gnattest})
19461 Sources described in @var{projname} are considered potential additional
19462 manual tests to be added to the test suite.
19464 @item -r
19465 @cindex @option{-r} (@command{gnattest})
19466 Recursively consider all sources from all projects.
19468 @item -X@var{name=value}
19469 @cindex @option{-X} (@command{gnattest})
19470 Indicate that external variable @var{name} has the value @var{value}.
19472 @item -q
19473 @cindex @option{-q} (@command{gnattest})
19474 Suppresses noncritical output messages.
19476 @item -v
19477 @cindex @option{-v} (@command{gnattest})
19478 Verbose mode: generates version information.
19480 @item --validate-type-extensions
19481 @cindex @option{--validate-type-extensions} (@command{gnattest})
19482 Enables substitution check: run all tests from all parents in order
19483 to check substitutability.
19485 @item --skeleton-default=@var{val}
19486 @cindex @option{--skeleton-default} (@command{gnattest})
19487 Specifies the default behavior of generated skeletons. @var{val} can be either
19488 "fail" or "pass", "fail" being the default.
19490 @item --tests-root=@var{dirname}
19491 @cindex @option{--tests-root} (@command{gnattest})
19492 The directory hierarchy of tested sources is recreated in the @var{dirname}
19493 directory, and test packages are placed in corresponding directories.
19494 If the @var{dirname} is a relative path, it is considered relative to the object
19495 directory of the project file. When all sources from all projects are taken
19496 recursively from all projects, directory hierarchies of tested sources are
19497 recreated for each project in their object directories and test packages are
19498 placed accordingly.
19500 @item --subdir=@var{dirname}
19501 @cindex @option{--subdir} (@command{gnattest})
19502 Test packages are placed in subdirectories.
19504 @item --tests-dir=@var{dirname}
19505 @cindex @option{--tests-dir} (@command{gnattest})
19506 All test packages are placed in the @var{dirname} directory.
19507 If the @var{dirname} is a relative path, it is considered relative to the object
19508 directory of the project file. When all sources from all projects are taken
19509 recursively from all projects, @var{dirname} directories are created for each
19510 project in their object directories and test packages are placed accordingly.
19512 @item --harness-dir=@var{dirname}
19513 @cindex @option{--harness-dir} (@command{gnattest})
19514 specifies the directory that will hold the harness packages and project file
19515 for the test driver. If the @var{dirname} is a relative path, it is considered
19516 relative to the object directory of the project file.
19518 @item --separates
19519 @cindex @option{--separates} (@command{gnattest})
19520 Bodies of all test routines are generated as separates. Note that this mode is
19521 kept for compatibility reasons only and it is not advised to use it due to
19522 possible problems with hash in names of test skeletons when using an
19523 inconsistent casing. Separate test skeletons can be incorporated to monolith
19524 test package with improved hash being used by using @option{--transition}
19525 switch.
19528 @item --transition
19529 @cindex @option{--transition} (@command{gnattest})
19530 This allows transition from separate test routines to monolith test packages.
19531 All matching test routines are overwritten with contents of corresponding
19532 separates. Note that if separate test routines had any manually added with
19533 clauses they will be moved to the test package body as is and have to be moved
19534 by hand.
19536 @end table
19538 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19539 mutually exclusive.
19541 @node Project Attributes for gnattest
19542 @section Project Attributes for @command{gnattest}
19544 @noindent
19546 Most of the command-line options can also be passed to the tool by adding
19547 special attributes to the project file. Those attributes should be put in
19548 package gnattest. Here is the list of attributes:
19550 @itemize @bullet
19552 @item Tests_Root
19553 is used to select the same output mode as with the --tests-root option.
19554 This attribute cannot be used together with Subdir or Tests_Dir.
19556 @item Subdir
19557 is used to select the same output mode as with the --subdir option.
19558 This attribute cannot be used together with Tests_Root or Tests_Dir.
19560 @item Tests_Dir
19561 is used to select the same output mode as with the --tests-dir option.
19562 This attribute cannot be used together with Subdir or Tests_Root.
19564 @item Harness_Dir
19565 is used to specify the directory in which to place harness packages and project
19566 file for the test driver, otherwise specified by --harness-dir.
19568 @item Additional_Tests
19569 is used to specify the project file, otherwise given by
19570 --additional-tests switch.
19572 @item Skeletons_Default
19573 is used to specify the default behaviour of test skeletons, otherwise
19574 specified by --skeleton-default option. The value of this attribute
19575 should be either "pass" or "fail".
19577 @end itemize
19579 Each of those attributes can be overridden from the command line if needed.
19580 Other @command{gnattest} switches can also be passed via the project
19581 file as an attribute list called GNATtest_Switches.
19583 @node Simple Example
19584 @section Simple Example
19586 @noindent
19588 Let's take a very simple example using the first @command{gnattest} example
19589 located in:
19591 @smallexample
19592 <install_prefix>/share/examples/gnattest/simple
19593 @end smallexample
19595 This project contains a simple package containing one subprogram. By running gnattest:
19597 @smallexample
19598 $ gnattest --harness-dir=driver -Psimple.gpr
19599 @end smallexample
19601 a test driver is created in directory "driver". It can be compiled and run:
19603 @smallexample
19604 $ cd obj/driver
19605 $ gnatmake -Ptest_driver
19606 $ test_runner
19607 @end smallexample
19609 One failed test with diagnosis "test not implemented" is reported.
19610 Since no special output option was specified, the test package Simple.Tests
19611 is located in:
19613 @smallexample
19614 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19615 @end smallexample
19617 For each package containing visible subprograms, a child test package is
19618 generated. It contains one test routine per tested subprogram. Each
19619 declaration of a test subprogram has a comment specifying which tested
19620 subprogram it corresponds to. Bodies of test routines are placed in test package
19621 bodies and are surrounded by special comment sections. Those comment sections
19622 should not be removed or modified in order for gnattest to be able to regenerate
19623 test packages and keep already written tests in place.
19624 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19625 a single statement: a call to procedure Assert. It has two arguments:
19626 the Boolean expression we want to check and the diagnosis message to display if
19627 the condition is false.
19629 That is where actual testing code should be written after a proper setup.
19630 An actual check can be performed by replacing the Assert call with:
19632 @smallexample @c ada
19633 Assert (Inc (1) = 2, "wrong incrementation");
19634 @end smallexample
19636 After recompiling and running the test driver, one successfully passed test
19637 is reported.
19639 @node Setting Up and Tearing Down the Testing Environment
19640 @section Setting Up and Tearing Down the Testing Environment
19642 @noindent
19644 Besides test routines themselves, each test package has a parent package
19645 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19646 overwritten by the tool. Set_Up is called before each test routine of the
19647 package and Tear_Down is called after each test routine. Those two procedures
19648 can be used to perform necessary initialization and finalization,
19649 memory allocation, etc. Test type declared in Test_Data package is parent type
19650 for the test type of test package and can have user-defined components whose
19651 values can be set by Set_Up routine and used in test routines afterwards.
19653 @node Regenerating Tests
19654 @section Regenerating Tests
19656 @noindent
19658 Bodies of test routines and test_data packages are never overridden after they
19659 have been created once. As long as the name of the subprogram, full expanded Ada
19660 names, and the order of its parameters is the same, and comment sections are
19661 intact the old test routine will fit in its place and no test skeleton will be
19662 generated for the subprogram.
19664 This can be demonstrated with the previous example. By uncommenting declaration
19665 and body of function Dec in simple.ads and simple.adb, running
19666 @command{gnattest} on the project, and then running the test driver:
19668 @smallexample
19669 gnattest --harness-dir=driver -Psimple.gpr
19670 cd obj/driver
19671 gnatmake -Ptest_driver
19672 test_runner
19673 @end smallexample
19675 the old test is not replaced with a stub, nor is it lost, but a new test
19676 skeleton is created for function Dec.
19678 The only way of regenerating tests skeletons is to remove the previously created
19679 tests together with corresponding comment sections.
19681 @node Default Test Behavior
19682 @section Default Test Behavior
19684 @noindent
19686 The generated test driver can treat unimplemented tests in two ways:
19687 either count them all as failed (this is useful to see which tests are still
19688 left to implement) or as passed (to sort out unimplemented ones from those
19689 actually failing).
19691 The test driver accepts a switch to specify this behavior:
19692 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19693 @command{gnattest}).
19695 The default behavior of the test driver is set with the same switch
19696 as passed to gnattest when generating the test driver.
19698 Passing it to the driver generated on the first example:
19700 @smallexample
19701 test_runner --skeleton-default=pass
19702 @end smallexample
19704 makes both tests pass, even the unimplemented one.
19706 @node Testing Primitive Operations of Tagged Types
19707 @section Testing Primitive Operations of Tagged Types
19709 @noindent
19711 Creation of test skeletons for primitive operations of tagged types entails
19712 a number of features. Test routines for all primitives of a given tagged type
19713 are placed in a separate child package named according to the tagged type. For
19714 example, if you have tagged type T in package P, all tests for primitives
19715 of T will be in P.T_Test_Data.T_Tests.
19717 Consider running gnattest on the second example (note: actual tests for this
19718 example already exist, so there's no need to worry if the tool reports that
19719 no new stubs were generated):
19721 @smallexample
19722 cd <install_prefix>/share/examples/gnattest/tagged_rec
19723 gnattest --harness-dir=driver -Ptagged_rec.gpr
19724 @end smallexample
19726 Taking a closer look at the test type declared in the test package
19727 Speed1.Controller_Test_Data is necessary. It is declared in:
19729 @smallexample
19730 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19731 @end smallexample
19733 Test types are direct or indirect descendants of
19734 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19735 subprograms, the user doesn't need to be concerned with them. However,
19736 when generating test packages for primitive operations, there are some things
19737 the user needs to know.
19739 Type Test_Controller has components that allow assignment of various
19740 derivations of type Controller. And if you look at the specification of
19741 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19742 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19743 Thus, test types mirror the hierarchy of tested types.
19745 The Set_Up procedure of Test_Data package corresponding to a test package
19746 of primitive operations of type T assigns to Fixture a reference to an
19747 object of that exact type T. Notice, however, that if the tagged type has
19748 discriminants, the Set_Up only has a commented template for setting
19749 up the fixture, since filling the discriminant with actual value is up
19750 to the user.
19752 The knowledge of the structure of test types allows additional testing
19753 without additional effort. Those possibilities are described below.
19755 @node Testing Inheritance
19756 @section Testing Inheritance
19758 @noindent
19760 Since the test type hierarchy mimics the hierarchy of tested types, the
19761 inheritance of tests takes place. An example of such inheritance can be
19762 seen by running the test driver generated for the second example. As previously
19763 mentioned, actual tests are already written for this example.
19765 @smallexample
19766 cd obj/driver
19767 gnatmake -Ptest_driver
19768 test_runner
19769 @end smallexample
19771 There are 6 passed tests while there are only 5 testable subprograms. The test
19772 routine for function Speed has been inherited and run against objects of the
19773 derived type.
19775 @node Tagged Types Substitutability Testing
19776 @section Tagged Types Substitutability Testing
19778 @noindent
19780 Tagged Types Substitutability Testing is a way of verifying the global type
19781 consistency by testing. Global type consistency is a principle stating that if
19782 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19783 then objects of type T may be replaced with objects of type S (that is,
19784 objects of type S may be substituted for objects of type T), without
19785 altering any of the desirable properties of the program. When the properties
19786 of the program are expressed in the form of subprogram preconditions and
19787 postconditions (let's call them pre and post), the principle is formulated as
19788 relations between the pre and post of primitive operations and the pre and post
19789 of their derived operations. The pre of a derived operation should not be
19790 stronger than the original pre, and the post of the derived operation should
19791 not be weaker than the original post. Those relations ensure that verifying if
19792 a dispatching call is safe can be done just by using the pre and post of the
19793 root operation.
19795 Verifying global type consistency by testing consists of running all the unit
19796 tests associated with the primitives of a given tagged type with objects of its
19797 derived types.
19799 In the example used in the previous section, there was clearly a violation of
19800 type consistency. The overriding primitive Adjust_Speed in package Speed2
19801 removes the functionality of the overridden primitive and thus doesn't respect
19802 the consistency principle.
19803 Gnattest has a special option to run overridden parent tests against objects
19804 of the type which have overriding primitives:
19806 @smallexample
19807 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19808 cd obj/driver
19809 gnatmake -Ptest_driver
19810 test_runner
19811 @end smallexample
19813 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19814 against objects of the derived type.
19816 Non-overridden tests are already inherited for derived test types, so the
19817 --validate-type-extensions enables the application of overriden tests to objects
19818 of derived types.
19820 @node Testing with Contracts
19821 @section Testing with Contracts
19823 @noindent
19825 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19826 as well as corresponding aspects.
19827 Test routines are generated, one per each Test_Case associated with a tested
19828 subprogram. Those test routines have special wrappers for tested functions
19829 that have composition of pre- and postcondition of the subprogram with
19830 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19831 either count for Nominal mode or do not count for Robustness mode).
19833 The third example demonstrates how this works:
19835 @smallexample
19836 cd <install_prefix>/share/examples/gnattest/contracts
19837 gnattest --harness-dir=driver -Pcontracts.gpr
19838 @end smallexample
19840 Putting actual checks within the range of the contract does not cause any
19841 error reports. For example, for the test routine which corresponds to
19842 test case 1:
19844 @smallexample @c ada
19845 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19846 @end smallexample
19848 and for the test routine corresponding to test case 2:
19850 @smallexample @c ada
19851 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19852 @end smallexample
19854 are acceptable:
19856 @smallexample
19857 cd obj/driver
19858 gnatmake -Ptest_driver
19859 test_runner
19860 @end smallexample
19862 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19863 a precondition violation for test case one. Also, by using any otherwise
19864 correct but positive pair of numbers in the second test routine, you can also
19865 get a precondition violation. Postconditions are checked and reported
19866 the same way.
19868 @node Additional Tests
19869 @section Additional Tests
19871 @noindent
19872 @command{gnattest} can add user-written tests to the main suite of the test
19873 driver. @command{gnattest} traverses the given packages and searches for test
19874 routines. All procedures with a single in out parameter of a type which is
19875 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19876 specifications are added to the suites and are then executed by the test driver.
19877 (Set_Up and Tear_Down are filtered out.)
19879 An example illustrates two ways of creating test harnesses for user-written
19880 tests. Directory additional_tests contains an AUnit-based test driver written
19881 by hand.
19883 @smallexample
19884 <install_prefix>/share/examples/gnattest/additional_tests/
19885 @end smallexample
19887 To create a test driver for already-written tests, use the --harness-only
19888 option:
19890 @smallexample
19891 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19892   --harness-only
19893 gnatmake -Pharness_only/test_driver.gpr
19894 harness_only/test_runner
19895 @end smallexample
19897 Additional tests can also be executed together with generated tests:
19899 @smallexample
19900 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19901   --harness-dir=mixing
19902 gnatmake -Pmixing/test_driver.gpr
19903 mixing/test_runner
19904 @end smallexample
19906 @ifclear vms
19907 @node Support for other platforms/run-times
19908 @section Support for other platforms/run-times
19910 @noindent
19911 @command{gnattest} can be used to generate the test harness for platforms
19912 and run-time libraries others than the default native target with the
19913 default full run-time. For example, when using a limited run-time library
19914 such as Zero FootPrint (ZFP), a simplified harness is generated.
19916 Two variables are used to tell the underlying AUnit framework how to generate
19917 the test harness: @code{PLATFORM}, which identifies the target, and
19918 @code{RUNTIME}, used to determine the run-time library for which the harness
19919 is generated. Corresponding prefix should also be used when calling
19920 @command{gnattest} for non-native targets. For example, the following options
19921 are used to generate the AUnit test harness for a PowerPC ELF target using
19922 the ZFP run-time library:
19924 @smallexample
19925 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19926 @end smallexample
19927 @end ifclear
19929 @node Current Limitations
19930 @section Current Limitations
19932 @noindent
19934 The tool currently does not support following features:
19936 @itemize @bullet
19937 @item generic tests for generic packages and package instantiations
19938 @item tests for protected subprograms and entries
19940 @end itemize
19942 @c *********************************
19943 @node Performing Dimensionality Analysis in GNAT
19944 @chapter Performing Dimensionality Analysis in GNAT
19945 @noindent
19946 The GNAT compiler now supports dimensionality checking. The user can
19947 specify physical units for objects, and the compiler will verify that uses
19948 of these objects are compatible with their dimensions, in a fashion that is
19949 familiar to engineering practice. The dimensions of algebraic expressions
19950 (including powers with static exponents) are computed from their consistuents.
19952 This feature depends on Ada 2012 aspect specifications, and is available from
19953 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
19954 you to define a system of units; the aspect Dimension then allows the user
19955 to declare dimensioned quantities within a given system.
19957 The major advantage of this model is that it does not require the declaration of
19958 multiple operators for all possible combinations of types: it is only necessary
19959 to use the proper subtypes in object declarations.
19961 The simplest way to impose dimensionality checking on a computation is to make
19962 use of the package System.Dim.Mks, which is part of the GNAT library. This
19963 package defines a floating-point type MKS_Type, for which a sequence of
19964 dimension names are specified, together with their conventional abbreviations.
19965 The following should be read together with the full specification of the
19966 package, in file s-dimmks.ads.
19968 @smallexample @c ada
19969    type Mks_Type is new Long_Long_Float
19970      with
19971       Dimension_System => (
19972         (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
19973         (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
19974         (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
19975         (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
19976         (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
19977         (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
19978         (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
19979 @end smallexample
19981 @noindent
19982 The package then defines a series of subtypes that correspond to these
19983 conventional units. For example:
19984 @smallexample @c ada
19985    subtype Length is Mks_Type
19986      with
19987       Dimension => (Symbol => 'm', Meter  => 1, others => 0);
19988 @end smallexample
19989 @noindent
19990 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
19991 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
19992 the SI system).
19994 The package also defines conventional names for values of each unit, for
19995 example:
19997 @smallexample @c ada
19998    m   : constant Length           := 1.0;
19999    kg  : constant Mass             := 1.0;
20000    s   : constant Time             := 1.0;
20001    A   : constant Electric_Current := 1.0;
20002 @end smallexample
20004 @noindent
20005 as well as useful multiples of these units:
20007 @smallexample @c ada
20008    cm  : constant Length := 1.0E-02;
20009    g   : constant Mass   := 1.0E-03;
20010    min : constant Time   := 60.0;
20011    day : constant TIme   := 60.0 * 24.0 * min;
20012   ...
20013 @end smallexample
20015 @noindent
20016 Using this package, you can then define a derived unit by
20017 providing the aspect that
20018 specifies its dimensions within the MKS system, as well as the string to
20019 be used for output of a value of that unit:
20021 @smallexample @c ada
20022   subtype Acceleration is Mks_Type
20023     with Dimension => ("m/sec^^^2",
20024                        Meter => 1,
20025                        Second => -2,
20026                        others => 0);
20027 @end smallexample
20029 @noindent
20030 Here is a complete example of use:
20032 @smallexample @c ada
20033 with System.Dim.MKS; use System.Dim.Mks;
20034 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
20035 with Text_IO; use Text_IO;
20036 procedure Free_Fall is
20037   subtype Acceleration is Mks_Type
20038     with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
20039   G : constant acceleration := 9.81 * m / (s ** 2);
20040   T : Time := 10.0*s;
20041   Distance : Length;
20042 begin
20043   Put ("Gravitational constant: ");
20044   Put (G, Aft => 2, Exp => 0); Put_Line ("");
20045   Distance := 0.5 * G * T ** 2;
20046   Put ("distance travelled in 10 seconds of free fall ");
20047   Put (Distance, Aft => 2, Exp => 0);
20048   Put_Line ("");
20049 end Free_Fall;
20050 @end smallexample
20052 @noindent
20053 Execution of this program yields:
20054 @smallexample
20055 Gravitational constant:  9.81 m/sec^^^2
20056 distance travelled in 10 seconds of free fall 490.50 m
20057 @end smallexample
20059 @noindent
20060 However, incorrect assignments such as:
20062 @smallexample @c ada
20063    Distance := 5.0;
20064    Distance := 5.0 * kg:
20065 @end smallexample
20067 @noindent
20068 are rejected with the following diagnoses:
20070 @smallexample
20071    Distance := 5.0;
20072       >>> dimensions mismatch in assignment
20073       >>> left-hand side has dimension [L]
20074       >>> right-hand side is dimensionless
20076    Distance := 5.0 * kg:
20077       >>> dimensions mismatch in assignment
20078       >>> left-hand side has dimension [L]
20079       >>> right-hand side has dimension [M]
20080 @end smallexample
20082 @noindent
20083 The dimensions of an expression are properly displayed, even if there is
20084 no explicit subtype for it. If we add to the program:
20086 @smallexample @c ada
20087       Put ("Final velocity: ");
20088       Put (G * T, Aft =>2, Exp =>0);
20089       Put_Line ("");
20090 @end smallexample
20092 @noindent
20093 then the output includes:
20094 @smallexample
20095      Final velocity: 98.10 m.s**(-1)
20096 @end smallexample
20098 @c *********************************
20099 @node Generating Ada Bindings for C and C++ headers
20100 @chapter Generating Ada Bindings for C and C++ headers
20101 @findex binding
20103 @noindent
20104 GNAT now comes with a binding generator for C and C++ headers which is
20105 intended to do 95% of the tedious work of generating Ada specs from C
20106 or C++ header files.
20108 Note that this capability is not intended to generate 100% correct Ada specs,
20109 and will is some cases require manual adjustments, although it can often
20110 be used out of the box in practice.
20112 Some of the known limitations include:
20114 @itemize @bullet
20115 @item only very simple character constant macros are translated into Ada
20116 constants. Function macros (macros with arguments) are partially translated
20117 as comments, to be completed manually if needed.
20118 @item some extensions (e.g. vector types) are not supported
20119 @item pointers to pointers or complex structures are mapped to System.Address
20120 @item identifiers with identical name (except casing) will generate compilation
20121       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
20122 @end itemize
20124 The code generated is using the Ada 2005 syntax, which makes it
20125 easier to interface with other languages than previous versions of Ada.
20127 @menu
20128 * Running the binding generator::
20129 * Generating bindings for C++ headers::
20130 * Switches::
20131 @end menu
20133 @node Running the binding generator
20134 @section Running the binding generator
20136 @noindent
20137 The binding generator is part of the @command{gcc} compiler and can be
20138 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20139 spec files for the header files specified on the command line, and all
20140 header files needed by these files transitively. For example:
20142 @smallexample
20143 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
20144 $ gcc -c -gnat05 *.ads
20145 @end smallexample
20147 will generate, under GNU/Linux, the following files: @file{time_h.ads},
20148 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20149 correspond to the files @file{/usr/include/time.h},
20150 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20151 mode these Ada specs.
20153 The @code{-C} switch tells @command{gcc} to extract comments from headers,
20154 and will attempt to generate corresponding Ada comments.
20156 If you want to generate a single Ada file and not the transitive closure, you
20157 can use instead the @option{-fdump-ada-spec-slim} switch.
20159 You can optionally specify a parent unit, of which all generated units will
20160 be children, using @code{-fada-spec-parent=}@var{unit}.
20162 Note that we recommend when possible to use the @command{g++} driver to
20163 generate bindings, even for most C headers, since this will in general
20164 generate better Ada specs. For generating bindings for C++ headers, it is
20165 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20166 is equivalent in this case. If @command{g++} cannot work on your C headers
20167 because of incompatibilities between C and C++, then you can fallback to
20168 @command{gcc} instead.
20170 For an example of better bindings generated from the C++ front-end,
20171 the name of the parameters (when available) are actually ignored by the C
20172 front-end. Consider the following C header:
20174 @smallexample
20175 extern void foo (int variable);
20176 @end smallexample
20178 with the C front-end, @code{variable} is ignored, and the above is handled as:
20180 @smallexample
20181 extern void foo (int);
20182 @end smallexample
20184 generating a generic:
20186 @smallexample
20187 procedure foo (param1 : int);
20188 @end smallexample
20190 with the C++ front-end, the name is available, and we generate:
20192 @smallexample
20193 procedure foo (variable : int);
20194 @end smallexample
20196 In some cases, the generated bindings will be more complete or more meaningful
20197 when defining some macros, which you can do via the @option{-D} switch. This
20198 is for example the case with @file{Xlib.h} under GNU/Linux:
20200 @smallexample
20201 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20202 @end smallexample
20204 The above will generate more complete bindings than a straight call without
20205 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20207 In other cases, it is not possible to parse a header file in a stand-alone
20208 manner, because other include files need to be included first. In this
20209 case, the solution is to create a small header file including the needed
20210 @code{#include} and possible @code{#define} directives. For example, to
20211 generate Ada bindings for @file{readline/readline.h}, you need to first
20212 include @file{stdio.h}, so you can create a file with the following two
20213 lines in e.g. @file{readline1.h}:
20215 @smallexample
20216 #include <stdio.h>
20217 #include <readline/readline.h>
20218 @end smallexample
20220 and then generate Ada bindings from this file:
20222 @smallexample
20223 $ g++ -c -fdump-ada-spec readline1.h
20224 @end smallexample
20226 @node Generating bindings for C++ headers
20227 @section Generating bindings for C++ headers
20229 @noindent
20230 Generating bindings for C++ headers is done using the same options, always
20231 with the @command{g++} compiler.
20233 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20234 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20235 multiple inheritance of abstract classes will be mapped to Ada interfaces
20236 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20237 information on interfacing to C++).
20239 For example, given the following C++ header file:
20241 @smallexample
20242 @group
20243 @cartouche
20244 class Carnivore @{
20245 public:
20246    virtual int Number_Of_Teeth () = 0;
20249 class Domestic @{
20250 public:
20251    virtual void Set_Owner (char* Name) = 0;
20254 class Animal @{
20255 public:
20256   int Age_Count;
20257   virtual void Set_Age (int New_Age);
20260 class Dog : Animal, Carnivore, Domestic @{
20261  public:
20262   int  Tooth_Count;
20263   char *Owner;
20265   virtual int  Number_Of_Teeth ();
20266   virtual void Set_Owner (char* Name);
20268   Dog();
20270 @end cartouche
20271 @end group
20272 @end smallexample
20274 The corresponding Ada code is generated:
20276 @smallexample @c ada
20277 @group
20278 @cartouche
20279   package Class_Carnivore is
20280     type Carnivore is limited interface;
20281     pragma Import (CPP, Carnivore);
20283     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20284   end;
20285   use Class_Carnivore;
20287   package Class_Domestic is
20288     type Domestic is limited interface;
20289     pragma Import (CPP, Domestic);
20291     procedure Set_Owner
20292       (this : access Domestic;
20293        Name : Interfaces.C.Strings.chars_ptr) is abstract;
20294   end;
20295   use Class_Domestic;
20297   package Class_Animal is
20298     type Animal is tagged limited record
20299       Age_Count : aliased int;
20300     end record;
20301     pragma Import (CPP, Animal);
20303     procedure Set_Age (this : access Animal; New_Age : int);
20304     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20305   end;
20306   use Class_Animal;
20308   package Class_Dog is
20309     type Dog is new Animal and Carnivore and Domestic with record
20310       Tooth_Count : aliased int;
20311       Owner : Interfaces.C.Strings.chars_ptr;
20312     end record;
20313     pragma Import (CPP, Dog);
20315     function Number_Of_Teeth (this : access Dog) return int;
20316     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20318     procedure Set_Owner
20319       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20320     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20322     function New_Dog return Dog;
20323     pragma CPP_Constructor (New_Dog);
20324     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20325   end;
20326   use Class_Dog;
20327 @end cartouche
20328 @end group
20329 @end smallexample
20331 @node Switches
20332 @section Switches
20334 @table @option
20335 @item -fdump-ada-spec
20336 @cindex @option{-fdump-ada-spec} (@command{gcc})
20337 Generate Ada spec files for the given header files transitively (including
20338 all header files that these headers depend upon).
20340 @item -fdump-ada-spec-slim
20341 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20342 Generate Ada spec files for the header files specified on the command line
20343 only.
20345 @item -fada-spec-parent=@var{unit}
20346 @cindex -fada-spec-parent (@command{gcc})
20347 Specifies that all files generated by @option{-fdump-ada-spec*} are
20348 to be child units of the specified parent unit.
20350 @item -C
20351 @cindex @option{-C} (@command{gcc})
20352 Extract comments from headers and generate Ada comments in the Ada spec files.
20353 @end table
20355 @node Other Utility Programs
20356 @chapter Other Utility Programs
20358 @noindent
20359 This chapter discusses some other utility programs available in the Ada
20360 environment.
20362 @menu
20363 * Using Other Utility Programs with GNAT::
20364 * The External Symbol Naming Scheme of GNAT::
20365 * Converting Ada Files to html with gnathtml::
20366 * Installing gnathtml::
20367 @ifset vms
20368 * LSE::
20369 * Profiling::
20370 @end ifset
20371 @end menu
20373 @node Using Other Utility Programs with GNAT
20374 @section Using Other Utility Programs with GNAT
20376 @noindent
20377 The object files generated by GNAT are in standard system format and in
20378 particular the debugging information uses this format. This means
20379 programs generated by GNAT can be used with existing utilities that
20380 depend on these formats.
20382 @ifclear vms
20383 In general, any utility program that works with C will also often work with
20384 Ada programs generated by GNAT. This includes software utilities such as
20385 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20386 as Purify.
20387 @end ifclear
20389 @node The External Symbol Naming Scheme of GNAT
20390 @section The External Symbol Naming Scheme of GNAT
20392 @noindent
20393 In order to interpret the output from GNAT, when using tools that are
20394 originally intended for use with other languages, it is useful to
20395 understand the conventions used to generate link names from the Ada
20396 entity names.
20398 All link names are in all lowercase letters. With the exception of library
20399 procedure names, the mechanism used is simply to use the full expanded
20400 Ada name with dots replaced by double underscores. For example, suppose
20401 we have the following package spec:
20403 @smallexample @c ada
20404 @group
20405 @cartouche
20406 package QRS is
20407    MN : Integer;
20408 end QRS;
20409 @end cartouche
20410 @end group
20411 @end smallexample
20413 @noindent
20414 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20415 the corresponding link name is @code{qrs__mn}.
20416 @findex Export
20417 Of course if a @code{pragma Export} is used this may be overridden:
20419 @smallexample @c ada
20420 @group
20421 @cartouche
20422 package Exports is
20423    Var1 : Integer;
20424    pragma Export (Var1, C, External_Name => "var1_name");
20425    Var2 : Integer;
20426    pragma Export (Var2, C, Link_Name => "var2_link_name");
20427 end Exports;
20428 @end cartouche
20429 @end group
20430 @end smallexample
20432 @noindent
20433 In this case, the link name for @var{Var1} is whatever link name the
20434 C compiler would assign for the C function @var{var1_name}. This typically
20435 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20436 system conventions, but other possibilities exist. The link name for
20437 @var{Var2} is @var{var2_link_name}, and this is not operating system
20438 dependent.
20440 @findex _main
20441 One exception occurs for library level procedures. A potential ambiguity
20442 arises between the required name @code{_main} for the C main program,
20443 and the name we would otherwise assign to an Ada library level procedure
20444 called @code{Main} (which might well not be the main program).
20446 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20447 names. So if we have a library level procedure such as
20449 @smallexample @c ada
20450 @group
20451 @cartouche
20452 procedure Hello (S : String);
20453 @end cartouche
20454 @end group
20455 @end smallexample
20457 @noindent
20458 the external name of this procedure will be @var{_ada_hello}.
20461 @node Converting Ada Files to html with gnathtml
20462 @section Converting Ada Files to HTML with @code{gnathtml}
20464 @noindent
20465 This @code{Perl} script allows Ada source files to be browsed using
20466 standard Web browsers. For installation procedure, see the section
20467 @xref{Installing gnathtml}.
20469 Ada reserved keywords are highlighted in a bold font and Ada comments in
20470 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20471 switch to suppress the generation of cross-referencing information, user
20472 defined variables and types will appear in a different color; you will
20473 be able to click on any identifier and go to its declaration.
20475 The command line is as follow:
20476 @smallexample
20477 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20478 @c Expanding @ovar macro inline (explanation in macro def comments)
20479 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20480 @end smallexample
20482 @noindent
20483 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20484 an html file for every ada file, and a global file called @file{index.htm}.
20485 This file is an index of every identifier defined in the files.
20487 The available ^switches^options^ are the following ones:
20489 @table @option
20490 @item -83
20491 @cindex @option{-83} (@code{gnathtml})
20492 Only the Ada 83 subset of keywords will be highlighted.
20494 @item -cc @var{color}
20495 @cindex @option{-cc} (@code{gnathtml})
20496 This option allows you to change the color used for comments. The default
20497 value is green. The color argument can be any name accepted by html.
20499 @item -d
20500 @cindex @option{-d} (@code{gnathtml})
20501 If the Ada files depend on some other files (for instance through
20502 @code{with} clauses, the latter files will also be converted to html.
20503 Only the files in the user project will be converted to html, not the files
20504 in the run-time library itself.
20506 @item -D
20507 @cindex @option{-D} (@code{gnathtml})
20508 This command is the same as @option{-d} above, but @command{gnathtml} will
20509 also look for files in the run-time library, and generate html files for them.
20511 @item -ext @var{extension}
20512 @cindex @option{-ext} (@code{gnathtml})
20513 This option allows you to change the extension of the generated HTML files.
20514 If you do not specify an extension, it will default to @file{htm}.
20516 @item -f
20517 @cindex @option{-f} (@code{gnathtml})
20518 By default, gnathtml will generate html links only for global entities
20519 ('with'ed units, global variables and types,@dots{}).  If you specify
20520 @option{-f} on the command line, then links will be generated for local
20521 entities too.
20523 @item -l @var{number}
20524 @cindex @option{-l} (@code{gnathtml})
20525 If this ^switch^option^ is provided and @var{number} is not 0, then
20526 @code{gnathtml} will number the html files every @var{number} line.
20528 @item -I @var{dir}
20529 @cindex @option{-I} (@code{gnathtml})
20530 Specify a directory to search for library files (@file{.ALI} files) and
20531 source files. You can provide several -I switches on the command line,
20532 and the directories will be parsed in the order of the command line.
20534 @item -o @var{dir}
20535 @cindex @option{-o} (@code{gnathtml})
20536 Specify the output directory for html files. By default, gnathtml will
20537 saved the generated html files in a subdirectory named @file{html/}.
20539 @item -p @var{file}
20540 @cindex @option{-p} (@code{gnathtml})
20541 If you are using Emacs and the most recent Emacs Ada mode, which provides
20542 a full Integrated Development Environment for compiling, checking,
20543 running and debugging applications, you may use @file{.gpr} files
20544 to give the directories where Emacs can find sources and object files.
20546 Using this ^switch^option^, you can tell gnathtml to use these files.
20547 This allows you to get an html version of your application, even if it
20548 is spread over multiple directories.
20550 @item -sc @var{color}
20551 @cindex @option{-sc} (@code{gnathtml})
20552 This ^switch^option^ allows you to change the color used for symbol
20553 definitions.
20554 The default value is red. The color argument can be any name accepted by html.
20556 @item -t @var{file}
20557 @cindex @option{-t} (@code{gnathtml})
20558 This ^switch^option^ provides the name of a file. This file contains a list of
20559 file names to be converted, and the effect is exactly as though they had
20560 appeared explicitly on the command line. This
20561 is the recommended way to work around the command line length limit on some
20562 systems.
20564 @end table
20566 @node Installing gnathtml
20567 @section Installing @code{gnathtml}
20569 @noindent
20570 @code{Perl} needs to be installed on your machine to run this script.
20571 @code{Perl} is freely available for almost every architecture and
20572 Operating System via the Internet.
20574 On Unix systems, you  may want to modify  the  first line of  the script
20575 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
20576 is. The syntax of this line is:
20577 @smallexample
20578 #!full_path_name_to_perl
20579 @end smallexample
20581 @noindent
20582 Alternatively, you may run the script using the following command line:
20584 @smallexample
20585 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20586 @c Expanding @ovar macro inline (explanation in macro def comments)
20587 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20588 @end smallexample
20590 @ifset vms
20591 @node LSE
20592 @section LSE
20593 @findex LSE
20595 @noindent
20596 The GNAT distribution provides an Ada 95 template for the HP Language
20597 Sensitive Editor (LSE), a component of DECset. In order to
20598 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20600 @node Profiling
20601 @section Profiling
20602 @findex PCA
20604 @noindent
20605 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20606 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20607 the collection phase with the /DEBUG qualifier.
20609 @smallexample
20610 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
20611 $ DEFINE LIB$DEBUG PCA$COLLECTOR
20612 $ RUN/DEBUG <PROGRAM_NAME>
20613 @end smallexample
20614 @noindent
20615 @end ifset
20617 @ifclear vms
20618 @c ******************************
20619 @node Code Coverage and Profiling
20620 @chapter Code Coverage and Profiling
20621 @cindex Code Coverage
20622 @cindex Profiling
20624 @noindent
20625 This chapter describes how to use @code{gcov} - coverage testing tool - and
20626 @code{gprof} - profiler tool - on your Ada programs.
20628 @menu
20629 * Code Coverage of Ada Programs with gcov::
20630 * Profiling an Ada Program with gprof::
20631 @end menu
20633 @node Code Coverage of Ada Programs with gcov
20634 @section Code Coverage of Ada Programs with gcov
20635 @cindex gcov
20636 @cindex -fprofile-arcs
20637 @cindex -ftest-coverage
20638 @cindex -coverage
20639 @cindex Code Coverage
20641 @noindent
20642 @code{gcov} is a test coverage program: it analyzes the execution of a given
20643 program on selected tests, to help you determine the portions of the program
20644 that are still untested.
20646 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20647 User's Guide. You can refer to this documentation for a more complete
20648 description.
20650 This chapter provides a quick startup guide, and
20651 details some Gnat-specific features.
20653 @menu
20654 * Quick startup guide::
20655 * Gnat specifics::
20656 @end menu
20658 @node Quick startup guide
20659 @subsection Quick startup guide
20661 In order to perform coverage analysis of a program using @code{gcov}, 3
20662 steps are needed:
20664 @itemize @bullet
20665 @item
20666 Code instrumentation during the compilation process
20667 @item
20668 Execution of the instrumented program
20669 @item
20670 Execution of the @code{gcov} tool to generate the result.
20671 @end itemize
20673 The code instrumentation needed by gcov is created at the object level:
20674 The source code is not modified in any way, because the instrumentation code is
20675 inserted by gcc during the compilation process. To compile your code with code
20676 coverage activated, you need to recompile your whole project using the
20677 switches
20678 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20679 @code{-fprofile-arcs}.
20681 @smallexample
20682 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20683    -largs -fprofile-arcs
20684 @end smallexample
20686 This compilation process will create @file{.gcno} files together with
20687 the usual object files.
20689 Once the program is compiled with coverage instrumentation, you can
20690 run it as many times as needed - on portions of a test suite for
20691 example. The first execution will produce @file{.gcda} files at the
20692 same location as the @file{.gcno} files.  The following executions
20693 will update those files, so that a cumulative result of the covered
20694 portions of the program is generated.
20696 Finally, you need to call the @code{gcov} tool. The different options of
20697 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20699 This will create annotated source files with a @file{.gcov} extension:
20700 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20702 @node Gnat specifics
20703 @subsection Gnat specifics
20705 Because Ada semantics, portions of the source code may be shared among
20706 several object files. This is the case for example when generics are
20707 involved, when inlining is active  or when declarations generate  initialisation
20708 calls. In order to take
20709 into account this shared code, you need to call @code{gcov} on all
20710 source files of the tested program at once.
20712 The list of source files might exceed the system's maximum command line
20713 length. In order to bypass this limitation, a new mechanism has been
20714 implemented in @code{gcov}: you can now list all your project's files into a
20715 text file, and provide this file to gcov as a parameter,  preceded by a @@
20716 (e.g. @samp{gcov @@mysrclist.txt}).
20718 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20719 not supported as there can be unresolved symbols during the final link.
20721 @node Profiling an Ada Program with gprof
20722 @section Profiling an Ada Program with gprof
20723 @cindex gprof
20724 @cindex -pg
20725 @cindex Profiling
20727 @noindent
20728 This section is not meant to be an exhaustive documentation of @code{gprof}.
20729 Full documentation for it can be found in the GNU Profiler User's Guide
20730 documentation that is part of this GNAT distribution.
20732 Profiling a program helps determine the parts of a program that are executed
20733 most often, and are therefore the most time-consuming.
20735 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20736 better handle Ada programs and multitasking.
20737 It is currently supported on the following platforms
20738 @itemize @bullet
20739 @item
20740 linux x86/x86_64
20741 @item
20742 solaris sparc/sparc64/x86
20743 @item
20744 windows x86
20745 @end itemize
20747 @noindent
20748 In order to profile a program using @code{gprof}, 3 steps are needed:
20750 @itemize @bullet
20751 @item
20752 Code instrumentation, requiring a full recompilation of the project with the
20753 proper switches.
20754 @item
20755 Execution of the program under the analysis conditions, i.e. with the desired
20756 input.
20757 @item
20758 Analysis of the results using the @code{gprof} tool.
20759 @end itemize
20761 @noindent
20762 The following sections detail the different steps, and indicate how
20763 to interpret the results:
20764 @menu
20765 * Compilation for profiling::
20766 * Program execution::
20767 * Running gprof::
20768 * Interpretation of profiling results::
20769 @end menu
20771 @node Compilation for profiling
20772 @subsection Compilation for profiling
20773 @cindex -pg
20774 @cindex Profiling
20776 In order to profile a program the first step is to tell the compiler
20777 to generate the necessary profiling information. The compiler switch to be used
20778 is @code{-pg}, which must be added to other compilation switches. This
20779 switch needs to be specified both during compilation and link stages, and can
20780 be specified once when using gnatmake:
20782 @smallexample
20783 gnatmake -f -pg -P my_project
20784 @end smallexample
20786 @noindent
20787 Note that only the objects that were compiled with the @samp{-pg} switch will
20788 be profiled; if you need to profile your whole project, use the @samp{-f}
20789 gnatmake switch to force full recompilation.
20791 @node Program execution
20792 @subsection Program execution
20794 @noindent
20795 Once the program has been compiled for profiling, you can run it as usual.
20797 The only constraint imposed by profiling is that the program must terminate
20798 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20799 properly analyzed.
20801 Once the program completes execution, a data file called @file{gmon.out} is
20802 generated in the directory where the program was launched from. If this file
20803 already exists, it will be overwritten.
20805 @node Running gprof
20806 @subsection Running gprof
20808 @noindent
20809 The @code{gprof} tool is called as follow:
20811 @smallexample
20812 gprof my_prog gmon.out
20813 @end smallexample
20815 @noindent
20816 or simpler:
20818 @smallexample
20819 gprof my_prog
20820 @end smallexample
20822 @noindent
20823 The complete form of the gprof command line is the following:
20825 @smallexample
20826 gprof [^switches^options^] [executable [data-file]]
20827 @end smallexample
20829 @noindent
20830 @code{gprof} supports numerous ^switch^options^. The order of these
20831 ^switch^options^ does not matter. The full list of options can be found in
20832 the GNU Profiler User's Guide documentation that comes with this documentation.
20834 The following is the subset of those switches that is most relevant:
20836 @table @option
20838 @item --demangle[=@var{style}]
20839 @itemx --no-demangle
20840 @cindex @option{--demangle} (@code{gprof})
20841 These options control whether symbol names should be demangled when
20842 printing output.  The default is to demangle C++ symbols.  The
20843 @code{--no-demangle} option may be used to turn off demangling. Different
20844 compilers have different mangling styles.  The optional demangling style
20845 argument can be used to choose an appropriate demangling style for your
20846 compiler, in particular Ada symbols generated by GNAT can be demangled using
20847 @code{--demangle=gnat}.
20849 @item -e @var{function_name}
20850 @cindex @option{-e} (@code{gprof})
20851 The @samp{-e @var{function}} option tells @code{gprof} not to print
20852 information about the function @var{function_name} (and its
20853 children@dots{}) in the call graph.  The function will still be listed
20854 as a child of any functions that call it, but its index number will be
20855 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
20856 given; only one @var{function_name} may be indicated with each @samp{-e}
20857 option.
20859 @item -E @var{function_name}
20860 @cindex @option{-E} (@code{gprof})
20861 The @code{-E @var{function}} option works like the @code{-e} option, but
20862 execution time spent in the function (and children who were not called from
20863 anywhere else), will not be used to compute the percentages-of-time for
20864 the call graph.  More than one @samp{-E} option may be given; only one
20865 @var{function_name} may be indicated with each @samp{-E} option.
20867 @item -f @var{function_name}
20868 @cindex @option{-f} (@code{gprof})
20869 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20870 call graph to the function @var{function_name} and its children (and
20871 their children@dots{}).  More than one @samp{-f} option may be given;
20872 only one @var{function_name} may be indicated with each @samp{-f}
20873 option.
20875 @item -F @var{function_name}
20876 @cindex @option{-F} (@code{gprof})
20877 The @samp{-F @var{function}} option works like the @code{-f} option, but
20878 only time spent in the function and its children (and their
20879 children@dots{}) will be used to determine total-time and
20880 percentages-of-time for the call graph.  More than one @samp{-F} option
20881 may be given; only one @var{function_name} may be indicated with each
20882 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
20884 @end table
20886 @node Interpretation of profiling results
20887 @subsection Interpretation of profiling results
20889 @noindent
20891 The results of the profiling analysis are represented by two arrays: the
20892 'flat profile' and the 'call graph'. Full documentation of those outputs
20893 can be found in the GNU Profiler User's Guide.
20895 The flat profile shows the time spent in each function of the program, and how
20896 many time it has been called. This allows you to locate easily the most
20897 time-consuming functions.
20899 The call graph shows, for each subprogram, the subprograms that call it,
20900 and the subprograms that it calls. It also provides an estimate of the time
20901 spent in each of those callers/called subprograms.
20902 @end ifclear
20904 @c ******************************
20905 @node Running and Debugging Ada Programs
20906 @chapter Running and Debugging Ada Programs
20907 @cindex Debugging
20909 @noindent
20910 This chapter discusses how to debug Ada programs.
20911 @ifset vms
20912 It applies to GNAT on the Alpha OpenVMS platform;
20913 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
20914 since HP has implemented Ada support in the OpenVMS debugger on I64.
20915 @end ifset
20917 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20919 @enumerate
20920 @item
20921 The illegality may be a violation of the static semantics of Ada. In
20922 that case GNAT diagnoses the constructs in the program that are illegal.
20923 It is then a straightforward matter for the user to modify those parts of
20924 the program.
20926 @item
20927 The illegality may be a violation of the dynamic semantics of Ada. In
20928 that case the program compiles and executes, but may generate incorrect
20929 results, or may terminate abnormally with some exception.
20931 @item
20932 When presented with a program that contains convoluted errors, GNAT
20933 itself may terminate abnormally without providing full diagnostics on
20934 the incorrect user program.
20935 @end enumerate
20937 @menu
20938 * The GNAT Debugger GDB::
20939 * Running GDB::
20940 * Introduction to GDB Commands::
20941 * Using Ada Expressions::
20942 * Calling User-Defined Subprograms::
20943 * Using the Next Command in a Function::
20944 * Ada Exceptions::
20945 * Ada Tasks::
20946 * Debugging Generic Units::
20947 * Remote Debugging with gdbserver::
20948 * GNAT Abnormal Termination or Failure to Terminate::
20949 * Naming Conventions for GNAT Source Files::
20950 * Getting Internal Debugging Information::
20951 * Stack Traceback::
20952 @end menu
20954 @cindex Debugger
20955 @findex gdb
20957 @node The GNAT Debugger GDB
20958 @section The GNAT Debugger GDB
20960 @noindent
20961 @code{GDB} is a general purpose, platform-independent debugger that
20962 can be used to debug mixed-language programs compiled with @command{gcc},
20963 and in particular is capable of debugging Ada programs compiled with
20964 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20965 complex Ada data structures.
20967 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20968 @ifset vms
20969 located in the GNU:[DOCS] directory,
20970 @end ifset
20971 for full details on the usage of @code{GDB}, including a section on
20972 its usage on programs. This manual should be consulted for full
20973 details. The section that follows is a brief introduction to the
20974 philosophy and use of @code{GDB}.
20976 When GNAT programs are compiled, the compiler optionally writes debugging
20977 information into the generated object file, including information on
20978 line numbers, and on declared types and variables. This information is
20979 separate from the generated code. It makes the object files considerably
20980 larger, but it does not add to the size of the actual executable that
20981 will be loaded into memory, and has no impact on run-time performance. The
20982 generation of debug information is triggered by the use of the
20983 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
20984 used to carry out the compilations. It is important to emphasize that
20985 the use of these options does not change the generated code.
20987 The debugging information is written in standard system formats that
20988 are used by many tools, including debuggers and profilers. The format
20989 of the information is typically designed to describe C types and
20990 semantics, but GNAT implements a translation scheme which allows full
20991 details about Ada types and variables to be encoded into these
20992 standard C formats. Details of this encoding scheme may be found in
20993 the file exp_dbug.ads in the GNAT source distribution. However, the
20994 details of this encoding are, in general, of no interest to a user,
20995 since @code{GDB} automatically performs the necessary decoding.
20997 When a program is bound and linked, the debugging information is
20998 collected from the object files, and stored in the executable image of
20999 the program. Again, this process significantly increases the size of
21000 the generated executable file, but it does not increase the size of
21001 the executable program itself. Furthermore, if this program is run in
21002 the normal manner, it runs exactly as if the debug information were
21003 not present, and takes no more actual memory.
21005 However, if the program is run under control of @code{GDB}, the
21006 debugger is activated.  The image of the program is loaded, at which
21007 point it is ready to run.  If a run command is given, then the program
21008 will run exactly as it would have if @code{GDB} were not present. This
21009 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
21010 entirely non-intrusive until a breakpoint is encountered.  If no
21011 breakpoint is ever hit, the program will run exactly as it would if no
21012 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21013 the debugging information and can respond to user commands to inspect
21014 variables, and more generally to report on the state of execution.
21016 @c **************
21017 @node Running GDB
21018 @section Running GDB
21020 @noindent
21021 This section describes how to initiate the debugger.
21022 @c The above sentence is really just filler, but it was otherwise
21023 @c clumsy to get the first paragraph nonindented given the conditional
21024 @c nature of the description
21026 @ifclear vms
21027 The debugger can be launched from a @code{GPS} menu or
21028 directly from the command line. The description below covers the latter use.
21029 All the commands shown can be used in the @code{GPS} debug console window,
21030 but there are usually more GUI-based ways to achieve the same effect.
21031 @end ifclear
21033 The command to run @code{GDB} is
21035 @smallexample
21036 $ ^gdb program^GDB PROGRAM^
21037 @end smallexample
21039 @noindent
21040 where @code{^program^PROGRAM^} is the name of the executable file. This
21041 activates the debugger and results in a prompt for debugger commands.
21042 The simplest command is simply @code{run}, which causes the program to run
21043 exactly as if the debugger were not present. The following section
21044 describes some of the additional commands that can be given to @code{GDB}.
21046 @c *******************************
21047 @node Introduction to GDB Commands
21048 @section Introduction to GDB Commands
21050 @noindent
21051 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
21052 Debugging with GDB, gdb, Debugging with GDB},
21053 @ifset vms
21054 located in the GNU:[DOCS] directory,
21055 @end ifset
21056 for extensive documentation on the use
21057 of these commands, together with examples of their use. Furthermore,
21058 the command @command{help} invoked from within GDB activates a simple help
21059 facility which summarizes the available commands and their options.
21060 In this section we summarize a few of the most commonly
21061 used commands to give an idea of what @code{GDB} is about. You should create
21062 a simple program with debugging information and experiment with the use of
21063 these @code{GDB} commands on the program as you read through the
21064 following section.
21066 @table @code
21067 @item set args @var{arguments}
21068 The @var{arguments} list above is a list of arguments to be passed to
21069 the program on a subsequent run command, just as though the arguments
21070 had been entered on a normal invocation of the program. The @code{set args}
21071 command is not needed if the program does not require arguments.
21073 @item run
21074 The @code{run} command causes execution of the program to start from
21075 the beginning. If the program is already running, that is to say if
21076 you are currently positioned at a breakpoint, then a prompt will ask
21077 for confirmation that you want to abandon the current execution and
21078 restart.
21080 @item breakpoint @var{location}
21081 The breakpoint command sets a breakpoint, that is to say a point at which
21082 execution will halt and @code{GDB} will await further
21083 commands. @var{location} is
21084 either a line number within a file, given in the format @code{file:linenumber},
21085 or it is the name of a subprogram. If you request that a breakpoint be set on
21086 a subprogram that is overloaded, a prompt will ask you to specify on which of
21087 those subprograms you want to breakpoint. You can also
21088 specify that all of them should be breakpointed. If the program is run
21089 and execution encounters the breakpoint, then the program
21090 stops and @code{GDB} signals that the breakpoint was encountered by
21091 printing the line of code before which the program is halted.
21093 @item catch exception @var{name}
21094 This command causes the program execution to stop whenever exception
21095 @var{name} is raised.  If @var{name} is omitted, then the execution is
21096 suspended when any exception is raised.
21098 @item print @var{expression}
21099 This will print the value of the given expression. Most simple
21100 Ada expression formats are properly handled by @code{GDB}, so the expression
21101 can contain function calls, variables, operators, and attribute references.
21103 @item continue
21104 Continues execution following a breakpoint, until the next breakpoint or the
21105 termination of the program.
21107 @item step
21108 Executes a single line after a breakpoint. If the next statement
21109 is a subprogram call, execution continues into (the first statement of)
21110 the called subprogram.
21112 @item next
21113 Executes a single line. If this line is a subprogram call, executes and
21114 returns from the call.
21116 @item list
21117 Lists a few lines around the current source location. In practice, it
21118 is usually more convenient to have a separate edit window open with the
21119 relevant source file displayed. Successive applications of this command
21120 print subsequent lines. The command can be given an argument which is a
21121 line number, in which case it displays a few lines around the specified one.
21123 @item backtrace
21124 Displays a backtrace of the call chain. This command is typically
21125 used after a breakpoint has occurred, to examine the sequence of calls that
21126 leads to the current breakpoint. The display includes one line for each
21127 activation record (frame) corresponding to an active subprogram.
21129 @item up
21130 At a breakpoint, @code{GDB} can display the values of variables local
21131 to the current frame. The command @code{up} can be used to
21132 examine the contents of other active frames, by moving the focus up
21133 the stack, that is to say from callee to caller, one frame at a time.
21135 @item down
21136 Moves the focus of @code{GDB} down from the frame currently being
21137 examined to the frame of its callee (the reverse of the previous command),
21139 @item frame @var{n}
21140 Inspect the frame with the given number. The value 0 denotes the frame
21141 of the current breakpoint, that is to say the top of the call stack.
21143 @end table
21145 @noindent
21146 The above list is a very short introduction to the commands that
21147 @code{GDB} provides. Important additional capabilities, including conditional
21148 breakpoints, the ability to execute command sequences on a breakpoint,
21149 the ability to debug at the machine instruction level and many other
21150 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
21151 Debugging with GDB}.  Note that most commands can be abbreviated
21152 (for example, c for continue, bt for backtrace).
21154 @node Using Ada Expressions
21155 @section Using Ada Expressions
21156 @cindex Ada expressions
21158 @noindent
21159 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
21160 extensions. The philosophy behind the design of this subset is
21162 @itemize @bullet
21163 @item
21164 That @code{GDB} should provide basic literals and access to operations for
21165 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21166 leaving more sophisticated computations to subprograms written into the
21167 program (which therefore may be called from @code{GDB}).
21169 @item
21170 That type safety and strict adherence to Ada language restrictions
21171 are not particularly important to the @code{GDB} user.
21173 @item
21174 That brevity is important to the @code{GDB} user.
21175 @end itemize
21177 @noindent
21178 Thus, for brevity, the debugger acts as if there were
21179 implicit @code{with} and @code{use} clauses in effect for all user-written
21180 packages, thus making it unnecessary to fully qualify most names with
21181 their packages, regardless of context. Where this causes ambiguity,
21182 @code{GDB} asks the user's intent.
21184 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21185 GDB, gdb, Debugging with GDB}.
21187 @node Calling User-Defined Subprograms
21188 @section Calling User-Defined Subprograms
21190 @noindent
21191 An important capability of @code{GDB} is the ability to call user-defined
21192 subprograms while debugging. This is achieved simply by entering
21193 a subprogram call statement in the form:
21195 @smallexample
21196 call subprogram-name (parameters)
21197 @end smallexample
21199 @noindent
21200 The keyword @code{call} can be omitted in the normal case where the
21201 @code{subprogram-name} does not coincide with any of the predefined
21202 @code{GDB} commands.
21204 The effect is to invoke the given subprogram, passing it the
21205 list of parameters that is supplied. The parameters can be expressions and
21206 can include variables from the program being debugged. The
21207 subprogram must be defined
21208 at the library level within your program, and @code{GDB} will call the
21209 subprogram within the environment of your program execution (which
21210 means that the subprogram is free to access or even modify variables
21211 within your program).
21213 The most important use of this facility is in allowing the inclusion of
21214 debugging routines that are tailored to particular data structures
21215 in your program. Such debugging routines can be written to provide a suitably
21216 high-level description of an abstract type, rather than a low-level dump
21217 of its physical layout. After all, the standard
21218 @code{GDB print} command only knows the physical layout of your
21219 types, not their abstract meaning. Debugging routines can provide information
21220 at the desired semantic level and are thus enormously useful.
21222 For example, when debugging GNAT itself, it is crucial to have access to
21223 the contents of the tree nodes used to represent the program internally.
21224 But tree nodes are represented simply by an integer value (which in turn
21225 is an index into a table of nodes).
21226 Using the @code{print} command on a tree node would simply print this integer
21227 value, which is not very useful. But the PN routine (defined in file
21228 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21229 a useful high level representation of the tree node, which includes the
21230 syntactic category of the node, its position in the source, the integers
21231 that denote descendant nodes and parent node, as well as varied
21232 semantic information. To study this example in more detail, you might want to
21233 look at the body of the PN procedure in the stated file.
21235 @node Using the Next Command in a Function
21236 @section Using the Next Command in a Function
21238 @noindent
21239 When you use the @code{next} command in a function, the current source
21240 location will advance to the next statement as usual. A special case
21241 arises in the case of a @code{return} statement.
21243 Part of the code for a return statement is the ``epilog'' of the function.
21244 This is the code that returns to the caller. There is only one copy of
21245 this epilog code, and it is typically associated with the last return
21246 statement in the function if there is more than one return. In some
21247 implementations, this epilog is associated with the first statement
21248 of the function.
21250 The result is that if you use the @code{next} command from a return
21251 statement that is not the last return statement of the function you
21252 may see a strange apparent jump to the last return statement or to
21253 the start of the function. You should simply ignore this odd jump.
21254 The value returned is always that from the first return statement
21255 that was stepped through.
21257 @node Ada Exceptions
21258 @section Stopping when Ada Exceptions are Raised
21259 @cindex Exceptions
21261 @noindent
21262 You can set catchpoints that stop the program execution when your program
21263 raises selected exceptions.
21265 @table @code
21266 @item catch exception
21267 Set a catchpoint that stops execution whenever (any task in the) program
21268 raises any exception.
21270 @item catch exception @var{name}
21271 Set a catchpoint that stops execution whenever (any task in the) program
21272 raises the exception @var{name}.
21274 @item catch exception unhandled
21275 Set a catchpoint that stops executing whenever (any task in the) program
21276 raises an exception for which there is no handler.
21278 @item info exceptions
21279 @itemx info exceptions @var{regexp}
21280 The @code{info exceptions} command permits the user to examine all defined
21281 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21282 argument, prints out only those exceptions whose name matches @var{regexp}.
21283 @end table
21285 @node Ada Tasks
21286 @section Ada Tasks
21287 @cindex Tasks
21289 @noindent
21290 @code{GDB} allows the following task-related commands:
21292 @table @code
21293 @item info tasks
21294 This command shows a list of current Ada tasks, as in the following example:
21296 @smallexample
21297 @iftex
21298 @leftskip=0cm
21299 @end iftex
21300 (gdb) info tasks
21301   ID       TID P-ID   Thread Pri State                 Name
21302    1   8088000   0   807e000  15 Child Activation Wait main_task
21303    2   80a4000   1   80ae000  15 Accept/Select Wait    b
21304    3   809a800   1   80a4800  15 Child Activation Wait a
21305 *  4   80ae800   3   80b8000  15 Running               c
21306 @end smallexample
21308 @noindent
21309 In this listing, the asterisk before the first task indicates it to be the
21310 currently running task. The first column lists the task ID that is used
21311 to refer to tasks in the following commands.
21313 @item break @var{linespec} task @var{taskid}
21314 @itemx break @var{linespec} task @var{taskid} if @dots{}
21315 @cindex Breakpoints and tasks
21316 These commands are like the @code{break @dots{} thread @dots{}}.
21317 @var{linespec} specifies source lines.
21319 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21320 to specify that you only want @code{GDB} to stop the program when a
21321 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21322 numeric task identifiers assigned by @code{GDB}, shown in the first
21323 column of the @samp{info tasks} display.
21325 If you do not specify @samp{task @var{taskid}} when you set a
21326 breakpoint, the breakpoint applies to @emph{all} tasks of your
21327 program.
21329 You can use the @code{task} qualifier on conditional breakpoints as
21330 well; in this case, place @samp{task @var{taskid}} before the
21331 breakpoint condition (before the @code{if}).
21333 @item task @var{taskno}
21334 @cindex Task switching
21336 This command allows to switch to the task referred by @var{taskno}. In
21337 particular, This allows to browse the backtrace of the specified
21338 task. It is advised to switch back to the original task before
21339 continuing execution otherwise the scheduling of the program may be
21340 perturbed.
21341 @end table
21343 @noindent
21344 For more detailed information on the tasking support,
21345 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21347 @node Debugging Generic Units
21348 @section Debugging Generic Units
21349 @cindex Debugging Generic Units
21350 @cindex Generics
21352 @noindent
21353 GNAT always uses code expansion for generic instantiation. This means that
21354 each time an instantiation occurs, a complete copy of the original code is
21355 made, with appropriate substitutions of formals by actuals.
21357 It is not possible to refer to the original generic entities in
21358 @code{GDB}, but it is always possible to debug a particular instance of
21359 a generic, by using the appropriate expanded names. For example, if we have
21361 @smallexample @c ada
21362 @group
21363 @cartouche
21364 procedure g is
21366    generic package k is
21367       procedure kp (v1 : in out integer);
21368    end k;
21370    package body k is
21371       procedure kp (v1 : in out integer) is
21372       begin
21373          v1 := v1 + 1;
21374       end kp;
21375    end k;
21377    package k1 is new k;
21378    package k2 is new k;
21380    var : integer := 1;
21382 begin
21383    k1.kp (var);
21384    k2.kp (var);
21385    k1.kp (var);
21386    k2.kp (var);
21387 end;
21388 @end cartouche
21389 @end group
21390 @end smallexample
21392 @noindent
21393 Then to break on a call to procedure kp in the k2 instance, simply
21394 use the command:
21396 @smallexample
21397 (gdb) break g.k2.kp
21398 @end smallexample
21400 @noindent
21401 When the breakpoint occurs, you can step through the code of the
21402 instance in the normal manner and examine the values of local variables, as for
21403 other units.
21405 @node Remote Debugging with gdbserver
21406 @section Remote Debugging with gdbserver
21407 @cindex Remote Debugging with gdbserver
21409 @noindent
21410 On platforms where gdbserver is supported, it is possible to use this tool
21411 to debug your application remotely.  This can be useful in situations
21412 where the program needs to be run on a target host that is different
21413 from the host used for development, particularly when the target has
21414 a limited amount of resources (either CPU and/or memory).
21416 To do so, start your program using gdbserver on the target machine.
21417 gdbserver then automatically suspends the execution of your program
21418 at its entry point, waiting for a debugger to connect to it.  The
21419 following commands starts an application and tells gdbserver to
21420 wait for a connection with the debugger on localhost port 4444.
21422 @smallexample
21423 $ gdbserver localhost:4444 program
21424 Process program created; pid = 5685
21425 Listening on port 4444
21426 @end smallexample
21428 Once gdbserver has started listening, we can tell the debugger to establish
21429 a connection with this gdbserver, and then start the same debugging session
21430 as if the program was being debugged on the same host, directly under
21431 the control of GDB.
21433 @smallexample
21434 $ gdb program
21435 (gdb) target remote targethost:4444
21436 Remote debugging using targethost:4444
21437 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21438 (gdb) b foo.adb:3
21439 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21440 (gdb) continue
21441 Continuing.
21443 Breakpoint 1, foo () at foo.adb:4
21444 4       end foo;
21445 @end smallexample
21447 It is also possible to use gdbserver to attach to an already running
21448 program, in which case the execution of that program is simply suspended
21449 until the connection between the debugger and gdbserver is established.
21451 For more information on how to use gdbserver, @ref{Top, Server, Using
21452 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
21453 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21455 @node GNAT Abnormal Termination or Failure to Terminate
21456 @section GNAT Abnormal Termination or Failure to Terminate
21457 @cindex GNAT Abnormal Termination or Failure to Terminate
21459 @noindent
21460 When presented with programs that contain serious errors in syntax
21461 or semantics,
21462 GNAT may on rare occasions  experience problems in operation, such
21463 as aborting with a
21464 segmentation fault or illegal memory access, raising an internal
21465 exception, terminating abnormally, or failing to terminate at all.
21466 In such cases, you can activate
21467 various features of GNAT that can help you pinpoint the construct in your
21468 program that is the likely source of the problem.
21470 The following strategies are presented in increasing order of
21471 difficulty, corresponding to your experience in using GNAT and your
21472 familiarity with compiler internals.
21474 @enumerate
21475 @item
21476 Run @command{gcc} with the @option{-gnatf}. This first
21477 switch causes all errors on a given line to be reported. In its absence,
21478 only the first error on a line is displayed.
21480 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21481 are encountered, rather than after compilation is terminated. If GNAT
21482 terminates prematurely or goes into an infinite loop, the last error
21483 message displayed may help to pinpoint the culprit.
21485 @item
21486 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21487 mode, @command{gcc} produces ongoing information about the progress of the
21488 compilation and provides the name of each procedure as code is
21489 generated. This switch allows you to find which Ada procedure was being
21490 compiled when it encountered a code generation problem.
21492 @item
21493 @cindex @option{-gnatdc} switch
21494 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21495 switch that does for the front-end what @option{^-v^VERBOSE^} does
21496 for the back end. The system prints the name of each unit,
21497 either a compilation unit or nested unit, as it is being analyzed.
21498 @item
21499 Finally, you can start
21500 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21501 front-end of GNAT, and can be run independently (normally it is just
21502 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21503 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21504 @code{where} command is the first line of attack; the variable
21505 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21506 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21507 which the execution stopped, and @code{input_file name} indicates the name of
21508 the source file.
21509 @end enumerate
21511 @node Naming Conventions for GNAT Source Files
21512 @section Naming Conventions for GNAT Source Files
21514 @noindent
21515 In order to examine the workings of the GNAT system, the following
21516 brief description of its organization may be helpful:
21518 @itemize @bullet
21519 @item
21520 Files with prefix @file{^sc^SC^} contain the lexical scanner.
21522 @item
21523 All files prefixed with @file{^par^PAR^} are components of the parser. The
21524 numbers correspond to chapters of the Ada Reference Manual. For example,
21525 parsing of select statements can be found in @file{par-ch9.adb}.
21527 @item
21528 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21529 numbers correspond to chapters of the Ada standard. For example, all
21530 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21531 addition, some features of the language require sufficient special processing
21532 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21533 dynamic dispatching, etc.
21535 @item
21536 All files prefixed with @file{^exp^EXP^} perform normalization and
21537 expansion of the intermediate representation (abstract syntax tree, or AST).
21538 these files use the same numbering scheme as the parser and semantics files.
21539 For example, the construction of record initialization procedures is done in
21540 @file{exp_ch3.adb}.
21542 @item
21543 The files prefixed with @file{^bind^BIND^} implement the binder, which
21544 verifies the consistency of the compilation, determines an order of
21545 elaboration, and generates the bind file.
21547 @item
21548 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21549 data structures used by the front-end.
21551 @item
21552 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21553 the abstract syntax tree as produced by the parser.
21555 @item
21556 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21557 all entities, computed during semantic analysis.
21559 @item
21560 Library management issues are dealt with in files with prefix
21561 @file{^lib^LIB^}.
21563 @item
21564 @findex Ada
21565 @cindex Annex A
21566 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21567 defined in Annex A.
21569 @item
21570 @findex Interfaces
21571 @cindex Annex B
21572 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21573 defined in Annex B.
21575 @item
21576 @findex System
21577 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21578 both language-defined children and GNAT run-time routines.
21580 @item
21581 @findex GNAT
21582 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21583 general-purpose packages, fully documented in their specs. All
21584 the other @file{.c} files are modifications of common @command{gcc} files.
21585 @end itemize
21587 @node Getting Internal Debugging Information
21588 @section Getting Internal Debugging Information
21590 @noindent
21591 Most compilers have internal debugging switches and modes. GNAT
21592 does also, except GNAT internal debugging switches and modes are not
21593 secret. A summary and full description of all the compiler and binder
21594 debug flags are in the file @file{debug.adb}. You must obtain the
21595 sources of the compiler to see the full detailed effects of these flags.
21597 The switches that print the source of the program (reconstructed from
21598 the internal tree) are of general interest for user programs, as are the
21599 options to print
21600 the full internal tree, and the entity table (the symbol table
21601 information). The reconstructed source provides a readable version of the
21602 program after the front-end has completed analysis and  expansion,
21603 and is useful when studying the performance of specific constructs.
21604 For example, constraint checks are indicated, complex aggregates
21605 are replaced with loops and assignments, and tasking primitives
21606 are replaced with run-time calls.
21608 @node Stack Traceback
21609 @section Stack Traceback
21610 @cindex traceback
21611 @cindex stack traceback
21612 @cindex stack unwinding
21614 @noindent
21615 Traceback is a mechanism to display the sequence of subprogram calls that
21616 leads to a specified execution point in a program. Often (but not always)
21617 the execution point is an instruction at which an exception has been raised.
21618 This mechanism is also known as @i{stack unwinding} because it obtains
21619 its information by scanning the run-time stack and recovering the activation
21620 records of all active subprograms. Stack unwinding is one of the most
21621 important tools for program debugging.
21623 The first entry stored in traceback corresponds to the deepest calling level,
21624 that is to say the subprogram currently executing the instruction
21625 from which we want to obtain the traceback.
21627 Note that there is no runtime performance penalty when stack traceback
21628 is enabled, and no exception is raised during program execution.
21630 @menu
21631 * Non-Symbolic Traceback::
21632 * Symbolic Traceback::
21633 @end menu
21635 @node Non-Symbolic Traceback
21636 @subsection Non-Symbolic Traceback
21637 @cindex traceback, non-symbolic
21639 @noindent
21640 Note: this feature is not supported on all platforms. See
21641 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21642 platforms.
21644 @menu
21645 * Tracebacks From an Unhandled Exception::
21646 * Tracebacks From Exception Occurrences (non-symbolic)::
21647 * Tracebacks From Anywhere in a Program (non-symbolic)::
21648 @end menu
21650 @node Tracebacks From an Unhandled Exception
21651 @subsubsection Tracebacks From an Unhandled Exception
21653 @noindent
21654 A runtime non-symbolic traceback is a list of addresses of call instructions.
21655 To enable this feature you must use the @option{-E}
21656 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21657 of exception information. You can retrieve this information using the
21658 @code{addr2line} tool.
21660 Here is a simple example:
21662 @smallexample @c ada
21663 @cartouche
21664 procedure STB is
21666    procedure P1 is
21667    begin
21668       raise Constraint_Error;
21669    end P1;
21671    procedure P2 is
21672    begin
21673       P1;
21674    end P2;
21676 begin
21677    P2;
21678 end STB;
21679 @end cartouche
21680 @end smallexample
21682 @smallexample
21683 $ gnatmake stb -bargs -E
21684 $ stb
21686 Execution terminated by unhandled exception
21687 Exception name: CONSTRAINT_ERROR
21688 Message: stb.adb:5
21689 Call stack traceback locations:
21690 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21691 @end smallexample
21693 @noindent
21694 As we see the traceback lists a sequence of addresses for the unhandled
21695 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21696 guess that this exception come from procedure P1. To translate these
21697 addresses into the source lines where the calls appear, the
21698 @code{addr2line} tool, described below, is invaluable. The use of this tool
21699 requires the program to be compiled with debug information.
21701 @smallexample
21702 $ gnatmake -g stb -bargs -E
21703 $ stb
21705 Execution terminated by unhandled exception
21706 Exception name: CONSTRAINT_ERROR
21707 Message: stb.adb:5
21708 Call stack traceback locations:
21709 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21711 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21712    0x4011f1 0x77e892a4
21714 00401373 at d:/stb/stb.adb:5
21715 0040138B at d:/stb/stb.adb:10
21716 0040139C at d:/stb/stb.adb:14
21717 00401335 at d:/stb/b~stb.adb:104
21718 004011C4 at /build/@dots{}/crt1.c:200
21719 004011F1 at /build/@dots{}/crt1.c:222
21720 77E892A4 in ?? at ??:0
21721 @end smallexample
21723 @noindent
21724 The @code{addr2line} tool has several other useful options:
21726 @table @code
21727 @item --functions
21728 to get the function name corresponding to any location
21730 @item --demangle=gnat
21731 to use the gnat decoding mode for the function names. Note that
21732 for binutils version 2.9.x the option is simply @option{--demangle}.
21733 @end table
21735 @smallexample
21736 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21737    0x40139c 0x401335 0x4011c4 0x4011f1
21739 00401373 in stb.p1 at d:/stb/stb.adb:5
21740 0040138B in stb.p2 at d:/stb/stb.adb:10
21741 0040139C in stb at d:/stb/stb.adb:14
21742 00401335 in main at d:/stb/b~stb.adb:104
21743 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21744 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21745 @end smallexample
21747 @noindent
21748 From this traceback we can see that the exception was raised in
21749 @file{stb.adb} at line 5, which was reached from a procedure call in
21750 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21751 which contains the call to the main program.
21752 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21753 and the output will vary from platform to platform.
21755 It is also possible to use @code{GDB} with these traceback addresses to debug
21756 the program. For example, we can break at a given code location, as reported
21757 in the stack traceback:
21759 @smallexample
21760 $ gdb -nw stb
21761 @ifclear vms
21762 @noindent
21763 Furthermore, this feature is not implemented inside Windows DLL. Only
21764 the non-symbolic traceback is reported in this case.
21765 @end ifclear
21767 (gdb) break *0x401373
21768 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21769 @end smallexample
21771 @noindent
21772 It is important to note that the stack traceback addresses
21773 do not change when debug information is included. This is particularly useful
21774 because it makes it possible to release software without debug information (to
21775 minimize object size), get a field report that includes a stack traceback
21776 whenever an internal bug occurs, and then be able to retrieve the sequence
21777 of calls with the same program compiled with debug information.
21779 @node Tracebacks From Exception Occurrences (non-symbolic)
21780 @subsubsection Tracebacks From Exception Occurrences
21782 @noindent
21783 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21784 The stack traceback is attached to the exception information string, and can
21785 be retrieved in an exception handler within the Ada program, by means of the
21786 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21788 @smallexample @c ada
21789 with Ada.Text_IO;
21790 with Ada.Exceptions;
21792 procedure STB is
21794    use Ada;
21795    use Ada.Exceptions;
21797    procedure P1 is
21798       K : Positive := 1;
21799    begin
21800       K := K - 1;
21801    exception
21802       when E : others =>
21803          Text_IO.Put_Line (Exception_Information (E));
21804    end P1;
21806    procedure P2 is
21807    begin
21808       P1;
21809    end P2;
21811 begin
21812    P2;
21813 end STB;
21814 @end smallexample
21816 @noindent
21817 This program will output:
21819 @smallexample
21820 $ stb
21822 Exception name: CONSTRAINT_ERROR
21823 Message: stb.adb:12
21824 Call stack traceback locations:
21825 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21826 @end smallexample
21828 @node Tracebacks From Anywhere in a Program (non-symbolic)
21829 @subsubsection Tracebacks From Anywhere in a Program
21831 @noindent
21832 It is also possible to retrieve a stack traceback from anywhere in a
21833 program. For this you need to
21834 use the @code{GNAT.Traceback} API. This package includes a procedure called
21835 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21836 display procedures described below. It is not necessary to use the
21837 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21838 is invoked explicitly.
21840 @noindent
21841 In the following example we compute a traceback at a specific location in
21842 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21843 convert addresses to strings:
21845 @smallexample @c ada
21846 with Ada.Text_IO;
21847 with GNAT.Traceback;
21848 with GNAT.Debug_Utilities;
21850 procedure STB is
21852    use Ada;
21853    use GNAT;
21854    use GNAT.Traceback;
21856    procedure P1 is
21857       TB  : Tracebacks_Array (1 .. 10);
21858       --  We are asking for a maximum of 10 stack frames.
21859       Len : Natural;
21860       --  Len will receive the actual number of stack frames returned.
21861    begin
21862       Call_Chain (TB, Len);
21864       Text_IO.Put ("In STB.P1 : ");
21866       for K in 1 .. Len loop
21867          Text_IO.Put (Debug_Utilities.Image (TB (K)));
21868          Text_IO.Put (' ');
21869       end loop;
21871       Text_IO.New_Line;
21872    end P1;
21874    procedure P2 is
21875    begin
21876       P1;
21877    end P2;
21879 begin
21880    P2;
21881 end STB;
21882 @end smallexample
21884 @smallexample
21885 $ gnatmake -g stb
21886 $ stb
21888 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21889 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21890 @end smallexample
21892 @noindent
21893 You can then get further information by invoking the @code{addr2line}
21894 tool as described earlier (note that the hexadecimal addresses
21895 need to be specified in C format, with a leading ``0x'').
21897 @node Symbolic Traceback
21898 @subsection Symbolic Traceback
21899 @cindex traceback, symbolic
21901 @noindent
21902 A symbolic traceback is a stack traceback in which procedure names are
21903 associated with each code location.
21905 @noindent
21906 Note that this feature is not supported on all platforms. See
21907 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21908 list of currently supported platforms.
21910 @noindent
21911 Note that the symbolic traceback requires that the program be compiled
21912 with debug information. If it is not compiled with debug information
21913 only the non-symbolic information will be valid.
21915 @menu
21916 * Tracebacks From Exception Occurrences (symbolic)::
21917 * Tracebacks From Anywhere in a Program (symbolic)::
21918 @end menu
21920 @node Tracebacks From Exception Occurrences (symbolic)
21921 @subsubsection Tracebacks From Exception Occurrences
21923 @smallexample @c ada
21924 with Ada.Text_IO;
21925 with GNAT.Traceback.Symbolic;
21927 procedure STB is
21929    procedure P1 is
21930    begin
21931       raise Constraint_Error;
21932    end P1;
21934    procedure P2 is
21935    begin
21936       P1;
21937    end P2;
21939    procedure P3 is
21940    begin
21941       P2;
21942    end P3;
21944 begin
21945    P3;
21946 exception
21947    when E : others =>
21948       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21949 end STB;
21950 @end smallexample
21952 @smallexample
21953 $ gnatmake -g .\stb -bargs -E
21954 $ stb
21956 0040149F in stb.p1 at stb.adb:8
21957 004014B7 in stb.p2 at stb.adb:13
21958 004014CF in stb.p3 at stb.adb:18
21959 004015DD in ada.stb at stb.adb:22
21960 00401461 in main at b~stb.adb:168
21961 004011C4 in __mingw_CRTStartup at crt1.c:200
21962 004011F1 in mainCRTStartup at crt1.c:222
21963 77E892A4 in ?? at ??:0
21964 @end smallexample
21966 @noindent
21967 In the above example the ``.\'' syntax in the @command{gnatmake} command
21968 is currently required by @command{addr2line} for files that are in
21969 the current working directory.
21970 Moreover, the exact sequence of linker options may vary from platform
21971 to platform.
21972 The above @option{-largs} section is for Windows platforms. By contrast,
21973 under Unix there is no need for the @option{-largs} section.
21974 Differences across platforms are due to details of linker implementation.
21976 @node Tracebacks From Anywhere in a Program (symbolic)
21977 @subsubsection Tracebacks From Anywhere in a Program
21979 @noindent
21980 It is possible to get a symbolic stack traceback
21981 from anywhere in a program, just as for non-symbolic tracebacks.
21982 The first step is to obtain a non-symbolic
21983 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21984 information. Here is an example:
21986 @smallexample @c ada
21987 with Ada.Text_IO;
21988 with GNAT.Traceback;
21989 with GNAT.Traceback.Symbolic;
21991 procedure STB is
21993    use Ada;
21994    use GNAT.Traceback;
21995    use GNAT.Traceback.Symbolic;
21997    procedure P1 is
21998       TB  : Tracebacks_Array (1 .. 10);
21999       --  We are asking for a maximum of 10 stack frames.
22000       Len : Natural;
22001       --  Len will receive the actual number of stack frames returned.
22002    begin
22003       Call_Chain (TB, Len);
22004       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22005    end P1;
22007    procedure P2 is
22008    begin
22009       P1;
22010    end P2;
22012 begin
22013    P2;
22014 end STB;
22015 @end smallexample
22017 @c ******************************
22018 @ifset vms
22019 @node Compatibility with HP Ada
22020 @chapter Compatibility with HP Ada
22021 @cindex Compatibility
22023 @noindent
22024 @cindex DEC Ada
22025 @cindex HP Ada
22026 @cindex Compatibility between GNAT and HP Ada
22027 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22028 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22029 GNAT is highly compatible
22030 with HP Ada, and it should generally be straightforward to port code
22031 from the HP Ada environment to GNAT. However, there are a few language
22032 and implementation differences of which the user must be aware. These
22033 differences are discussed in this chapter. In
22034 addition, the operating environment and command structure for the
22035 compiler are different, and these differences are also discussed.
22037 For further details on these and other compatibility issues,
22038 see Appendix E of the HP publication
22039 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22041 Except where otherwise indicated, the description of GNAT for OpenVMS
22042 applies to both the Alpha and I64 platforms.
22044 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22045 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22047 The discussion in this chapter addresses specifically the implementation
22048 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22049 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22050 GNAT always follows the Alpha implementation.
22052 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22053 attributes are recognized, although only a subset of them can sensibly
22054 be implemented.  The description of pragmas in
22055 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
22056 indicates whether or not they are applicable to non-VMS systems.
22058 @menu
22059 * Ada Language Compatibility::
22060 * Differences in the Definition of Package System::
22061 * Language-Related Features::
22062 * The Package STANDARD::
22063 * The Package SYSTEM::
22064 * Tasking and Task-Related Features::
22065 * Pragmas and Pragma-Related Features::
22066 * Library of Predefined Units::
22067 * Bindings::
22068 * Main Program Definition::
22069 * Implementation-Defined Attributes::
22070 * Compiler and Run-Time Interfacing::
22071 * Program Compilation and Library Management::
22072 * Input-Output::
22073 * Implementation Limits::
22074 * Tools and Utilities::
22075 @end menu
22077 @node Ada Language Compatibility
22078 @section Ada Language Compatibility
22080 @noindent
22081 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
22082 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
22083 with Ada 83, and therefore Ada 83 programs will compile
22084 and run under GNAT with
22085 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
22086 provides details on specific incompatibilities.
22088 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
22089 as well as the pragma @code{ADA_83}, to force the compiler to
22090 operate in Ada 83 mode. This mode does not guarantee complete
22091 conformance to Ada 83, but in practice is sufficient to
22092 eliminate most sources of incompatibilities.
22093 In particular, it eliminates the recognition of the
22094 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
22095 in Ada 83 programs is legal, and handles the cases of packages
22096 with optional bodies, and generics that instantiate unconstrained
22097 types without the use of @code{(<>)}.
22099 @node Differences in the Definition of Package System
22100 @section Differences in the Definition of Package @code{System}
22102 @noindent
22103 An Ada compiler is allowed to add
22104 implementation-dependent declarations to package @code{System}.
22105 In normal mode,
22106 GNAT does not take advantage of this permission, and the version of
22107 @code{System} provided by GNAT exactly matches that defined in the Ada
22108 Reference Manual.
22110 However, HP Ada adds an extensive set of declarations to package
22111 @code{System},
22112 as fully documented in the HP Ada manuals. To minimize changes required
22113 for programs that make use of these extensions, GNAT provides the pragma
22114 @code{Extend_System} for extending the definition of package System. By using:
22115 @cindex pragma @code{Extend_System}
22116 @cindex @code{Extend_System} pragma
22118 @smallexample @c ada
22119 @group
22120 @cartouche
22121 pragma Extend_System (Aux_DEC);
22122 @end cartouche
22123 @end group
22124 @end smallexample
22126 @noindent
22127 the set of definitions in @code{System} is extended to include those in
22128 package @code{System.Aux_DEC}.
22129 @cindex @code{System.Aux_DEC} package
22130 @cindex @code{Aux_DEC} package (child of @code{System})
22131 These definitions are incorporated directly into package @code{System},
22132 as though they had been declared there. For a
22133 list of the declarations added, see the spec of this package,
22134 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
22135 @cindex @file{s-auxdec.ads} file
22136 The pragma @code{Extend_System} is a configuration pragma, which means that
22137 it can be placed in the file @file{gnat.adc}, so that it will automatically
22138 apply to all subsequent compilations. See @ref{Configuration Pragmas},
22139 for further details.
22141 An alternative approach that avoids the use of the non-standard
22142 @code{Extend_System} pragma is to add a context clause to the unit that
22143 references these facilities:
22145 @smallexample @c ada
22146 @cartouche
22147 with System.Aux_DEC;
22148 use  System.Aux_DEC;
22149 @end cartouche
22150 @end smallexample
22152 @noindent
22153 The effect is not quite semantically identical to incorporating
22154 the declarations directly into package @code{System},
22155 but most programs will not notice a difference
22156 unless they use prefix notation (e.g.@: @code{System.Integer_8})
22157 to reference the entities directly in package @code{System}.
22158 For units containing such references,
22159 the prefixes must either be removed, or the pragma @code{Extend_System}
22160 must be used.
22162 @node Language-Related Features
22163 @section Language-Related Features
22165 @noindent
22166 The following sections highlight differences in types,
22167 representations of types, operations, alignment, and
22168 related topics.
22170 @menu
22171 * Integer Types and Representations::
22172 * Floating-Point Types and Representations::
22173 * Pragmas Float_Representation and Long_Float::
22174 * Fixed-Point Types and Representations::
22175 * Record and Array Component Alignment::
22176 * Address Clauses::
22177 * Other Representation Clauses::
22178 @end menu
22180 @node Integer Types and Representations
22181 @subsection Integer Types and Representations
22183 @noindent
22184 The set of predefined integer types is identical in HP Ada and GNAT.
22185 Furthermore the representation of these integer types is also identical,
22186 including the capability of size clauses forcing biased representation.
22188 In addition,
22189 HP Ada for OpenVMS Alpha systems has defined the
22190 following additional integer types in package @code{System}:
22192 @itemize @bullet
22194 @item
22195 @code{INTEGER_8}
22197 @item
22198 @code{INTEGER_16}
22200 @item
22201 @code{INTEGER_32}
22203 @item
22204 @code{INTEGER_64}
22206 @item
22207 @code{LARGEST_INTEGER}
22208 @end itemize
22210 @noindent
22211 In GNAT, the first four of these types may be obtained from the
22212 standard Ada package @code{Interfaces}.
22213 Alternatively, by use of the pragma @code{Extend_System}, identical
22214 declarations can be referenced directly in package @code{System}.
22215 On both GNAT and HP Ada, the maximum integer size is 64 bits.
22217 @node Floating-Point Types and Representations
22218 @subsection Floating-Point Types and Representations
22219 @cindex Floating-Point types
22221 @noindent
22222 The set of predefined floating-point types is identical in HP Ada and GNAT.
22223 Furthermore the representation of these floating-point
22224 types is also identical. One important difference is that the default
22225 representation for HP Ada is @code{VAX_Float}, but the default representation
22226 for GNAT is IEEE.
22228 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22229 pragma @code{Float_Representation} as described in the HP Ada
22230 documentation.
22231 For example, the declarations:
22233 @smallexample @c ada
22234 @cartouche
22235 type F_Float is digits 6;
22236 pragma Float_Representation (VAX_Float, F_Float);
22237 @end cartouche
22238 @end smallexample
22240 @noindent
22241 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22242 format.
22243 This set of declarations actually appears in @code{System.Aux_DEC},
22244 which contains
22245 the full set of additional floating-point declarations provided in
22246 the HP Ada version of package @code{System}.
22247 This and similar declarations may be accessed in a user program
22248 by using pragma @code{Extend_System}. The use of this
22249 pragma, and the related pragma @code{Long_Float} is described in further
22250 detail in the following section.
22252 @node Pragmas Float_Representation and Long_Float
22253 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22255 @noindent
22256 HP Ada provides the pragma @code{Float_Representation}, which
22257 acts as a program library switch to allow control over
22258 the internal representation chosen for the predefined
22259 floating-point types declared in the package @code{Standard}.
22260 The format of this pragma is as follows:
22262 @smallexample @c ada
22263 @cartouche
22264 pragma Float_Representation(VAX_Float | IEEE_Float);
22265 @end cartouche
22266 @end smallexample
22268 @noindent
22269 This pragma controls the representation of floating-point
22270 types as follows:
22272 @itemize @bullet
22273 @item
22274 @code{VAX_Float} specifies that floating-point
22275 types are represented by default with the VAX system hardware types
22276 @code{F-floating}, @code{D-floating}, @code{G-floating}.
22277 Note that the @code{H-floating}
22278 type was available only on VAX systems, and is not available
22279 in either HP Ada or GNAT.
22281 @item
22282 @code{IEEE_Float} specifies that floating-point
22283 types are represented by default with the IEEE single and
22284 double floating-point types.
22285 @end itemize
22287 @noindent
22288 GNAT provides an identical implementation of the pragma
22289 @code{Float_Representation}, except that it functions as a
22290 configuration pragma. Note that the
22291 notion of configuration pragma corresponds closely to the
22292 HP Ada notion of a program library switch.
22294 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22295 which is different
22296 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22297 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22298 advisable to change the format of numbers passed to standard library
22299 routines, and if necessary explicit type conversions may be needed.
22301 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22302 efficient, and (given that it conforms to an international standard)
22303 potentially more portable.
22304 The situation in which @code{VAX_Float} may be useful is in interfacing
22305 to existing code and data that expect the use of @code{VAX_Float}.
22306 In such a situation use the predefined @code{VAX_Float}
22307 types in package @code{System}, as extended by
22308 @code{Extend_System}. For example, use @code{System.F_Float}
22309 to specify the 32-bit @code{F-Float} format.
22311 @noindent
22312 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22313 to allow control over the internal representation chosen
22314 for the predefined type @code{Long_Float} and for floating-point
22315 type declarations with digits specified in the range 7 .. 15.
22316 The format of this pragma is as follows:
22318 @smallexample @c ada
22319 @cartouche
22320 pragma Long_Float (D_FLOAT | G_FLOAT);
22321 @end cartouche
22322 @end smallexample
22324 @node Fixed-Point Types and Representations
22325 @subsection Fixed-Point Types and Representations
22327 @noindent
22328 On HP Ada for OpenVMS Alpha systems, rounding is
22329 away from zero for both positive and negative numbers.
22330 Therefore, @code{+0.5} rounds to @code{1},
22331 and @code{-0.5} rounds to @code{-1}.
22333 On GNAT the results of operations
22334 on fixed-point types are in accordance with the Ada
22335 rules. In particular, results of operations on decimal
22336 fixed-point types are truncated.
22338 @node Record and Array Component Alignment
22339 @subsection Record and Array Component Alignment
22341 @noindent
22342 On HP Ada for OpenVMS Alpha, all non-composite components
22343 are aligned on natural boundaries. For example, 1-byte
22344 components are aligned on byte boundaries, 2-byte
22345 components on 2-byte boundaries, 4-byte components on 4-byte
22346 byte boundaries, and so on. The OpenVMS Alpha hardware
22347 runs more efficiently with naturally aligned data.
22349 On GNAT, alignment rules are compatible
22350 with HP Ada for OpenVMS Alpha.
22352 @node Address Clauses
22353 @subsection Address Clauses
22355 @noindent
22356 In HP Ada and GNAT, address clauses are supported for
22357 objects and imported subprograms.
22358 The predefined type @code{System.Address} is a private type
22359 in both compilers on Alpha OpenVMS, with the same representation
22360 (it is simply a machine pointer). Addition, subtraction, and comparison
22361 operations are available in the standard Ada package
22362 @code{System.Storage_Elements}, or in package @code{System}
22363 if it is extended to include @code{System.Aux_DEC} using a
22364 pragma @code{Extend_System} as previously described.
22366 Note that code that @code{with}'s both this extended package @code{System}
22367 and the package @code{System.Storage_Elements} should not @code{use}
22368 both packages, or ambiguities will result. In general it is better
22369 not to mix these two sets of facilities. The Ada package was
22370 designed specifically to provide the kind of features that HP Ada
22371 adds directly to package @code{System}.
22373 The type @code{System.Address} is a 64-bit integer type in GNAT for
22374 I64 OpenVMS.  For more information,
22375 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22377 GNAT is compatible with HP Ada in its handling of address
22378 clauses, except for some limitations in
22379 the form of address clauses for composite objects with
22380 initialization. Such address clauses are easily replaced
22381 by the use of an explicitly-defined constant as described
22382 in the Ada Reference Manual (13.1(22)). For example, the sequence
22383 of declarations:
22385 @smallexample @c ada
22386 @cartouche
22387 X, Y : Integer := Init_Func;
22388 Q : String (X .. Y) := "abc";
22389 @dots{}
22390 for Q'Address use Compute_Address;
22391 @end cartouche
22392 @end smallexample
22394 @noindent
22395 will be rejected by GNAT, since the address cannot be computed at the time
22396 that @code{Q} is declared. To achieve the intended effect, write instead:
22398 @smallexample @c ada
22399 @group
22400 @cartouche
22401 X, Y : Integer := Init_Func;
22402 Q_Address : constant Address := Compute_Address;
22403 Q : String (X .. Y) := "abc";
22404 @dots{}
22405 for Q'Address use Q_Address;
22406 @end cartouche
22407 @end group
22408 @end smallexample
22410 @noindent
22411 which will be accepted by GNAT (and other Ada compilers), and is also
22412 compatible with Ada 83. A fuller description of the restrictions
22413 on address specifications is found in @ref{Top, GNAT Reference Manual,
22414 About This Guide, gnat_rm, GNAT Reference Manual}.
22416 @node Other Representation Clauses
22417 @subsection Other Representation Clauses
22419 @noindent
22420 GNAT implements in a compatible manner all the representation
22421 clauses supported by HP Ada. In addition, GNAT
22422 implements the representation clause forms that were introduced in Ada 95,
22423 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22425 @node The Package STANDARD
22426 @section The Package @code{STANDARD}
22428 @noindent
22429 The package @code{STANDARD}, as implemented by HP Ada, is fully
22430 described in the @cite{Ada Reference Manual} and in the
22431 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22432 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22434 In addition, HP Ada supports the Latin-1 character set in
22435 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22436 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22437 the type @code{WIDE_CHARACTER}.
22439 The floating-point types supported by GNAT are those
22440 supported by HP Ada, but the defaults are different, and are controlled by
22441 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22443 @node The Package SYSTEM
22444 @section The Package @code{SYSTEM}
22446 @noindent
22447 HP Ada provides a specific version of the package
22448 @code{SYSTEM} for each platform on which the language is implemented.
22449 For the complete spec of the package @code{SYSTEM}, see
22450 Appendix F of the @cite{HP Ada Language Reference Manual}.
22452 On HP Ada, the package @code{SYSTEM} includes the following conversion
22453 functions:
22454 @itemize @bullet
22455 @item @code{TO_ADDRESS(INTEGER)}
22457 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22459 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22461 @item @code{TO_INTEGER(ADDRESS)}
22463 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22465 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22466 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22467 @end itemize
22469 @noindent
22470 By default, GNAT supplies a version of @code{SYSTEM} that matches
22471 the definition given in the @cite{Ada Reference Manual}.
22472 This
22473 is a subset of the HP system definitions, which is as
22474 close as possible to the original definitions. The only difference
22475 is that the definition of @code{SYSTEM_NAME} is different:
22477 @smallexample @c ada
22478 @cartouche
22479 type Name is (SYSTEM_NAME_GNAT);
22480 System_Name : constant Name := SYSTEM_NAME_GNAT;
22481 @end cartouche
22482 @end smallexample
22484 @noindent
22485 Also, GNAT adds the Ada declarations for
22486 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22488 However, the use of the following pragma causes GNAT
22489 to extend the definition of package @code{SYSTEM} so that it
22490 encompasses the full set of HP-specific extensions,
22491 including the functions listed above:
22493 @smallexample @c ada
22494 @cartouche
22495 pragma Extend_System (Aux_DEC);
22496 @end cartouche
22497 @end smallexample
22499 @noindent
22500 The pragma @code{Extend_System} is a configuration pragma that
22501 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22502 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22504 HP Ada does not allow the recompilation of the package
22505 @code{SYSTEM}. Instead HP Ada provides several pragmas
22506 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22507 to modify values in the package @code{SYSTEM}.
22508 On OpenVMS Alpha systems, the pragma
22509 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22510 its single argument.
22512 GNAT does permit the recompilation of package @code{SYSTEM} using
22513 the special switch @option{-gnatg}, and this switch can be used if
22514 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22515 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22516 or @code{MEMORY_SIZE} by any other means.
22518 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22519 enumeration literal @code{SYSTEM_NAME_GNAT}.
22521 The definitions provided by the use of
22523 @smallexample @c ada
22524 pragma Extend_System (AUX_Dec);
22525 @end smallexample
22527 @noindent
22528 are virtually identical to those provided by the HP Ada 83 package
22529 @code{SYSTEM}. One important difference is that the name of the
22530 @code{TO_ADDRESS}
22531 function for type @code{UNSIGNED_LONGWORD} is changed to
22532 @code{TO_ADDRESS_LONG}.
22533 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22534 discussion of why this change was necessary.
22536 @noindent
22537 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22538 is in fact
22539 an extension to Ada 83 not strictly compatible with the reference manual.
22540 GNAT, in order to be exactly compatible with the standard,
22541 does not provide this capability. In HP Ada 83, the
22542 point of this definition is to deal with a call like:
22544 @smallexample @c ada
22545 TO_ADDRESS (16#12777#);
22546 @end smallexample
22548 @noindent
22549 Normally, according to Ada 83 semantics, one would expect this to be
22550 ambiguous, since it matches both the @code{INTEGER} and
22551 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22552 However, in HP Ada 83, there is no ambiguity, since the
22553 definition using @i{universal_integer} takes precedence.
22555 In GNAT, since the version with @i{universal_integer} cannot be supplied,
22556 it is
22557 not possible to be 100% compatible. Since there are many programs using
22558 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22559 GNAT was
22560 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22561 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22563 @smallexample @c ada
22564 function To_Address (X : Integer) return Address;
22565 pragma Pure_Function (To_Address);
22567 function To_Address_Long (X : Unsigned_Longword) return Address;
22568 pragma Pure_Function (To_Address_Long);
22569 @end smallexample
22571 @noindent
22572 This means that programs using @code{TO_ADDRESS} for
22573 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22575 @node Tasking and Task-Related Features
22576 @section Tasking and Task-Related Features
22578 @noindent
22579 This section compares the treatment of tasking in GNAT
22580 and in HP Ada for OpenVMS Alpha.
22581 The GNAT description applies to both Alpha and I64 OpenVMS.
22582 For detailed information on tasking in
22583 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22584 relevant run-time reference manual.
22586 @menu
22587 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22588 * Assigning Task IDs::
22589 * Task IDs and Delays::
22590 * Task-Related Pragmas::
22591 * Scheduling and Task Priority::
22592 * The Task Stack::
22593 * External Interrupts::
22594 @end menu
22596 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22597 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22599 @noindent
22600 On OpenVMS Alpha systems, each Ada task (except a passive
22601 task) is implemented as a single stream of execution
22602 that is created and managed by the kernel. On these
22603 systems, HP Ada tasking support is based on DECthreads,
22604 an implementation of the POSIX standard for threads.
22606 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22607 code that calls DECthreads routines can be used together.
22608 The interaction between Ada tasks and DECthreads routines
22609 can have some benefits. For example when on OpenVMS Alpha,
22610 HP Ada can call C code that is already threaded.
22612 GNAT uses the facilities of DECthreads,
22613 and Ada tasks are mapped to threads.
22615 @node Assigning Task IDs
22616 @subsection Assigning Task IDs
22618 @noindent
22619 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
22620 the environment task that executes the main program. On
22621 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
22622 that have been created but are not yet activated.
22624 On OpenVMS Alpha systems, task IDs are assigned at
22625 activation. On GNAT systems, task IDs are also assigned at
22626 task creation but do not have the same form or values as
22627 task ID values in HP Ada. There is no null task, and the
22628 environment task does not have a specific task ID value.
22630 @node Task IDs and Delays
22631 @subsection Task IDs and Delays
22633 @noindent
22634 On OpenVMS Alpha systems, tasking delays are implemented
22635 using Timer System Services. The Task ID is used for the
22636 identification of the timer request (the @code{REQIDT} parameter).
22637 If Timers are used in the application take care not to use
22638 @code{0} for the identification, because cancelling such a timer
22639 will cancel all timers and may lead to unpredictable results.
22641 @node Task-Related Pragmas
22642 @subsection Task-Related Pragmas
22644 @noindent
22645 Ada supplies the pragma @code{TASK_STORAGE}, which allows
22646 specification of the size of the guard area for a task
22647 stack. (The guard area forms an area of memory that has no
22648 read or write access and thus helps in the detection of
22649 stack overflow.) On OpenVMS Alpha systems, if the pragma
22650 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
22651 area is created. In the absence of a pragma @code{TASK_STORAGE},
22652 a default guard area is created.
22654 GNAT supplies the following task-related pragmas:
22656 @itemize @bullet
22657 @item  @code{TASK_INFO}
22659 This pragma appears within a task definition and
22660 applies to the task in which it appears. The argument
22661 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
22663 @item  @code{TASK_STORAGE}
22665 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
22666 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
22667 @code{SUPPRESS}, and @code{VOLATILE}.
22668 @end itemize
22669 @node Scheduling and Task Priority
22670 @subsection Scheduling and Task Priority
22672 @noindent
22673 HP Ada implements the Ada language requirement that
22674 when two tasks are eligible for execution and they have
22675 different priorities, the lower priority task does not
22676 execute while the higher priority task is waiting. The HP
22677 Ada Run-Time Library keeps a task running until either the
22678 task is suspended or a higher priority task becomes ready.
22680 On OpenVMS Alpha systems, the default strategy is round-
22681 robin with preemption. Tasks of equal priority take turns
22682 at the processor. A task is run for a certain period of
22683 time and then placed at the tail of the ready queue for
22684 its priority level.
22686 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
22687 which can be used to enable or disable round-robin
22688 scheduling of tasks with the same priority.
22689 See the relevant HP Ada run-time reference manual for
22690 information on using the pragmas to control HP Ada task
22691 scheduling.
22693 GNAT follows the scheduling rules of Annex D (Real-Time
22694 Annex) of the @cite{Ada Reference Manual}. In general, this
22695 scheduling strategy is fully compatible with HP Ada
22696 although it provides some additional constraints (as
22697 fully documented in Annex D).
22698 GNAT implements time slicing control in a manner compatible with
22699 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
22700 are identical to the HP Ada 83 pragma of the same name.
22701 Note that it is not possible to mix GNAT tasking and
22702 HP Ada 83 tasking in the same program, since the two run-time
22703 libraries are not compatible.
22705 @node The Task Stack
22706 @subsection The Task Stack
22708 @noindent
22709 In HP Ada, a task stack is allocated each time a
22710 non-passive task is activated. As soon as the task is
22711 terminated, the storage for the task stack is deallocated.
22712 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
22713 a default stack size is used. Also, regardless of the size
22714 specified, some additional space is allocated for task
22715 management purposes. On OpenVMS Alpha systems, at least
22716 one page is allocated.
22718 GNAT handles task stacks in a similar manner. In accordance with
22719 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
22720 an alternative method for controlling the task stack size.
22721 The specification of the attribute @code{T'STORAGE_SIZE} is also
22722 supported in a manner compatible with HP Ada.
22724 @node External Interrupts
22725 @subsection External Interrupts
22727 @noindent
22728 On HP Ada, external interrupts can be associated with task entries.
22729 GNAT is compatible with HP Ada in its handling of external interrupts.
22731 @node Pragmas and Pragma-Related Features
22732 @section Pragmas and Pragma-Related Features
22734 @noindent
22735 Both HP Ada and GNAT supply all language-defined pragmas
22736 as specified by the Ada 83 standard. GNAT also supplies all
22737 language-defined pragmas introduced by Ada 95 and Ada 2005.
22738 In addition, GNAT implements the implementation-defined pragmas
22739 from HP Ada 83.
22741 @itemize @bullet
22742 @item  @code{AST_ENTRY}
22744 @item  @code{COMMON_OBJECT}
22746 @item  @code{COMPONENT_ALIGNMENT}
22748 @item  @code{EXPORT_EXCEPTION}
22750 @item  @code{EXPORT_FUNCTION}
22752 @item  @code{EXPORT_OBJECT}
22754 @item  @code{EXPORT_PROCEDURE}
22756 @item  @code{EXPORT_VALUED_PROCEDURE}
22758 @item  @code{FLOAT_REPRESENTATION}
22760 @item  @code{IDENT}
22762 @item  @code{IMPORT_EXCEPTION}
22764 @item  @code{IMPORT_FUNCTION}
22766 @item  @code{IMPORT_OBJECT}
22768 @item  @code{IMPORT_PROCEDURE}
22770 @item  @code{IMPORT_VALUED_PROCEDURE}
22772 @item  @code{INLINE_GENERIC}
22774 @item  @code{INTERFACE_NAME}
22776 @item  @code{LONG_FLOAT}
22778 @item  @code{MAIN_STORAGE}
22780 @item  @code{PASSIVE}
22782 @item  @code{PSECT_OBJECT}
22784 @item  @code{SHARE_GENERIC}
22786 @item  @code{SUPPRESS_ALL}
22788 @item  @code{TASK_STORAGE}
22790 @item  @code{TIME_SLICE}
22792 @item  @code{TITLE}
22793 @end itemize
22795 @noindent
22796 These pragmas are all fully implemented, with the exception of @code{TITLE},
22797 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
22798 recognized, but which have no
22799 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
22800 use of Ada protected objects. In GNAT, all generics are inlined.
22802 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
22803 a separate subprogram specification which must appear before the
22804 subprogram body.
22806 GNAT also supplies a number of implementation-defined pragmas including the
22807 following:
22809 @itemize @bullet
22810 @item  @code{ABORT_DEFER}
22812 @item  @code{ADA_83}
22814 @item  @code{ADA_95}
22816 @item  @code{ADA_05}
22818 @item  @code{Ada_2005}
22820 @item  @code{Ada_12}
22822 @item  @code{Ada_2012}
22824 @item  @code{ANNOTATE}
22826 @item  @code{ASSERT}
22828 @item  @code{C_PASS_BY_COPY}
22830 @item  @code{CPP_CLASS}
22832 @item  @code{CPP_CONSTRUCTOR}
22834 @item  @code{CPP_DESTRUCTOR}
22836 @item  @code{DEBUG}
22838 @item  @code{EXTEND_SYSTEM}
22840 @item  @code{LINKER_ALIAS}
22842 @item  @code{LINKER_SECTION}
22844 @item  @code{MACHINE_ATTRIBUTE}
22846 @item  @code{NO_RETURN}
22848 @item  @code{PURE_FUNCTION}
22850 @item  @code{SOURCE_FILE_NAME}
22852 @item  @code{SOURCE_REFERENCE}
22854 @item  @code{TASK_INFO}
22856 @item  @code{UNCHECKED_UNION}
22858 @item  @code{UNIMPLEMENTED_UNIT}
22860 @item  @code{UNIVERSAL_DATA}
22862 @item  @code{UNSUPPRESS}
22864 @item  @code{WARNINGS}
22866 @item  @code{WEAK_EXTERNAL}
22867 @end itemize
22869 @noindent
22870 For full details on these and other GNAT implementation-defined pragmas,
22871 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
22872 Manual}.
22874 @menu
22875 * Restrictions on the Pragma INLINE::
22876 * Restrictions on the Pragma INTERFACE::
22877 * Restrictions on the Pragma SYSTEM_NAME::
22878 @end menu
22880 @node Restrictions on the Pragma INLINE
22881 @subsection Restrictions on Pragma @code{INLINE}
22883 @noindent
22884 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
22885 @itemize @bullet
22886 @item  Parameters cannot have a task type.
22888 @item  Function results cannot be task types, unconstrained
22889 array types, or unconstrained types with discriminants.
22891 @item  Bodies cannot declare the following:
22892 @itemize @bullet
22893 @item  Subprogram body or stub (imported subprogram is allowed)
22895 @item  Tasks
22897 @item  Generic declarations
22899 @item  Instantiations
22901 @item  Exceptions
22903 @item  Access types (types derived from access types allowed)
22905 @item  Array or record types
22907 @item  Dependent tasks
22909 @item  Direct recursive calls of subprogram or containing
22910 subprogram, directly or via a renaming
22912 @end itemize
22913 @end itemize
22915 @noindent
22916 In GNAT, the only restriction on pragma @code{INLINE} is that the
22917 body must occur before the call if both are in the same
22918 unit, and the size must be appropriately small. There are
22919 no other specific restrictions which cause subprograms to
22920 be incapable of being inlined.
22922 @node  Restrictions on the Pragma INTERFACE
22923 @subsection  Restrictions on Pragma @code{INTERFACE}
22925 @noindent
22926 The following restrictions on pragma @code{INTERFACE}
22927 are enforced by both HP Ada and GNAT:
22928 @itemize @bullet
22929 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
22930 Default is the default on OpenVMS Alpha systems.
22932 @item  Parameter passing: Language specifies default
22933 mechanisms but can be overridden with an @code{EXPORT} pragma.
22935 @itemize @bullet
22936 @item  Ada: Use internal Ada rules.
22938 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
22939 record or task type. Result cannot be a string, an
22940 array, or a record.
22942 @item  Fortran: Parameters cannot have a task type. Result cannot
22943 be a string, an array, or a record.
22944 @end itemize
22945 @end itemize
22947 @noindent
22948 GNAT is entirely upwards compatible with HP Ada, and in addition allows
22949 record parameters for all languages.
22951 @node  Restrictions on the Pragma SYSTEM_NAME
22952 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
22954 @noindent
22955 For HP Ada for OpenVMS Alpha, the enumeration literal
22956 for the type @code{NAME} is @code{OPENVMS_AXP}.
22957 In GNAT, the enumeration
22958 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
22960 @node  Library of Predefined Units
22961 @section  Library of Predefined Units
22963 @noindent
22964 A library of predefined units is provided as part of the
22965 HP Ada and GNAT implementations. HP Ada does not provide
22966 the package @code{MACHINE_CODE} but instead recommends importing
22967 assembler code.
22969 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
22970 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
22971 version.
22972 The HP Ada Predefined Library units are modified to remove post-Ada 83
22973 incompatibilities and to make them interoperable with GNAT
22974 (@pxref{Changes to DECLIB}, for details).
22975 The units are located in the @file{DECLIB} directory.
22977 The GNAT RTL is contained in
22978 the @file{ADALIB} directory, and
22979 the default search path is set up to find @code{DECLIB} units in preference
22980 to @code{ADALIB} units with the same name (@code{TEXT_IO},
22981 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
22983 @menu
22984 * Changes to DECLIB::
22985 @end menu
22987 @node Changes to DECLIB
22988 @subsection Changes to @code{DECLIB}
22990 @noindent
22991 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
22992 compatibility are minor and include the following:
22994 @itemize @bullet
22995 @item  Adjusting the location of pragmas and record representation
22996 clauses to obey Ada 95 (and thus Ada 2005) rules
22998 @item  Adding the proper notation to generic formal parameters
22999 that take unconstrained types in instantiation
23001 @item  Adding pragma @code{ELABORATE_BODY} to package specs
23002 that have package bodies not otherwise allowed
23004 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23005 ``@code{PROTECTD}''.
23006 Currently these are found only in the @code{STARLET} package spec.
23008 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23009 where the address size is constrained to 32 bits.
23010 @end itemize
23012 @noindent
23013 None of the above changes is visible to users.
23015 @node Bindings
23016 @section Bindings
23018 @noindent
23019 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23020 @itemize @bullet
23022 @item  Command Language Interpreter (CLI interface)
23024 @item  DECtalk Run-Time Library (DTK interface)
23026 @item  Librarian utility routines (LBR interface)
23028 @item  General Purpose Run-Time Library (LIB interface)
23030 @item  Math Run-Time Library (MTH interface)
23032 @item  National Character Set Run-Time Library (NCS interface)
23034 @item  Compiled Code Support Run-Time Library (OTS interface)
23036 @item  Parallel Processing Run-Time Library (PPL interface)
23038 @item  Screen Management Run-Time Library (SMG interface)
23040 @item  Sort Run-Time Library (SOR interface)
23042 @item  String Run-Time Library (STR interface)
23044 @item STARLET System Library
23045 @findex Starlet
23047 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
23049 @item  X Windows Toolkit (XT interface)
23051 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
23052 @end itemize
23054 @noindent
23055 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23056 directory, on both the Alpha and I64 OpenVMS platforms.
23058 The X components of DECLIB compatibility package are located in a separate
23059 library, called XDECGNAT, which is not linked with by default; this library
23060 must be explicitly linked with any application that makes use of any X facilities,
23061 with a command similar to
23063 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
23065 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23066 in the
23067 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23068 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23069 @code{Xt}, and @code{X_Lib}
23070 causing the default X/Motif sharable image libraries to be linked in. This
23071 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23072 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23074 It may be necessary to edit these options files to update or correct the
23075 library names if, for example, the newer X/Motif bindings from
23076 @file{ADA$EXAMPLES}
23077 had been (previous to installing GNAT) copied and renamed to supersede the
23078 default @file{ADA$PREDEFINED} versions.
23080 @menu
23081 * Shared Libraries and Options Files::
23082 * Interfaces to C::
23083 @end menu
23085 @node Shared Libraries and Options Files
23086 @subsection Shared Libraries and Options Files
23088 @noindent
23089 When using the HP Ada
23090 predefined X and Motif bindings, the linking with their sharable images is
23091 done automatically by @command{GNAT LINK}.
23092 When using other X and Motif bindings, you need
23093 to add the corresponding sharable images to the command line for
23094 @code{GNAT LINK}. When linking with shared libraries, or with
23095 @file{.OPT} files, you must
23096 also add them to the command line for @command{GNAT LINK}.
23098 A shared library to be used with GNAT is built in the same way as other
23099 libraries under VMS. The VMS Link command can be used in standard fashion.
23101 @node Interfaces to C
23102 @subsection Interfaces to C
23104 @noindent
23105 HP Ada
23106 provides the following Ada types and operations:
23108 @itemize @bullet
23109 @item C types package (@code{C_TYPES})
23111 @item C strings (@code{C_TYPES.NULL_TERMINATED})
23113 @item Other_types (@code{SHORT_INT})
23114 @end itemize
23116 @noindent
23117 Interfacing to C with GNAT, you can use the above approach
23118 described for HP Ada or the facilities of Annex B of
23119 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
23120 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
23121 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
23123 The @option{-gnatF} qualifier forces default and explicit
23124 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
23125 to be uppercased for compatibility with the default behavior
23126 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
23128 @node Main Program Definition
23129 @section Main Program Definition
23131 @noindent
23132 The following section discusses differences in the
23133 definition of main programs on HP Ada and GNAT.
23134 On HP Ada, main programs are defined to meet the
23135 following conditions:
23136 @itemize @bullet
23137 @item  Procedure with no formal parameters (returns @code{0} upon
23138 normal completion)
23140 @item  Procedure with no formal parameters (returns @code{42} when
23141 an unhandled exception is raised)
23143 @item  Function with no formal parameters whose returned value
23144 is of a discrete type
23146 @item  Procedure with one @code{out} formal of a discrete type for
23147 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
23149 @end itemize
23151 @noindent
23152 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
23153 a main function or main procedure returns a discrete
23154 value whose size is less than 64 bits (32 on VAX systems),
23155 the value is zero- or sign-extended as appropriate.
23156 On GNAT, main programs are defined as follows:
23157 @itemize @bullet
23158 @item  Must be a non-generic, parameterless subprogram that
23159 is either a procedure or function returning an Ada
23160 @code{STANDARD.INTEGER} (the predefined type)
23162 @item  Cannot be a generic subprogram or an instantiation of a
23163 generic subprogram
23164 @end itemize
23166 @node Implementation-Defined Attributes
23167 @section Implementation-Defined Attributes
23169 @noindent
23170 GNAT provides all HP Ada implementation-defined
23171 attributes.
23173 @node Compiler and Run-Time Interfacing
23174 @section Compiler and Run-Time Interfacing
23176 @noindent
23177 HP Ada provides the following qualifiers to pass options to the linker
23178 (ACS LINK):
23179 @itemize @bullet
23180 @item  @option{/WAIT} and @option{/SUBMIT}
23182 @item  @option{/COMMAND}
23184 @item  @option{/@r{[}NO@r{]}MAP}
23186 @item  @option{/OUTPUT=@var{file-spec}}
23188 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23189 @end itemize
23191 @noindent
23192 To pass options to the linker, GNAT provides the following
23193 switches:
23195 @itemize @bullet
23196 @item   @option{/EXECUTABLE=@var{exec-name}}
23198 @item   @option{/VERBOSE}
23200 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23201 @end itemize
23203 @noindent
23204 For more information on these switches, see
23205 @ref{Switches for gnatlink}.
23206 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23207 to control optimization. HP Ada also supplies the
23208 following pragmas:
23209 @itemize @bullet
23210 @item  @code{OPTIMIZE}
23212 @item  @code{INLINE}
23214 @item  @code{INLINE_GENERIC}
23216 @item  @code{SUPPRESS_ALL}
23218 @item  @code{PASSIVE}
23219 @end itemize
23221 @noindent
23222 In GNAT, optimization is controlled strictly by command
23223 line parameters, as described in the corresponding section of this guide.
23224 The HP pragmas for control of optimization are
23225 recognized but ignored.
23227 Note that in GNAT, the default is optimization off, whereas in HP Ada
23228 the default is that optimization is turned on.
23230 @node Program Compilation and Library Management
23231 @section Program Compilation and Library Management
23233 @noindent
23234 HP Ada and GNAT provide a comparable set of commands to
23235 build programs. HP Ada also provides a program library,
23236 which is a concept that does not exist on GNAT. Instead,
23237 GNAT provides directories of sources that are compiled as
23238 needed.
23240 The following table summarizes
23241 the HP Ada commands and provides
23242 equivalent GNAT commands. In this table, some GNAT
23243 equivalents reflect the fact that GNAT does not use the
23244 concept of a program library. Instead, it uses a model
23245 in which collections of source and object files are used
23246 in a manner consistent with other languages like C and
23247 Fortran. Therefore, standard system file commands are used
23248 to manipulate these elements. Those GNAT commands are marked with
23249 an asterisk.
23250 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23252 @need 1500
23253 @multitable @columnfractions .35 .65
23255 @item @emph{HP Ada Command}
23256 @tab @emph{GNAT Equivalent / Description}
23258 @item @command{ADA}
23259 @tab @command{GNAT COMPILE}@*
23260 Invokes the compiler to compile one or more Ada source files.
23262 @item @command{ACS ATTACH}@*
23263 @tab [No equivalent]@*
23264 Switches control of terminal from current process running the program
23265 library manager.
23267 @item @command{ACS CHECK}
23268 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23269 Forms the execution closure of one
23270 or more compiled units and checks completeness and currency.
23272 @item @command{ACS COMPILE}
23273 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23274 Forms the execution closure of one or
23275 more specified units, checks completeness and currency,
23276 identifies units that have revised source files, compiles same,
23277 and recompiles units that are or will become obsolete.
23278 Also completes incomplete generic instantiations.
23280 @item @command{ACS COPY FOREIGN}
23281 @tab Copy (*)@*
23282 Copies a foreign object file into the program library as a
23283 library unit body.
23285 @item @command{ACS COPY UNIT}
23286 @tab Copy (*)@*
23287 Copies a compiled unit from one program library to another.
23289 @item @command{ACS CREATE LIBRARY}
23290 @tab Create /directory (*)@*
23291 Creates a program library.
23293 @item @command{ACS CREATE SUBLIBRARY}
23294 @tab Create /directory (*)@*
23295 Creates a program sublibrary.
23297 @item @command{ACS DELETE LIBRARY}
23298 @tab @*
23299 Deletes a program library and its contents.
23301 @item @command{ACS DELETE SUBLIBRARY}
23302 @tab @*
23303 Deletes a program sublibrary and its contents.
23305 @item @command{ACS DELETE UNIT}
23306 @tab Delete file (*)@*
23307 On OpenVMS systems, deletes one or more compiled units from
23308 the current program library.
23310 @item @command{ACS DIRECTORY}
23311 @tab Directory (*)@*
23312 On OpenVMS systems, lists units contained in the current
23313 program library.
23315 @item @command{ACS ENTER FOREIGN}
23316 @tab Copy (*)@*
23317 Allows the import of a foreign body as an Ada library
23318 spec and enters a reference to a pointer.
23320 @item @command{ACS ENTER UNIT}
23321 @tab Copy (*)@*
23322 Enters a reference (pointer) from the current program library to
23323 a unit compiled into another program library.
23325 @item @command{ACS EXIT}
23326 @tab [No equivalent]@*
23327 Exits from the program library manager.
23329 @item @command{ACS EXPORT}
23330 @tab Copy (*)@*
23331 Creates an object file that contains system-specific object code
23332 for one or more units. With GNAT, object files can simply be copied
23333 into the desired directory.
23335 @item @command{ACS EXTRACT SOURCE}
23336 @tab Copy (*)@*
23337 Allows access to the copied source file for each Ada compilation unit
23339 @item @command{ACS HELP}
23340 @tab @command{HELP GNAT}@*
23341 Provides online help.
23343 @item @command{ACS LINK}
23344 @tab @command{GNAT LINK}@*
23345 Links an object file containing Ada units into an executable file.
23347 @item @command{ACS LOAD}
23348 @tab Copy (*)@*
23349 Loads (partially compiles) Ada units into the program library.
23350 Allows loading a program from a collection of files into a library
23351 without knowing the relationship among units.
23353 @item @command{ACS MERGE}
23354 @tab Copy (*)@*
23355 Merges into the current program library, one or more units from
23356 another library where they were modified.
23358 @item @command{ACS RECOMPILE}
23359 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23360 Recompiles from   external or copied source files any obsolete
23361 unit in the closure. Also, completes any incomplete generic
23362 instantiations.
23364 @item @command{ACS REENTER}
23365 @tab @command{GNAT MAKE}@*
23366 Reenters current references to units compiled after last entered
23367 with the @command{ACS ENTER UNIT} command.
23369 @item @command{ACS SET LIBRARY}
23370 @tab Set default (*)@*
23371 Defines a program library to be the compilation context as well
23372 as the target library for compiler output and commands in general.
23374 @item @command{ACS SET PRAGMA}
23375 @tab Edit @file{gnat.adc} (*)@*
23376 Redefines specified  values of the library characteristics
23377 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23378 and @code{Float_Representation}.
23380 @item @command{ACS SET SOURCE}
23381 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23382 Defines the source file search list for the @command{ACS COMPILE} command.
23384 @item @command{ACS SHOW LIBRARY}
23385 @tab Directory (*)@*
23386 Lists information about one or more program libraries.
23388 @item @command{ACS SHOW PROGRAM}
23389 @tab [No equivalent]@*
23390 Lists information about the execution closure of one or
23391 more units in the program library.
23393 @item @command{ACS SHOW SOURCE}
23394 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23395 Shows the source file search used when compiling units.
23397 @item @command{ACS SHOW VERSION}
23398 @tab Compile with @option{VERBOSE} option
23399 Displays the version number of the compiler and program library
23400 manager used.
23402 @item @command{ACS SPAWN}
23403 @tab [No equivalent]@*
23404 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23405 command).
23407 @item @command{ACS VERIFY}
23408 @tab [No equivalent]@*
23409 Performs a series of consistency checks on a program library to
23410 determine whether the library structure and library files are in
23411 valid form.
23412 @end multitable
23414 @noindent
23416 @node Input-Output
23417 @section Input-Output
23419 @noindent
23420 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23421 Management Services (RMS) to perform operations on
23422 external files.
23424 @noindent
23425 HP Ada and GNAT predefine an identical set of input-
23426 output packages. To make the use of the
23427 generic @code{TEXT_IO} operations more convenient, HP Ada
23428 provides predefined library packages that instantiate the
23429 integer and floating-point operations for the predefined
23430 integer and floating-point types as shown in the following table.
23432 @multitable @columnfractions .45 .55
23433 @item @emph{Package Name} @tab Instantiation
23435 @item @code{INTEGER_TEXT_IO}
23436 @tab @code{INTEGER_IO(INTEGER)}
23438 @item @code{SHORT_INTEGER_TEXT_IO}
23439 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23441 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23442 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23444 @item @code{FLOAT_TEXT_IO}
23445 @tab @code{FLOAT_IO(FLOAT)}
23447 @item @code{LONG_FLOAT_TEXT_IO}
23448 @tab @code{FLOAT_IO(LONG_FLOAT)}
23449 @end multitable
23451 @noindent
23452 The HP Ada predefined packages and their operations
23453 are implemented using OpenVMS Alpha files and input-output
23454 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23455 Familiarity with the following is recommended:
23456 @itemize @bullet
23457 @item  RMS file organizations and access methods
23459 @item  OpenVMS file specifications and directories
23461 @item  OpenVMS File Definition Language (FDL)
23462 @end itemize
23464 @noindent
23465 GNAT provides I/O facilities that are completely
23466 compatible with HP Ada. The distribution includes the
23467 standard HP Ada versions of all I/O packages, operating
23468 in a manner compatible with HP Ada. In particular, the
23469 following packages are by default the HP Ada (Ada 83)
23470 versions of these packages rather than the renamings
23471 suggested in Annex J of the Ada Reference Manual:
23472 @itemize @bullet
23473 @item  @code{TEXT_IO}
23475 @item  @code{SEQUENTIAL_IO}
23477 @item  @code{DIRECT_IO}
23478 @end itemize
23480 @noindent
23481 The use of the standard child package syntax (for
23482 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23483 packages.
23484 GNAT provides HP-compatible predefined instantiations
23485 of the @code{TEXT_IO} packages, and also
23486 provides the standard predefined instantiations required
23487 by the @cite{Ada Reference Manual}.
23489 For further information on how GNAT interfaces to the file
23490 system or how I/O is implemented in programs written in
23491 mixed languages, see @ref{Implementation of the Standard I/O,,,
23492 gnat_rm, GNAT Reference Manual}.
23493 This chapter covers the following:
23494 @itemize @bullet
23495 @item  Standard I/O packages
23497 @item  @code{FORM} strings
23499 @item  @code{ADA.DIRECT_IO}
23501 @item  @code{ADA.SEQUENTIAL_IO}
23503 @item  @code{ADA.TEXT_IO}
23505 @item  Stream pointer positioning
23507 @item  Reading and writing non-regular files
23509 @item  @code{GET_IMMEDIATE}
23511 @item  Treating @code{TEXT_IO} files as streams
23513 @item  Shared files
23515 @item  Open modes
23516 @end itemize
23518 @node Implementation Limits
23519 @section Implementation Limits
23521 @noindent
23522 The following table lists implementation limits for HP Ada
23523 and GNAT systems.
23524 @multitable @columnfractions .60 .20 .20
23525 @sp 1
23526 @item  @emph{Compilation Parameter}
23527 @tab   @emph{HP Ada}
23528 @tab   @emph{GNAT}
23529 @sp 1
23531 @item  In a subprogram or entry  declaration, maximum number of
23532 formal parameters that are of an unconstrained record type
23533 @tab   32
23534 @tab   No set limit
23535 @sp 1
23537 @item  Maximum identifier length (number of characters)
23538 @tab   255
23539 @tab   32766
23540 @sp 1
23542 @item  Maximum number of characters in a source line
23543 @tab   255
23544 @tab   32766
23545 @sp 1
23547 @item  Maximum collection size   (number of bytes)
23548 @tab   2**31-1
23549 @tab   2**31-1
23550 @sp 1
23552 @item  Maximum number of discriminants for a record type
23553 @tab   245
23554 @tab   No set limit
23555 @sp 1
23557 @item  Maximum number of formal parameters in an entry or
23558 subprogram declaration
23559 @tab   246
23560 @tab    No set limit
23561 @sp 1
23563 @item  Maximum number of dimensions in an array type
23564 @tab   255
23565 @tab   No set limit
23566 @sp 1
23568 @item  Maximum number of library  units and subunits in a compilation.
23569 @tab   4095
23570 @tab   No set limit
23571 @sp 1
23573 @item  Maximum number of library units and subunits in an execution.
23574 @tab   16383
23575 @tab   No set limit
23576 @sp 1
23578 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23579 or @code{PSECT_OBJECT}
23580 @tab   32757
23581 @tab   No set limit
23582 @sp 1
23584 @item  Maximum number of enumeration literals in an enumeration type
23585 definition
23586 @tab   65535
23587 @tab   No set limit
23588 @sp 1
23590 @item  Maximum number of lines in a source file
23591 @tab   65534
23592 @tab   No set limit
23593 @sp 1
23595 @item  Maximum number of bits in any object
23596 @tab   2**31-1
23597 @tab   2**31-1
23598 @sp 1
23600 @item  Maximum size of the static portion of a stack frame (approximate)
23601 @tab   2**31-1
23602 @tab   2**31-1
23603 @end multitable
23605 @node Tools and Utilities
23606 @section Tools and Utilities
23608 @noindent
23609 The following table lists some of the OpenVMS development tools
23610 available for HP Ada, and the corresponding tools for
23611 use with @value{EDITION} on Alpha and I64 platforms.
23612 Aside from the debugger, all the OpenVMS tools identified are part
23613 of the DECset package.
23615 @iftex
23616 @c Specify table in TeX since Texinfo does a poor job
23617 @tex
23618 \smallskip
23619 \smallskip
23620 \settabs\+Language-Sensitive Editor\quad
23621    &Product with HP Ada\quad
23622    &\cr
23623 \+\it Tool
23624    &\it Product with HP Ada
23625    & \it Product with @value{EDITION}\cr
23626 \smallskip
23627 \+Code Management System
23628    &HP CMS
23629    & HP CMS\cr
23630 \smallskip
23631 \+Language-Sensitive Editor
23632    &HP LSE
23633    & emacs or HP LSE (Alpha)\cr
23635    &
23636    & HP LSE (I64)\cr
23637 \smallskip
23638 \+Debugger
23639    &OpenVMS Debug
23640    & gdb (Alpha),\cr
23642    &
23643    & OpenVMS Debug (I64)\cr
23644 \smallskip
23645 \+Source Code Analyzer /
23646    &HP SCA
23647    & GNAT XREF\cr
23648 \+Cross Referencer
23649    &
23650    &\cr
23651 \smallskip
23652 \+Test Manager
23653    &HP Digital Test
23654    & HP DTM\cr
23656    &Manager (DTM)
23657    &\cr
23658 \smallskip
23659 \+Performance and
23660    & HP PCA
23661    & HP PCA\cr
23662 \+Coverage Analyzer
23663    &
23664    &\cr
23665 \smallskip
23666 \+Module Management
23667    & HP MMS
23668    & Not applicable\cr
23669 \+ System
23670    &
23671    &\cr
23672 \smallskip
23673 \smallskip
23674 @end tex
23675 @end iftex
23677 @ifnottex
23678 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
23679 @c the TeX version above for the printed version
23680 @flushleft
23681 @c @multitable @columnfractions .3 .4 .4
23682 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
23683 @item @i{Tool}
23684 @tab @i{Tool with HP Ada}
23685 @tab @i{Tool with @value{EDITION}}
23686 @item Code Management@*System
23687 @tab HP CMS
23688 @tab HP CMS
23689 @item Language-Sensitive@*Editor
23690 @tab HP LSE
23691 @tab emacs or HP LSE (Alpha)
23692 @item
23693 @tab
23694 @tab HP LSE (I64)
23695 @item Debugger
23696 @tab OpenVMS Debug
23697 @tab gdb (Alpha),
23698 @item
23699 @tab
23700 @tab OpenVMS Debug (I64)
23701 @item Source Code Analyzer /@*Cross Referencer
23702 @tab HP SCA
23703 @tab GNAT XREF
23704 @item Test Manager
23705 @tab HP Digital Test@*Manager (DTM)
23706 @tab HP DTM
23707 @item Performance and@*Coverage Analyzer
23708 @tab HP PCA
23709 @tab HP PCA
23710 @item Module Management@*System
23711 @tab HP MMS
23712 @tab Not applicable
23713 @end multitable
23714 @end flushleft
23715 @end ifnottex
23717 @end ifset
23719 @c **************************************
23720 @node Platform-Specific Information for the Run-Time Libraries
23721 @appendix Platform-Specific Information for the Run-Time Libraries
23722 @cindex Tasking and threads libraries
23723 @cindex Threads libraries and tasking
23724 @cindex Run-time libraries (platform-specific information)
23726 @noindent
23727 The GNAT run-time implementation may vary with respect to both the
23728 underlying threads library and the exception handling scheme.
23729 For threads support, one or more of the following are supplied:
23730 @itemize @bullet
23731 @item @b{native threads library}, a binding to the thread package from
23732 the underlying operating system
23734 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
23735 POSIX thread package
23736 @end itemize
23738 @noindent
23739 For exception handling, either or both of two models are supplied:
23740 @itemize @bullet
23741 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
23742 Most programs should experience a substantial speed improvement by
23743 being compiled with a ZCX run-time.
23744 This is especially true for
23745 tasking applications or applications with many exception handlers.}
23746 @cindex Zero-Cost Exceptions
23747 @cindex ZCX (Zero-Cost Exceptions)
23748 which uses binder-generated tables that
23749 are interrogated at run time to locate a handler
23751 @item @b{setjmp / longjmp} (``SJLJ''),
23752 @cindex setjmp/longjmp Exception Model
23753 @cindex SJLJ (setjmp/longjmp Exception Model)
23754 which uses dynamically-set data to establish
23755 the set of handlers
23756 @end itemize
23758 @noindent
23759 This appendix summarizes which combinations of threads and exception support
23760 are supplied on various GNAT platforms.
23761 It then shows how to select a particular library either
23762 permanently or temporarily,
23763 explains the properties of (and tradeoffs among) the various threads
23764 libraries, and provides some additional
23765 information about several specific platforms.
23767 @menu
23768 * Summary of Run-Time Configurations::
23769 * Specifying a Run-Time Library::
23770 * Choosing the Scheduling Policy::
23771 * Solaris-Specific Considerations::
23772 * Linux-Specific Considerations::
23773 * AIX-Specific Considerations::
23774 * RTX-Specific Considerations::
23775 * HP-UX-Specific Considerations::
23776 @end menu
23778 @node Summary of Run-Time Configurations
23779 @section Summary of Run-Time Configurations
23781 @multitable @columnfractions .30 .70
23782 @item @b{alpha-openvms}
23783 @item @code{@ @ }@i{rts-native (default)}
23784 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
23785 @item @code{@ @ @ @ }Exceptions @tab ZCX
23787 @item @code{@ @ }@i{rts-sjlj}
23788 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
23789 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23791 @item @b{ia64-hp_linux}
23792 @item @code{@ @ }@i{rts-native (default)}
23793 @item @code{@ @ @ @ }Tasking    @tab pthread library
23794 @item @code{@ @ @ @ }Exceptions @tab ZCX
23796 @item @b{ia64-hpux}
23797 @item @code{@ @ }@i{rts-native (default)}
23798 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23799 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23801 @item @b{ia64-openvms}
23802 @item @code{@ @ }@i{rts-native (default)}
23803 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
23804 @item @code{@ @ @ @ }Exceptions @tab ZCX
23806 @item @b{ia64-sgi_linux}
23807 @item @code{@ @ }@i{rts-native (default)}
23808 @item @code{@ @ @ @ }Tasking    @tab pthread library
23809 @item @code{@ @ @ @ }Exceptions @tab ZCX
23811 @item @b{pa-hpux}
23812 @item @code{@ @ }@i{rts-native (default)}
23813 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23814 @item @code{@ @ @ @ }Exceptions @tab ZCX
23816 @item @code{@ @ }@i{rts-sjlj}
23817 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23818 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23820 @item @b{ppc-aix}
23821 @item @code{@ @ }@i{rts-native (default)}
23822 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
23823 @item @code{@ @ @ @ }Exceptions @tab ZCX
23825 @item @code{@ @ }@i{rts-sjlj}
23826 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
23827 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23829 @item @b{ppc-darwin}
23830 @item @code{@ @ }@i{rts-native (default)}
23831 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
23832 @item @code{@ @ @ @ }Exceptions @tab ZCX
23834 @item @b{sparc-solaris}  @tab
23835 @item @code{@ @ }@i{rts-native (default)}
23836 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23837 @item @code{@ @ @ @ }Exceptions @tab ZCX
23839 @item @code{@ @ }@i{rts-pthread}
23840 @item @code{@ @ @ @ }Tasking    @tab pthread library
23841 @item @code{@ @ @ @ }Exceptions @tab ZCX
23843 @item @code{@ @ }@i{rts-sjlj}
23844 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23845 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23847 @item @b{sparc64-solaris}  @tab
23848 @item @code{@ @ }@i{rts-native (default)}
23849 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23850 @item @code{@ @ @ @ }Exceptions @tab ZCX
23852 @item @b{x86-linux}
23853 @item @code{@ @ }@i{rts-native (default)}
23854 @item @code{@ @ @ @ }Tasking    @tab pthread library
23855 @item @code{@ @ @ @ }Exceptions @tab ZCX
23857 @item @code{@ @ }@i{rts-sjlj}
23858 @item @code{@ @ @ @ }Tasking    @tab pthread library
23859 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23861 @item @b{x86-lynx}
23862 @item @code{@ @ }@i{rts-native (default)}
23863 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
23864 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23866 @item @b{x86-solaris}
23867 @item @code{@ @ }@i{rts-native (default)}
23868 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
23869 @item @code{@ @ @ @ }Exceptions @tab ZCX
23871 @item @code{@ @ }@i{rts-sjlj}
23872 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23873 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23875 @item @b{x86-windows}
23876 @item @code{@ @ }@i{rts-native (default)}
23877 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
23878 @item @code{@ @ @ @ }Exceptions @tab ZCX
23880 @item @code{@ @ }@i{rts-sjlj}
23881 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
23882 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23884 @item @b{x86-windows-rtx}
23885 @item @code{@ @ }@i{rts-rtx-rtss (default)}
23886 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
23887 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23889 @item @code{@ @ }@i{rts-rtx-w32}
23890 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
23891 @item @code{@ @ @ @ }Exceptions @tab ZCX
23893 @item @b{x86_64-linux}
23894 @item @code{@ @ }@i{rts-native (default)}
23895 @item @code{@ @ @ @ }Tasking    @tab pthread library
23896 @item @code{@ @ @ @ }Exceptions @tab ZCX
23898 @item @code{@ @ }@i{rts-sjlj}
23899 @item @code{@ @ @ @ }Tasking    @tab pthread library
23900 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23902 @end multitable
23904 @node Specifying a Run-Time Library
23905 @section Specifying a Run-Time Library
23907 @noindent
23908 The @file{adainclude} subdirectory containing the sources of the GNAT
23909 run-time library, and the @file{adalib} subdirectory containing the
23910 @file{ALI} files and the static and/or shared GNAT library, are located
23911 in the gcc target-dependent area:
23913 @smallexample
23914 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
23915 @end smallexample
23917 @noindent
23918 As indicated above, on some platforms several run-time libraries are supplied.
23919 These libraries are installed in the target dependent area and
23920 contain a complete source and binary subdirectory. The detailed description
23921 below explains the differences between the different libraries in terms of
23922 their thread support.
23924 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23925 This default run time is selected by the means of soft links.
23926 For example on x86-linux:
23928 @smallexample
23929 @group
23930  $(target-dir)
23931      |
23932      +--- adainclude----------+
23933      |                        |
23934      +--- adalib-----------+  |
23935      |                     |  |
23936      +--- rts-native       |  |
23937      |    |                |  |
23938      |    +--- adainclude <---+
23939      |    |                |
23940      |    +--- adalib <----+
23941      |
23942      +--- rts-sjlj
23943           |
23944           +--- adainclude
23945           |
23946           +--- adalib
23947 @end group
23948 @end smallexample
23950 @noindent
23951 If the @i{rts-sjlj} library is to be selected on a permanent basis,
23952 these soft links can be modified with the following commands:
23954 @smallexample
23955 $ cd $target
23956 $ rm -f adainclude adalib
23957 $ ln -s rts-sjlj/adainclude adainclude
23958 $ ln -s rts-sjlj/adalib adalib
23959 @end smallexample
23961 @noindent
23962 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
23963 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
23964 @file{$target/ada_object_path}.
23966 Selecting another run-time library temporarily can be
23967 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
23968 @cindex @option{--RTS} option
23970 @node Choosing the Scheduling Policy
23971 @section Choosing the Scheduling Policy
23973 @noindent
23974 When using a POSIX threads implementation, you have a choice of several
23975 scheduling policies: @code{SCHED_FIFO},
23976 @cindex @code{SCHED_FIFO} scheduling policy
23977 @code{SCHED_RR}
23978 @cindex @code{SCHED_RR} scheduling policy
23979 and @code{SCHED_OTHER}.
23980 @cindex @code{SCHED_OTHER} scheduling policy
23981 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23982 or @code{SCHED_RR} requires special (e.g., root) privileges.
23984 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23985 @code{SCHED_FIFO},
23986 @cindex @code{SCHED_FIFO} scheduling policy
23987 you can use one of the following:
23989 @itemize @bullet
23990 @item
23991 @code{pragma Time_Slice (0.0)}
23992 @cindex pragma Time_Slice
23993 @item
23994 the corresponding binder option @option{-T0}
23995 @cindex @option{-T0} option
23996 @item
23997 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23998 @cindex pragma Task_Dispatching_Policy
23999 @end itemize
24001 @noindent
24002 To specify @code{SCHED_RR},
24003 @cindex @code{SCHED_RR} scheduling policy
24004 you should use @code{pragma Time_Slice} with a
24005 value greater than @code{0.0}, or else use the corresponding @option{-T}
24006 binder option.
24008 @node Solaris-Specific Considerations
24009 @section Solaris-Specific Considerations
24010 @cindex Solaris Sparc threads libraries
24012 @noindent
24013 This section addresses some topics related to the various threads libraries
24014 on Sparc Solaris.
24016 @menu
24017 * Solaris Threads Issues::
24018 @end menu
24020 @node Solaris Threads Issues
24021 @subsection Solaris Threads Issues
24023 @noindent
24024 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24025 library based on POSIX threads --- @emph{rts-pthread}.
24026 @cindex rts-pthread threads library
24027 This run-time library has the advantage of being mostly shared across all
24028 POSIX-compliant thread implementations, and it also provides under
24029 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24030 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24031 and @code{PTHREAD_PRIO_PROTECT}
24032 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24033 semantics that can be selected using the predefined pragma
24034 @code{Locking_Policy}
24035 @cindex pragma Locking_Policy (under rts-pthread)
24036 with respectively
24037 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24038 @cindex @code{Inheritance_Locking} (under rts-pthread)
24039 @cindex @code{Ceiling_Locking} (under rts-pthread)
24041 As explained above, the native run-time library is based on the Solaris thread
24042 library (@code{libthread}) and is the default library.
24044 When the Solaris threads library is used (this is the default), programs
24045 compiled with GNAT can automatically take advantage of
24046 and can thus execute on multiple processors.
24047 The user can alternatively specify a processor on which the program should run
24048 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24049 is made by
24050 setting the environment variable @env{GNAT_PROCESSOR}
24051 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24052 to one of the following:
24054 @table @code
24055 @item -2
24056 Use the default configuration (run the program on all
24057 available processors) - this is the same as having @code{GNAT_PROCESSOR}
24058 unset
24060 @item -1
24061 Let the run-time implementation choose one processor and run the program on
24062 that processor
24064 @item 0 .. Last_Proc
24065 Run the program on the specified processor.
24066 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24067 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24068 @end table
24070 @node Linux-Specific Considerations
24071 @section Linux-Specific Considerations
24072 @cindex Linux threads libraries
24074 @noindent
24075 On GNU/Linux without NPTL support (usually system with GNU C Library
24076 older than 2.3), the signal model is not POSIX compliant, which means
24077 that to send a signal to the process, you need to send the signal to all
24078 threads, e.g.@: by using @code{killpg()}.
24080 @node AIX-Specific Considerations
24081 @section AIX-Specific Considerations
24082 @cindex AIX resolver library
24084 @noindent
24085 On AIX, the resolver library initializes some internal structure on
24086 the first call to @code{get*by*} functions, which are used to implement
24087 @code{GNAT.Sockets.Get_Host_By_Name} and
24088 @code{GNAT.Sockets.Get_Host_By_Address}.
24089 If such initialization occurs within an Ada task, and the stack size for
24090 the task is the default size, a stack overflow may occur.
24092 To avoid this overflow, the user should either ensure that the first call
24093 to @code{GNAT.Sockets.Get_Host_By_Name} or
24094 @code{GNAT.Sockets.Get_Host_By_Addrss}
24095 occurs in the environment task, or use @code{pragma Storage_Size} to
24096 specify a sufficiently large size for the stack of the task that contains
24097 this call.
24099 @node RTX-Specific Considerations
24100 @section RTX-Specific Considerations
24101 @cindex RTX libraries
24103 @noindent
24104 The Real-time Extension (RTX) to Windows is based on the Windows Win32
24105 API. Applications can be built to work in two different modes:
24107 @itemize @bullet
24108 @item
24109 Windows executables that run in Ring 3 to utilize memory protection
24110 (@emph{rts-rtx-w32}).
24112 @item
24113 Real-time subsystem (RTSS) executables that run in Ring 0, where
24114 performance can be optimized with RTSS applications taking precedent
24115 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
24116 the Microsoft linker to handle RTSS libraries.
24118 @end itemize
24120 @node HP-UX-Specific Considerations
24121 @section HP-UX-Specific Considerations
24122 @cindex HP-UX Scheduling
24124 @noindent
24125 On HP-UX, appropriate privileges are required to change the scheduling
24126 parameters of a task. The calling process must have appropriate
24127 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
24128 successfully change the scheduling parameters.
24130 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
24131 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
24132 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
24134 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
24135 one of the following:
24137 @itemize @bullet
24138 @item
24139 @code{pragma Time_Slice (0.0)}
24140 @cindex pragma Time_Slice
24141 @item
24142 the corresponding binder option @option{-T0}
24143 @cindex @option{-T0} option
24144 @item
24145 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24146 @cindex pragma Task_Dispatching_Policy
24147 @end itemize
24149 @noindent
24150 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
24151 you should use @code{pragma Time_Slice} with a
24152 value greater than @code{0.0}, or use the corresponding @option{-T}
24153 binder option, or set the @code{pragma Task_Dispatching_Policy
24154 (Round_Robin_Within_Priorities)}.
24156 @c *******************************
24157 @node Example of Binder Output File
24158 @appendix Example of Binder Output File
24160 @noindent
24161 This Appendix displays the source code for @command{gnatbind}'s output
24162 file generated for a simple ``Hello World'' program.
24163 Comments have been added for clarification purposes.
24165 @smallexample @c adanocomment
24166 @iftex
24167 @leftskip=0cm
24168 @end iftex
24169 --  The package is called Ada_Main unless this name is actually used
24170 --  as a unit name in the partition, in which case some other unique
24171 --  name is used.
24173 with System;
24174 package ada_main is
24176    Elab_Final_Code : Integer;
24177    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24179    --  The main program saves the parameters (argument count,
24180    --  argument values, environment pointer) in global variables
24181    --  for later access by other units including
24182    --  Ada.Command_Line.
24184    gnat_argc : Integer;
24185    gnat_argv : System.Address;
24186    gnat_envp : System.Address;
24188    --  The actual variables are stored in a library routine. This
24189    --  is useful for some shared library situations, where there
24190    --  are problems if variables are not in the library.
24192    pragma Import (C, gnat_argc);
24193    pragma Import (C, gnat_argv);
24194    pragma Import (C, gnat_envp);
24196    --  The exit status is similarly an external location
24198    gnat_exit_status : Integer;
24199    pragma Import (C, gnat_exit_status);
24201    GNAT_Version : constant String :=
24202                     "GNAT Version: 6.0.0w (20061115)";
24203    pragma Export (C, GNAT_Version, "__gnat_version");
24205    --  This is the generated adafinal routine that performs
24206    --  finalization at the end of execution. In the case where
24207    --  Ada is the main program, this main program makes a call
24208    --  to adafinal at program termination.
24210    procedure adafinal;
24211    pragma Export (C, adafinal, "adafinal");
24213    --  This is the generated adainit routine that performs
24214    --  initialization at the start of execution. In the case
24215    --  where Ada is the main program, this main program makes
24216    --  a call to adainit at program startup.
24218    procedure adainit;
24219    pragma Export (C, adainit, "adainit");
24221    --  This routine is called at the start of execution. It is
24222    --  a dummy routine that is used by the debugger to breakpoint
24223    --  at the start of execution.
24225    procedure Break_Start;
24226    pragma Import (C, Break_Start, "__gnat_break_start");
24228    --  This is the actual generated main program (it would be
24229    --  suppressed if the no main program switch were used). As
24230    --  required by standard system conventions, this program has
24231    --  the external name main.
24233    function main
24234      (argc : Integer;
24235       argv : System.Address;
24236       envp : System.Address)
24237       return Integer;
24238    pragma Export (C, main, "main");
24240    --  The following set of constants give the version
24241    --  identification values for every unit in the bound
24242    --  partition. This identification is computed from all
24243    --  dependent semantic units, and corresponds to the
24244    --  string that would be returned by use of the
24245    --  Body_Version or Version attributes.
24247    type Version_32 is mod 2 ** 32;
24248    u00001 : constant Version_32 := 16#7880BEB3#;
24249    u00002 : constant Version_32 := 16#0D24CBD0#;
24250    u00003 : constant Version_32 := 16#3283DBEB#;
24251    u00004 : constant Version_32 := 16#2359F9ED#;
24252    u00005 : constant Version_32 := 16#664FB847#;
24253    u00006 : constant Version_32 := 16#68E803DF#;
24254    u00007 : constant Version_32 := 16#5572E604#;
24255    u00008 : constant Version_32 := 16#46B173D8#;
24256    u00009 : constant Version_32 := 16#156A40CF#;
24257    u00010 : constant Version_32 := 16#033DABE0#;
24258    u00011 : constant Version_32 := 16#6AB38FEA#;
24259    u00012 : constant Version_32 := 16#22B6217D#;
24260    u00013 : constant Version_32 := 16#68A22947#;
24261    u00014 : constant Version_32 := 16#18CC4A56#;
24262    u00015 : constant Version_32 := 16#08258E1B#;
24263    u00016 : constant Version_32 := 16#367D5222#;
24264    u00017 : constant Version_32 := 16#20C9ECA4#;
24265    u00018 : constant Version_32 := 16#50D32CB6#;
24266    u00019 : constant Version_32 := 16#39A8BB77#;
24267    u00020 : constant Version_32 := 16#5CF8FA2B#;
24268    u00021 : constant Version_32 := 16#2F1EB794#;
24269    u00022 : constant Version_32 := 16#31AB6444#;
24270    u00023 : constant Version_32 := 16#1574B6E9#;
24271    u00024 : constant Version_32 := 16#5109C189#;
24272    u00025 : constant Version_32 := 16#56D770CD#;
24273    u00026 : constant Version_32 := 16#02F9DE3D#;
24274    u00027 : constant Version_32 := 16#08AB6B2C#;
24275    u00028 : constant Version_32 := 16#3FA37670#;
24276    u00029 : constant Version_32 := 16#476457A0#;
24277    u00030 : constant Version_32 := 16#731E1B6E#;
24278    u00031 : constant Version_32 := 16#23C2E789#;
24279    u00032 : constant Version_32 := 16#0F1BD6A1#;
24280    u00033 : constant Version_32 := 16#7C25DE96#;
24281    u00034 : constant Version_32 := 16#39ADFFA2#;
24282    u00035 : constant Version_32 := 16#571DE3E7#;
24283    u00036 : constant Version_32 := 16#5EB646AB#;
24284    u00037 : constant Version_32 := 16#4249379B#;
24285    u00038 : constant Version_32 := 16#0357E00A#;
24286    u00039 : constant Version_32 := 16#3784FB72#;
24287    u00040 : constant Version_32 := 16#2E723019#;
24288    u00041 : constant Version_32 := 16#623358EA#;
24289    u00042 : constant Version_32 := 16#107F9465#;
24290    u00043 : constant Version_32 := 16#6843F68A#;
24291    u00044 : constant Version_32 := 16#63305874#;
24292    u00045 : constant Version_32 := 16#31E56CE1#;
24293    u00046 : constant Version_32 := 16#02917970#;
24294    u00047 : constant Version_32 := 16#6CCBA70E#;
24295    u00048 : constant Version_32 := 16#41CD4204#;
24296    u00049 : constant Version_32 := 16#572E3F58#;
24297    u00050 : constant Version_32 := 16#20729FF5#;
24298    u00051 : constant Version_32 := 16#1D4F93E8#;
24299    u00052 : constant Version_32 := 16#30B2EC3D#;
24300    u00053 : constant Version_32 := 16#34054F96#;
24301    u00054 : constant Version_32 := 16#5A199860#;
24302    u00055 : constant Version_32 := 16#0E7F912B#;
24303    u00056 : constant Version_32 := 16#5760634A#;
24304    u00057 : constant Version_32 := 16#5D851835#;
24306    --  The following Export pragmas export the version numbers
24307    --  with symbolic names ending in B (for body) or S
24308    --  (for spec) so that they can be located in a link. The
24309    --  information provided here is sufficient to track down
24310    --  the exact versions of units used in a given build.
24312    pragma Export (C, u00001, "helloB");
24313    pragma Export (C, u00002, "system__standard_libraryB");
24314    pragma Export (C, u00003, "system__standard_libraryS");
24315    pragma Export (C, u00004, "adaS");
24316    pragma Export (C, u00005, "ada__text_ioB");
24317    pragma Export (C, u00006, "ada__text_ioS");
24318    pragma Export (C, u00007, "ada__exceptionsB");
24319    pragma Export (C, u00008, "ada__exceptionsS");
24320    pragma Export (C, u00009, "gnatS");
24321    pragma Export (C, u00010, "gnat__heap_sort_aB");
24322    pragma Export (C, u00011, "gnat__heap_sort_aS");
24323    pragma Export (C, u00012, "systemS");
24324    pragma Export (C, u00013, "system__exception_tableB");
24325    pragma Export (C, u00014, "system__exception_tableS");
24326    pragma Export (C, u00015, "gnat__htableB");
24327    pragma Export (C, u00016, "gnat__htableS");
24328    pragma Export (C, u00017, "system__exceptionsS");
24329    pragma Export (C, u00018, "system__machine_state_operationsB");
24330    pragma Export (C, u00019, "system__machine_state_operationsS");
24331    pragma Export (C, u00020, "system__machine_codeS");
24332    pragma Export (C, u00021, "system__storage_elementsB");
24333    pragma Export (C, u00022, "system__storage_elementsS");
24334    pragma Export (C, u00023, "system__secondary_stackB");
24335    pragma Export (C, u00024, "system__secondary_stackS");
24336    pragma Export (C, u00025, "system__parametersB");
24337    pragma Export (C, u00026, "system__parametersS");
24338    pragma Export (C, u00027, "system__soft_linksB");
24339    pragma Export (C, u00028, "system__soft_linksS");
24340    pragma Export (C, u00029, "system__stack_checkingB");
24341    pragma Export (C, u00030, "system__stack_checkingS");
24342    pragma Export (C, u00031, "system__tracebackB");
24343    pragma Export (C, u00032, "system__tracebackS");
24344    pragma Export (C, u00033, "ada__streamsS");
24345    pragma Export (C, u00034, "ada__tagsB");
24346    pragma Export (C, u00035, "ada__tagsS");
24347    pragma Export (C, u00036, "system__string_opsB");
24348    pragma Export (C, u00037, "system__string_opsS");
24349    pragma Export (C, u00038, "interfacesS");
24350    pragma Export (C, u00039, "interfaces__c_streamsB");
24351    pragma Export (C, u00040, "interfaces__c_streamsS");
24352    pragma Export (C, u00041, "system__file_ioB");
24353    pragma Export (C, u00042, "system__file_ioS");
24354    pragma Export (C, u00043, "ada__finalizationB");
24355    pragma Export (C, u00044, "ada__finalizationS");
24356    pragma Export (C, u00045, "system__finalization_rootB");
24357    pragma Export (C, u00046, "system__finalization_rootS");
24358    pragma Export (C, u00047, "system__finalization_implementationB");
24359    pragma Export (C, u00048, "system__finalization_implementationS");
24360    pragma Export (C, u00049, "system__string_ops_concat_3B");
24361    pragma Export (C, u00050, "system__string_ops_concat_3S");
24362    pragma Export (C, u00051, "system__stream_attributesB");
24363    pragma Export (C, u00052, "system__stream_attributesS");
24364    pragma Export (C, u00053, "ada__io_exceptionsS");
24365    pragma Export (C, u00054, "system__unsigned_typesS");
24366    pragma Export (C, u00055, "system__file_control_blockS");
24367    pragma Export (C, u00056, "ada__finalization__list_controllerB");
24368    pragma Export (C, u00057, "ada__finalization__list_controllerS");
24370    -- BEGIN ELABORATION ORDER
24371    -- ada (spec)
24372    -- gnat (spec)
24373    -- gnat.heap_sort_a (spec)
24374    -- gnat.heap_sort_a (body)
24375    -- gnat.htable (spec)
24376    -- gnat.htable (body)
24377    -- interfaces (spec)
24378    -- system (spec)
24379    -- system.machine_code (spec)
24380    -- system.parameters (spec)
24381    -- system.parameters (body)
24382    -- interfaces.c_streams (spec)
24383    -- interfaces.c_streams (body)
24384    -- system.standard_library (spec)
24385    -- ada.exceptions (spec)
24386    -- system.exception_table (spec)
24387    -- system.exception_table (body)
24388    -- ada.io_exceptions (spec)
24389    -- system.exceptions (spec)
24390    -- system.storage_elements (spec)
24391    -- system.storage_elements (body)
24392    -- system.machine_state_operations (spec)
24393    -- system.machine_state_operations (body)
24394    -- system.secondary_stack (spec)
24395    -- system.stack_checking (spec)
24396    -- system.soft_links (spec)
24397    -- system.soft_links (body)
24398    -- system.stack_checking (body)
24399    -- system.secondary_stack (body)
24400    -- system.standard_library (body)
24401    -- system.string_ops (spec)
24402    -- system.string_ops (body)
24403    -- ada.tags (spec)
24404    -- ada.tags (body)
24405    -- ada.streams (spec)
24406    -- system.finalization_root (spec)
24407    -- system.finalization_root (body)
24408    -- system.string_ops_concat_3 (spec)
24409    -- system.string_ops_concat_3 (body)
24410    -- system.traceback (spec)
24411    -- system.traceback (body)
24412    -- ada.exceptions (body)
24413    -- system.unsigned_types (spec)
24414    -- system.stream_attributes (spec)
24415    -- system.stream_attributes (body)
24416    -- system.finalization_implementation (spec)
24417    -- system.finalization_implementation (body)
24418    -- ada.finalization (spec)
24419    -- ada.finalization (body)
24420    -- ada.finalization.list_controller (spec)
24421    -- ada.finalization.list_controller (body)
24422    -- system.file_control_block (spec)
24423    -- system.file_io (spec)
24424    -- system.file_io (body)
24425    -- ada.text_io (spec)
24426    -- ada.text_io (body)
24427    -- hello (body)
24428    -- END ELABORATION ORDER
24430 end ada_main;
24432 --  The following source file name pragmas allow the generated file
24433 --  names to be unique for different main programs. They are needed
24434 --  since the package name will always be Ada_Main.
24436 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24437 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24439 --  Generated package body for Ada_Main starts here
24441 package body ada_main is
24443    --  The actual finalization is performed by calling the
24444    --  library routine in System.Standard_Library.Adafinal
24446    procedure Do_Finalize;
24447    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24449    -------------
24450    -- adainit --
24451    -------------
24453 @findex adainit
24454    procedure adainit is
24456       --  These booleans are set to True once the associated unit has
24457       --  been elaborated. It is also used to avoid elaborating the
24458       --  same unit twice.
24460       E040 : Boolean;
24461       pragma Import (Ada, E040, "interfaces__c_streams_E");
24463       E008 : Boolean;
24464       pragma Import (Ada, E008, "ada__exceptions_E");
24466       E014 : Boolean;
24467       pragma Import (Ada, E014, "system__exception_table_E");
24469       E053 : Boolean;
24470       pragma Import (Ada, E053, "ada__io_exceptions_E");
24472       E017 : Boolean;
24473       pragma Import (Ada, E017, "system__exceptions_E");
24475       E024 : Boolean;
24476       pragma Import (Ada, E024, "system__secondary_stack_E");
24478       E030 : Boolean;
24479       pragma Import (Ada, E030, "system__stack_checking_E");
24481       E028 : Boolean;
24482       pragma Import (Ada, E028, "system__soft_links_E");
24484       E035 : Boolean;
24485       pragma Import (Ada, E035, "ada__tags_E");
24487       E033 : Boolean;
24488       pragma Import (Ada, E033, "ada__streams_E");
24490       E046 : Boolean;
24491       pragma Import (Ada, E046, "system__finalization_root_E");
24493       E048 : Boolean;
24494       pragma Import (Ada, E048, "system__finalization_implementation_E");
24496       E044 : Boolean;
24497       pragma Import (Ada, E044, "ada__finalization_E");
24499       E057 : Boolean;
24500       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24502       E055 : Boolean;
24503       pragma Import (Ada, E055, "system__file_control_block_E");
24505       E042 : Boolean;
24506       pragma Import (Ada, E042, "system__file_io_E");
24508       E006 : Boolean;
24509       pragma Import (Ada, E006, "ada__text_io_E");
24511       --  Set_Globals is a library routine that stores away the
24512       --  value of the indicated set of global values in global
24513       --  variables within the library.
24515       procedure Set_Globals
24516         (Main_Priority            : Integer;
24517          Time_Slice_Value         : Integer;
24518          WC_Encoding              : Character;
24519          Locking_Policy           : Character;
24520          Queuing_Policy           : Character;
24521          Task_Dispatching_Policy  : Character;
24522          Adafinal                 : System.Address;
24523          Unreserve_All_Interrupts : Integer;
24524          Exception_Tracebacks     : Integer);
24525 @findex __gnat_set_globals
24526       pragma Import (C, Set_Globals, "__gnat_set_globals");
24528       --  SDP_Table_Build is a library routine used to build the
24529       --  exception tables. See unit Ada.Exceptions in files
24530       --  a-except.ads/adb for full details of how zero cost
24531       --  exception handling works. This procedure, the call to
24532       --  it, and the two following tables are all omitted if the
24533       --  build is in longjmp/setjmp exception mode.
24535 @findex SDP_Table_Build
24536 @findex Zero Cost Exceptions
24537       procedure SDP_Table_Build
24538         (SDP_Addresses   : System.Address;
24539          SDP_Count       : Natural;
24540          Elab_Addresses  : System.Address;
24541          Elab_Addr_Count : Natural);
24542       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24544       --  Table of Unit_Exception_Table addresses. Used for zero
24545       --  cost exception handling to build the top level table.
24547       ST : aliased constant array (1 .. 23) of System.Address := (
24548         Hello'UET_Address,
24549         Ada.Text_Io'UET_Address,
24550         Ada.Exceptions'UET_Address,
24551         Gnat.Heap_Sort_A'UET_Address,
24552         System.Exception_Table'UET_Address,
24553         System.Machine_State_Operations'UET_Address,
24554         System.Secondary_Stack'UET_Address,
24555         System.Parameters'UET_Address,
24556         System.Soft_Links'UET_Address,
24557         System.Stack_Checking'UET_Address,
24558         System.Traceback'UET_Address,
24559         Ada.Streams'UET_Address,
24560         Ada.Tags'UET_Address,
24561         System.String_Ops'UET_Address,
24562         Interfaces.C_Streams'UET_Address,
24563         System.File_Io'UET_Address,
24564         Ada.Finalization'UET_Address,
24565         System.Finalization_Root'UET_Address,
24566         System.Finalization_Implementation'UET_Address,
24567         System.String_Ops_Concat_3'UET_Address,
24568         System.Stream_Attributes'UET_Address,
24569         System.File_Control_Block'UET_Address,
24570         Ada.Finalization.List_Controller'UET_Address);
24572       --  Table of addresses of elaboration routines. Used for
24573       --  zero cost exception handling to make sure these
24574       --  addresses are included in the top level procedure
24575       --  address table.
24577       EA : aliased constant array (1 .. 23) of System.Address := (
24578         adainit'Code_Address,
24579         Do_Finalize'Code_Address,
24580         Ada.Exceptions'Elab_Spec'Address,
24581         System.Exceptions'Elab_Spec'Address,
24582         Interfaces.C_Streams'Elab_Spec'Address,
24583         System.Exception_Table'Elab_Body'Address,
24584         Ada.Io_Exceptions'Elab_Spec'Address,
24585         System.Stack_Checking'Elab_Spec'Address,
24586         System.Soft_Links'Elab_Body'Address,
24587         System.Secondary_Stack'Elab_Body'Address,
24588         Ada.Tags'Elab_Spec'Address,
24589         Ada.Tags'Elab_Body'Address,
24590         Ada.Streams'Elab_Spec'Address,
24591         System.Finalization_Root'Elab_Spec'Address,
24592         Ada.Exceptions'Elab_Body'Address,
24593         System.Finalization_Implementation'Elab_Spec'Address,
24594         System.Finalization_Implementation'Elab_Body'Address,
24595         Ada.Finalization'Elab_Spec'Address,
24596         Ada.Finalization.List_Controller'Elab_Spec'Address,
24597         System.File_Control_Block'Elab_Spec'Address,
24598         System.File_Io'Elab_Body'Address,
24599         Ada.Text_Io'Elab_Spec'Address,
24600         Ada.Text_Io'Elab_Body'Address);
24602    --  Start of processing for adainit
24604    begin
24606       --  Call SDP_Table_Build to build the top level procedure
24607       --  table for zero cost exception handling (omitted in
24608       --  longjmp/setjmp mode).
24610       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24612       --  Call Set_Globals to record various information for
24613       --  this partition.  The values are derived by the binder
24614       --  from information stored in the ali files by the compiler.
24616 @findex __gnat_set_globals
24617       Set_Globals
24618         (Main_Priority            => -1,
24619          --  Priority of main program, -1 if no pragma Priority used
24621          Time_Slice_Value         => -1,
24622          --  Time slice from Time_Slice pragma, -1 if none used
24624          WC_Encoding              => 'b',
24625          --  Wide_Character encoding used, default is brackets
24627          Locking_Policy           => ' ',
24628          --  Locking_Policy used, default of space means not
24629          --  specified, otherwise it is the first character of
24630          --  the policy name.
24632          Queuing_Policy           => ' ',
24633          --  Queuing_Policy used, default of space means not
24634          --  specified, otherwise it is the first character of
24635          --  the policy name.
24637          Task_Dispatching_Policy  => ' ',
24638          --  Task_Dispatching_Policy used, default of space means
24639          --  not specified, otherwise first character of the
24640          --  policy name.
24642          Adafinal                 => System.Null_Address,
24643          --  Address of Adafinal routine, not used anymore
24645          Unreserve_All_Interrupts => 0,
24646          --  Set true if pragma Unreserve_All_Interrupts was used
24648          Exception_Tracebacks     => 0);
24649          --  Indicates if exception tracebacks are enabled
24651       Elab_Final_Code := 1;
24653       --  Now we have the elaboration calls for all units in the partition.
24654       --  The Elab_Spec and Elab_Body attributes generate references to the
24655       --  implicit elaboration procedures generated by the compiler for
24656       --  each unit that requires elaboration.
24658       if not E040 then
24659          Interfaces.C_Streams'Elab_Spec;
24660       end if;
24661       E040 := True;
24662       if not E008 then
24663          Ada.Exceptions'Elab_Spec;
24664       end if;
24665       if not E014 then
24666          System.Exception_Table'Elab_Body;
24667          E014 := True;
24668       end if;
24669       if not E053 then
24670          Ada.Io_Exceptions'Elab_Spec;
24671          E053 := True;
24672       end if;
24673       if not E017 then
24674          System.Exceptions'Elab_Spec;
24675          E017 := True;
24676       end if;
24677       if not E030 then
24678          System.Stack_Checking'Elab_Spec;
24679       end if;
24680       if not E028 then
24681          System.Soft_Links'Elab_Body;
24682          E028 := True;
24683       end if;
24684       E030 := True;
24685       if not E024 then
24686          System.Secondary_Stack'Elab_Body;
24687          E024 := True;
24688       end if;
24689       if not E035 then
24690          Ada.Tags'Elab_Spec;
24691       end if;
24692       if not E035 then
24693          Ada.Tags'Elab_Body;
24694          E035 := True;
24695       end if;
24696       if not E033 then
24697          Ada.Streams'Elab_Spec;
24698          E033 := True;
24699       end if;
24700       if not E046 then
24701          System.Finalization_Root'Elab_Spec;
24702       end if;
24703       E046 := True;
24704       if not E008 then
24705          Ada.Exceptions'Elab_Body;
24706          E008 := True;
24707       end if;
24708       if not E048 then
24709          System.Finalization_Implementation'Elab_Spec;
24710       end if;
24711       if not E048 then
24712          System.Finalization_Implementation'Elab_Body;
24713          E048 := True;
24714       end if;
24715       if not E044 then
24716          Ada.Finalization'Elab_Spec;
24717       end if;
24718       E044 := True;
24719       if not E057 then
24720          Ada.Finalization.List_Controller'Elab_Spec;
24721       end if;
24722       E057 := True;
24723       if not E055 then
24724          System.File_Control_Block'Elab_Spec;
24725          E055 := True;
24726       end if;
24727       if not E042 then
24728          System.File_Io'Elab_Body;
24729          E042 := True;
24730       end if;
24731       if not E006 then
24732          Ada.Text_Io'Elab_Spec;
24733       end if;
24734       if not E006 then
24735          Ada.Text_Io'Elab_Body;
24736          E006 := True;
24737       end if;
24739       Elab_Final_Code := 0;
24740    end adainit;
24742    --------------
24743    -- adafinal --
24744    --------------
24746 @findex adafinal
24747    procedure adafinal is
24748    begin
24749       Do_Finalize;
24750    end adafinal;
24752    ----------
24753    -- main --
24754    ----------
24756    --  main is actually a function, as in the ANSI C standard,
24757    --  defined to return the exit status. The three parameters
24758    --  are the argument count, argument values and environment
24759    --  pointer.
24761 @findex Main Program
24762    function main
24763      (argc : Integer;
24764       argv : System.Address;
24765       envp : System.Address)
24766       return Integer
24767    is
24768       --  The initialize routine performs low level system
24769       --  initialization using a standard library routine which
24770       --  sets up signal handling and performs any other
24771       --  required setup. The routine can be found in file
24772       --  a-init.c.
24774 @findex __gnat_initialize
24775       procedure initialize;
24776       pragma Import (C, initialize, "__gnat_initialize");
24778       --  The finalize routine performs low level system
24779       --  finalization using a standard library routine. The
24780       --  routine is found in file a-final.c and in the standard
24781       --  distribution is a dummy routine that does nothing, so
24782       --  really this is a hook for special user finalization.
24784 @findex __gnat_finalize
24785       procedure finalize;
24786       pragma Import (C, finalize, "__gnat_finalize");
24788       --  We get to the main program of the partition by using
24789       --  pragma Import because if we try to with the unit and
24790       --  call it Ada style, then not only do we waste time
24791       --  recompiling it, but also, we don't really know the right
24792       --  switches (e.g.@: identifier character set) to be used
24793       --  to compile it.
24795       procedure Ada_Main_Program;
24796       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
24798    --  Start of processing for main
24800    begin
24801       --  Save global variables
24803       gnat_argc := argc;
24804       gnat_argv := argv;
24805       gnat_envp := envp;
24807       --  Call low level system initialization
24809       Initialize;
24811       --  Call our generated Ada initialization routine
24813       adainit;
24815       --  This is the point at which we want the debugger to get
24816       --  control
24818       Break_Start;
24820       --  Now we call the main program of the partition
24822       Ada_Main_Program;
24824       --  Perform Ada finalization
24826       adafinal;
24828       --  Perform low level system finalization
24830       Finalize;
24832       --  Return the proper exit status
24833       return (gnat_exit_status);
24834    end;
24836 --  This section is entirely comments, so it has no effect on the
24837 --  compilation of the Ada_Main package. It provides the list of
24838 --  object files and linker options, as well as some standard
24839 --  libraries needed for the link. The gnatlink utility parses
24840 --  this b~hello.adb file to read these comment lines to generate
24841 --  the appropriate command line arguments for the call to the
24842 --  system linker. The BEGIN/END lines are used for sentinels for
24843 --  this parsing operation.
24845 --  The exact file names will of course depend on the environment,
24846 --  host/target and location of files on the host system.
24848 @findex Object file list
24849 -- BEGIN Object file/option list
24850    --   ./hello.o
24851    --   -L./
24852    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
24853    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
24854 -- END Object file/option list
24856 end ada_main;
24857 @end smallexample
24859 @noindent
24860 The Ada code in the above example is exactly what is generated by the
24861 binder. We have added comments to more clearly indicate the function
24862 of each part of the generated @code{Ada_Main} package.
24864 The code is standard Ada in all respects, and can be processed by any
24865 tools that handle Ada. In particular, it is possible to use the debugger
24866 in Ada mode to debug the generated @code{Ada_Main} package. For example,
24867 suppose that for reasons that you do not understand, your program is crashing
24868 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
24869 you can place a breakpoint on the call:
24871 @smallexample @c ada
24872 Ada.Text_Io'Elab_Body;
24873 @end smallexample
24875 @noindent
24876 and trace the elaboration routine for this package to find out where
24877 the problem might be (more usually of course you would be debugging
24878 elaboration code in your own application).
24880 @node Elaboration Order Handling in GNAT
24881 @appendix Elaboration Order Handling in GNAT
24882 @cindex Order of elaboration
24883 @cindex Elaboration control
24885 @menu
24886 * Elaboration Code::
24887 * Checking the Elaboration Order::
24888 * Controlling the Elaboration Order::
24889 * Controlling Elaboration in GNAT - Internal Calls::
24890 * Controlling Elaboration in GNAT - External Calls::
24891 * Default Behavior in GNAT - Ensuring Safety::
24892 * Treatment of Pragma Elaborate::
24893 * Elaboration Issues for Library Tasks::
24894 * Mixing Elaboration Models::
24895 * What to Do If the Default Elaboration Behavior Fails::
24896 * Elaboration for Dispatching Calls::
24897 * Summary of Procedures for Elaboration Control::
24898 * Other Elaboration Order Considerations::
24899 @end menu
24901 @noindent
24902 This chapter describes the handling of elaboration code in Ada and
24903 in GNAT, and discusses how the order of elaboration of program units can
24904 be controlled in GNAT, either automatically or with explicit programming
24905 features.
24907 @node Elaboration Code
24908 @section Elaboration Code
24910 @noindent
24911 Ada provides rather general mechanisms for executing code at elaboration
24912 time, that is to say before the main program starts executing. Such code arises
24913 in three contexts:
24915 @table @asis
24916 @item Initializers for variables.
24917 Variables declared at the library level, in package specs or bodies, can
24918 require initialization that is performed at elaboration time, as in:
24919 @smallexample @c ada
24920 @cartouche
24921 Sqrt_Half : Float := Sqrt (0.5);
24922 @end cartouche
24923 @end smallexample
24925 @item Package initialization code
24926 Code in a @code{BEGIN-END} section at the outer level of a package body is
24927 executed as part of the package body elaboration code.
24929 @item Library level task allocators
24930 Tasks that are declared using task allocators at the library level
24931 start executing immediately and hence can execute at elaboration time.
24932 @end table
24934 @noindent
24935 Subprogram calls are possible in any of these contexts, which means that
24936 any arbitrary part of the program may be executed as part of the elaboration
24937 code. It is even possible to write a program which does all its work at
24938 elaboration time, with a null main program, although stylistically this
24939 would usually be considered an inappropriate way to structure
24940 a program.
24942 An important concern arises in the context of elaboration code:
24943 we have to be sure that it is executed in an appropriate order. What we
24944 have is a series of elaboration code sections, potentially one section
24945 for each unit in the program. It is important that these execute
24946 in the correct order. Correctness here means that, taking the above
24947 example of the declaration of @code{Sqrt_Half},
24948 if some other piece of
24949 elaboration code references @code{Sqrt_Half},
24950 then it must run after the
24951 section of elaboration code that contains the declaration of
24952 @code{Sqrt_Half}.
24954 There would never be any order of elaboration problem if we made a rule
24955 that whenever you @code{with} a unit, you must elaborate both the spec and body
24956 of that unit before elaborating the unit doing the @code{with}'ing:
24958 @smallexample @c ada
24959 @group
24960 @cartouche
24961 with Unit_1;
24962 package Unit_2 is @dots{}
24963 @end cartouche
24964 @end group
24965 @end smallexample
24967 @noindent
24968 would require that both the body and spec of @code{Unit_1} be elaborated
24969 before the spec of @code{Unit_2}. However, a rule like that would be far too
24970 restrictive. In particular, it would make it impossible to have routines
24971 in separate packages that were mutually recursive.
24973 You might think that a clever enough compiler could look at the actual
24974 elaboration code and determine an appropriate correct order of elaboration,
24975 but in the general case, this is not possible. Consider the following
24976 example.
24978 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
24979 that references
24980 the variable @code{Sqrt_1}, which is declared in the elaboration code
24981 of the body of @code{Unit_1}:
24983 @smallexample @c ada
24984 @cartouche
24985 Sqrt_1 : Float := Sqrt (0.1);
24986 @end cartouche
24987 @end smallexample
24989 @noindent
24990 The elaboration code of the body of @code{Unit_1} also contains:
24992 @smallexample @c ada
24993 @group
24994 @cartouche
24995 if expression_1 = 1 then
24996    Q := Unit_2.Func_2;
24997 end if;
24998 @end cartouche
24999 @end group
25000 @end smallexample
25002 @noindent
25003 @code{Unit_2} is exactly parallel,
25004 it has a procedure @code{Func_2} that references
25005 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25006 the body @code{Unit_2}:
25008 @smallexample @c ada
25009 @cartouche
25010 Sqrt_2 : Float := Sqrt (0.1);
25011 @end cartouche
25012 @end smallexample
25014 @noindent
25015 The elaboration code of the body of @code{Unit_2} also contains:
25017 @smallexample @c ada
25018 @group
25019 @cartouche
25020 if expression_2 = 2 then
25021    Q := Unit_1.Func_1;
25022 end if;
25023 @end cartouche
25024 @end group
25025 @end smallexample
25027 @noindent
25028 Now the question is, which of the following orders of elaboration is
25029 acceptable:
25031 @smallexample
25032 @group
25033 Spec of Unit_1
25034 Spec of Unit_2
25035 Body of Unit_1
25036 Body of Unit_2
25037 @end group
25038 @end smallexample
25040 @noindent
25043 @smallexample
25044 @group
25045 Spec of Unit_2
25046 Spec of Unit_1
25047 Body of Unit_2
25048 Body of Unit_1
25049 @end group
25050 @end smallexample
25052 @noindent
25053 If you carefully analyze the flow here, you will see that you cannot tell
25054 at compile time the answer to this question.
25055 If @code{expression_1} is not equal to 1,
25056 and @code{expression_2} is not equal to 2,
25057 then either order is acceptable, because neither of the function calls is
25058 executed. If both tests evaluate to true, then neither order is acceptable
25059 and in fact there is no correct order.
25061 If one of the two expressions is true, and the other is false, then one
25062 of the above orders is correct, and the other is incorrect. For example,
25063 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25064 then the call to @code{Func_1}
25065 will occur, but not the call to @code{Func_2.}
25066 This means that it is essential
25067 to elaborate the body of @code{Unit_1} before
25068 the body of @code{Unit_2}, so the first
25069 order of elaboration is correct and the second is wrong.
25071 By making @code{expression_1} and @code{expression_2}
25072 depend on input data, or perhaps
25073 the time of day, we can make it impossible for the compiler or binder
25074 to figure out which of these expressions will be true, and hence it
25075 is impossible to guarantee a safe order of elaboration at run time.
25077 @node Checking the Elaboration Order
25078 @section Checking the Elaboration Order
25080 @noindent
25081 In some languages that involve the same kind of elaboration problems,
25082 e.g.@: Java and C++, the programmer is expected to worry about these
25083 ordering problems himself, and it is common to
25084 write a program in which an incorrect elaboration order  gives
25085 surprising results, because it references variables before they
25086 are initialized.
25087 Ada is designed to be a safe language, and a programmer-beware approach is
25088 clearly not sufficient. Consequently, the language provides three lines
25089 of defense:
25091 @table @asis
25092 @item Standard rules
25093 Some standard rules restrict the possible choice of elaboration
25094 order. In particular, if you @code{with} a unit, then its spec is always
25095 elaborated before the unit doing the @code{with}. Similarly, a parent
25096 spec is always elaborated before the child spec, and finally
25097 a spec is always elaborated before its corresponding body.
25099 @item Dynamic elaboration checks
25100 @cindex Elaboration checks
25101 @cindex Checks, elaboration
25102 Dynamic checks are made at run time, so that if some entity is accessed
25103 before it is elaborated (typically  by means of a subprogram call)
25104 then the exception (@code{Program_Error}) is raised.
25106 @item Elaboration control
25107 Facilities are provided for the programmer to specify the desired order
25108 of elaboration.
25109 @end table
25111 Let's look at these facilities in more detail. First, the rules for
25112 dynamic checking. One possible rule would be simply to say that the
25113 exception is raised if you access a variable which has not yet been
25114 elaborated. The trouble with this approach is that it could require
25115 expensive checks on every variable reference. Instead Ada has two
25116 rules which are a little more restrictive, but easier to check, and
25117 easier to state:
25119 @table @asis
25120 @item Restrictions on calls
25121 A subprogram can only be called at elaboration time if its body
25122 has been elaborated. The rules for elaboration given above guarantee
25123 that the spec of the subprogram has been elaborated before the
25124 call, but not the body. If this rule is violated, then the
25125 exception @code{Program_Error} is raised.
25127 @item Restrictions on instantiations
25128 A generic unit can only be instantiated if the body of the generic
25129 unit has been elaborated. Again, the rules for elaboration given above
25130 guarantee that the spec of the generic unit has been elaborated
25131 before the instantiation, but not the body. If this rule is
25132 violated, then the exception @code{Program_Error} is raised.
25133 @end table
25135 @noindent
25136 The idea is that if the body has been elaborated, then any variables
25137 it references must have been elaborated; by checking for the body being
25138 elaborated we guarantee that none of its references causes any
25139 trouble. As we noted above, this is a little too restrictive, because a
25140 subprogram that has no non-local references in its body may in fact be safe
25141 to call. However, it really would be unsafe to rely on this, because
25142 it would mean that the caller was aware of details of the implementation
25143 in the body. This goes against the basic tenets of Ada.
25145 A plausible implementation can be described as follows.
25146 A Boolean variable is associated with each subprogram
25147 and each generic unit. This variable is initialized to False, and is set to
25148 True at the point body is elaborated. Every call or instantiation checks the
25149 variable, and raises @code{Program_Error} if the variable is False.
25151 Note that one might think that it would be good enough to have one Boolean
25152 variable for each package, but that would not deal with cases of trying
25153 to call a body in the same package as the call
25154 that has not been elaborated yet.
25155 Of course a compiler may be able to do enough analysis to optimize away
25156 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
25157 does such optimizations, but still the easiest conceptual model is to
25158 think of there being one variable per subprogram.
25160 @node Controlling the Elaboration Order
25161 @section Controlling the Elaboration Order
25163 @noindent
25164 In the previous section we discussed the rules in Ada which ensure
25165 that @code{Program_Error} is raised if an incorrect elaboration order is
25166 chosen. This prevents erroneous executions, but we need mechanisms to
25167 specify a correct execution and avoid the exception altogether.
25168 To achieve this, Ada provides a number of features for controlling
25169 the order of elaboration. We discuss these features in this section.
25171 First, there are several ways of indicating to the compiler that a given
25172 unit has no elaboration problems:
25174 @table @asis
25175 @item packages that do not require a body
25176 A library package that does not require a body does not permit
25177 a body (this rule was introduced in Ada 95).
25178 Thus if we have a such a package, as in:
25180 @smallexample @c ada
25181 @group
25182 @cartouche
25183 package Definitions is
25184    generic
25185       type m is new integer;
25186    package Subp is
25187       type a is array (1 .. 10) of m;
25188       type b is array (1 .. 20) of m;
25189    end Subp;
25190 end Definitions;
25191 @end cartouche
25192 @end group
25193 @end smallexample
25195 @noindent
25196 A package that @code{with}'s @code{Definitions} may safely instantiate
25197 @code{Definitions.Subp} because the compiler can determine that there
25198 definitely is no package body to worry about in this case
25200 @item pragma Pure
25201 @cindex pragma Pure
25202 @findex Pure
25203 Places sufficient restrictions on a unit to guarantee that
25204 no call to any subprogram in the unit can result in an
25205 elaboration problem. This means that the compiler does not need
25206 to worry about the point of elaboration of such units, and in
25207 particular, does not need to check any calls to any subprograms
25208 in this unit.
25210 @item pragma Preelaborate
25211 @findex Preelaborate
25212 @cindex pragma Preelaborate
25213 This pragma places slightly less stringent restrictions on a unit than
25214 does pragma Pure,
25215 but these restrictions are still sufficient to ensure that there
25216 are no elaboration problems with any calls to the unit.
25218 @item pragma Elaborate_Body
25219 @findex Elaborate_Body
25220 @cindex pragma Elaborate_Body
25221 This pragma requires that the body of a unit be elaborated immediately
25222 after its spec. Suppose a unit @code{A} has such a pragma,
25223 and unit @code{B} does
25224 a @code{with} of unit @code{A}. Recall that the standard rules require
25225 the spec of unit @code{A}
25226 to be elaborated before the @code{with}'ing unit; given the pragma in
25227 @code{A}, we also know that the body of @code{A}
25228 will be elaborated before @code{B}, so
25229 that calls to @code{A} are safe and do not need a check.
25230 @end table
25232 @noindent
25233 Note that,
25234 unlike pragma @code{Pure} and pragma @code{Preelaborate},
25235 the use of
25236 @code{Elaborate_Body} does not guarantee that the program is
25237 free of elaboration problems, because it may not be possible
25238 to satisfy the requested elaboration order.
25239 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25240 If a programmer
25241 marks @code{Unit_1} as @code{Elaborate_Body},
25242 and not @code{Unit_2,} then the order of
25243 elaboration will be:
25245 @smallexample
25246 @group
25247 Spec of Unit_2
25248 Spec of Unit_1
25249 Body of Unit_1
25250 Body of Unit_2
25251 @end group
25252 @end smallexample
25254 @noindent
25255 Now that means that the call to @code{Func_1} in @code{Unit_2}
25256 need not be checked,
25257 it must be safe. But the call to @code{Func_2} in
25258 @code{Unit_1} may still fail if
25259 @code{Expression_1} is equal to 1,
25260 and the programmer must still take
25261 responsibility for this not being the case.
25263 If all units carry a pragma @code{Elaborate_Body}, then all problems are
25264 eliminated, except for calls entirely within a body, which are
25265 in any case fully under programmer control. However, using the pragma
25266 everywhere is not always possible.
25267 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25268 we marked both of them as having pragma @code{Elaborate_Body}, then
25269 clearly there would be no possible elaboration order.
25271 The above pragmas allow a server to guarantee safe use by clients, and
25272 clearly this is the preferable approach. Consequently a good rule
25273 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25274 and if this is not possible,
25275 mark them as @code{Elaborate_Body} if possible.
25276 As we have seen, there are situations where neither of these
25277 three pragmas can be used.
25278 So we also provide methods for clients to control the
25279 order of elaboration of the servers on which they depend:
25281 @table @asis
25282 @item pragma Elaborate (unit)
25283 @findex Elaborate
25284 @cindex pragma Elaborate
25285 This pragma is placed in the context clause, after a @code{with} clause,
25286 and it requires that the body of the named unit be elaborated before
25287 the unit in which the pragma occurs. The idea is to use this pragma
25288 if the current unit calls at elaboration time, directly or indirectly,
25289 some subprogram in the named unit.
25291 @item pragma Elaborate_All (unit)
25292 @findex Elaborate_All
25293 @cindex pragma Elaborate_All
25294 This is a stronger version of the Elaborate pragma. Consider the
25295 following example:
25297 @smallexample
25298 Unit A @code{with}'s unit B and calls B.Func in elab code
25299 Unit B @code{with}'s unit C, and B.Func calls C.Func
25300 @end smallexample
25302 @noindent
25303 Now if we put a pragma @code{Elaborate (B)}
25304 in unit @code{A}, this ensures that the
25305 body of @code{B} is elaborated before the call, but not the
25306 body of @code{C}, so
25307 the call to @code{C.Func} could still cause @code{Program_Error} to
25308 be raised.
25310 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25311 not only that the body of the named unit be elaborated before the
25312 unit doing the @code{with}, but also the bodies of all units that the
25313 named unit uses, following @code{with} links transitively. For example,
25314 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25315 then it requires
25316 not only that the body of @code{B} be elaborated before @code{A},
25317 but also the
25318 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25319 @end table
25321 @noindent
25322 We are now in a position to give a usage rule in Ada for avoiding
25323 elaboration problems, at least if dynamic dispatching and access to
25324 subprogram values are not used. We will handle these cases separately
25325 later.
25327 The rule is simple. If a unit has elaboration code that can directly or
25328 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25329 a generic package in a @code{with}'ed unit,
25330 then if the @code{with}'ed unit does not have
25331 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25332 a pragma @code{Elaborate_All}
25333 for the @code{with}'ed unit. By following this rule a client is
25334 assured that calls can be made without risk of an exception.
25336 For generic subprogram instantiations, the rule can be relaxed to
25337 require only a pragma @code{Elaborate} since elaborating the body
25338 of a subprogram cannot cause any transitive elaboration (we are
25339 not calling the subprogram in this case, just elaborating its
25340 declaration).
25342 If this rule is not followed, then a program may be in one of four
25343 states:
25345 @table @asis
25346 @item No order exists
25347 No order of elaboration exists which follows the rules, taking into
25348 account any @code{Elaborate}, @code{Elaborate_All},
25349 or @code{Elaborate_Body} pragmas. In
25350 this case, an Ada compiler must diagnose the situation at bind
25351 time, and refuse to build an executable program.
25353 @item One or more orders exist, all incorrect
25354 One or more acceptable elaboration orders exist, and all of them
25355 generate an elaboration order problem. In this case, the binder
25356 can build an executable program, but @code{Program_Error} will be raised
25357 when the program is run.
25359 @item Several orders exist, some right, some incorrect
25360 One or more acceptable elaboration orders exists, and some of them
25361 work, and some do not. The programmer has not controlled
25362 the order of elaboration, so the binder may or may not pick one of
25363 the correct orders, and the program may or may not raise an
25364 exception when it is run. This is the worst case, because it means
25365 that the program may fail when moved to another compiler, or even
25366 another version of the same compiler.
25368 @item One or more orders exists, all correct
25369 One ore more acceptable elaboration orders exist, and all of them
25370 work. In this case the program runs successfully. This state of
25371 affairs can be guaranteed by following the rule we gave above, but
25372 may be true even if the rule is not followed.
25373 @end table
25375 @noindent
25376 Note that one additional advantage of following our rules on the use
25377 of @code{Elaborate} and @code{Elaborate_All}
25378 is that the program continues to stay in the ideal (all orders OK) state
25379 even if maintenance
25380 changes some bodies of some units. Conversely, if a program that does
25381 not follow this rule happens to be safe at some point, this state of affairs
25382 may deteriorate silently as a result of maintenance changes.
25384 You may have noticed that the above discussion did not mention
25385 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25386 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25387 code in the body makes calls to some other unit, so it is still necessary
25388 to use @code{Elaborate_All} on such units.
25390 @node Controlling Elaboration in GNAT - Internal Calls
25391 @section Controlling Elaboration in GNAT - Internal Calls
25393 @noindent
25394 In the case of internal calls, i.e., calls within a single package, the
25395 programmer has full control over the order of elaboration, and it is up
25396 to the programmer to elaborate declarations in an appropriate order. For
25397 example writing:
25399 @smallexample @c ada
25400 @group
25401 @cartouche
25402 function One return Float;
25404 Q : Float := One;
25406 function One return Float is
25407 begin
25408      return 1.0;
25409 end One;
25410 @end cartouche
25411 @end group
25412 @end smallexample
25414 @noindent
25415 will obviously raise @code{Program_Error} at run time, because function
25416 One will be called before its body is elaborated. In this case GNAT will
25417 generate a warning that the call will raise @code{Program_Error}:
25419 @smallexample
25420 @group
25421 @cartouche
25422  1. procedure y is
25423  2.    function One return Float;
25424  3.
25425  4.    Q : Float := One;
25426                     |
25427     >>> warning: cannot call "One" before body is elaborated
25428     >>> warning: Program_Error will be raised at run time
25430  5.
25431  6.    function One return Float is
25432  7.    begin
25433  8.         return 1.0;
25434  9.    end One;
25436 11. begin
25437 12.    null;
25438 13. end;
25439 @end cartouche
25440 @end group
25441 @end smallexample
25443 @noindent
25444 Note that in this particular case, it is likely that the call is safe, because
25445 the function @code{One} does not access any global variables.
25446 Nevertheless in Ada, we do not want the validity of the check to depend on
25447 the contents of the body (think about the separate compilation case), so this
25448 is still wrong, as we discussed in the previous sections.
25450 The error is easily corrected by rearranging the declarations so that the
25451 body of @code{One} appears before the declaration containing the call
25452 (note that in Ada 95 and Ada 2005,
25453 declarations can appear in any order, so there is no restriction that
25454 would prevent this reordering, and if we write:
25456 @smallexample @c ada
25457 @group
25458 @cartouche
25459 function One return Float;
25461 function One return Float is
25462 begin
25463      return 1.0;
25464 end One;
25466 Q : Float := One;
25467 @end cartouche
25468 @end group
25469 @end smallexample
25471 @noindent
25472 then all is well, no warning is generated, and no
25473 @code{Program_Error} exception
25474 will be raised.
25475 Things are more complicated when a chain of subprograms is executed:
25477 @smallexample @c ada
25478 @group
25479 @cartouche
25480 function A return Integer;
25481 function B return Integer;
25482 function C return Integer;
25484 function B return Integer is begin return A; end;
25485 function C return Integer is begin return B; end;
25487 X : Integer := C;
25489 function A return Integer is begin return 1; end;
25490 @end cartouche
25491 @end group
25492 @end smallexample
25494 @noindent
25495 Now the call to @code{C}
25496 at elaboration time in the declaration of @code{X} is correct, because
25497 the body of @code{C} is already elaborated,
25498 and the call to @code{B} within the body of
25499 @code{C} is correct, but the call
25500 to @code{A} within the body of @code{B} is incorrect, because the body
25501 of @code{A} has not been elaborated, so @code{Program_Error}
25502 will be raised on the call to @code{A}.
25503 In this case GNAT will generate a
25504 warning that @code{Program_Error} may be
25505 raised at the point of the call. Let's look at the warning:
25507 @smallexample
25508 @group
25509 @cartouche
25510  1. procedure x is
25511  2.    function A return Integer;
25512  3.    function B return Integer;
25513  4.    function C return Integer;
25514  5.
25515  6.    function B return Integer is begin return A; end;
25516                                                     |
25517     >>> warning: call to "A" before body is elaborated may
25518                  raise Program_Error
25519     >>> warning: "B" called at line 7
25520     >>> warning: "C" called at line 9
25522  7.    function C return Integer is begin return B; end;
25523  8.
25524  9.    X : Integer := C;
25526 11.    function A return Integer is begin return 1; end;
25528 13. begin
25529 14.    null;
25530 15. end;
25531 @end cartouche
25532 @end group
25533 @end smallexample
25535 @noindent
25536 Note that the message here says ``may raise'', instead of the direct case,
25537 where the message says ``will be raised''. That's because whether
25538 @code{A} is
25539 actually called depends in general on run-time flow of control.
25540 For example, if the body of @code{B} said
25542 @smallexample @c ada
25543 @group
25544 @cartouche
25545 function B return Integer is
25546 begin
25547    if some-condition-depending-on-input-data then
25548       return A;
25549    else
25550       return 1;
25551    end if;
25552 end B;
25553 @end cartouche
25554 @end group
25555 @end smallexample
25557 @noindent
25558 then we could not know until run time whether the incorrect call to A would
25559 actually occur, so @code{Program_Error} might
25560 or might not be raised. It is possible for a compiler to
25561 do a better job of analyzing bodies, to
25562 determine whether or not @code{Program_Error}
25563 might be raised, but it certainly
25564 couldn't do a perfect job (that would require solving the halting problem
25565 and is provably impossible), and because this is a warning anyway, it does
25566 not seem worth the effort to do the analysis. Cases in which it
25567 would be relevant are rare.
25569 In practice, warnings of either of the forms given
25570 above will usually correspond to
25571 real errors, and should be examined carefully and eliminated.
25572 In the rare case where a warning is bogus, it can be suppressed by any of
25573 the following methods:
25575 @itemize @bullet
25576 @item
25577 Compile with the @option{-gnatws} switch set
25579 @item
25580 Suppress @code{Elaboration_Check} for the called subprogram
25582 @item
25583 Use pragma @code{Warnings_Off} to turn warnings off for the call
25584 @end itemize
25586 @noindent
25587 For the internal elaboration check case,
25588 GNAT by default generates the
25589 necessary run-time checks to ensure
25590 that @code{Program_Error} is raised if any
25591 call fails an elaboration check. Of course this can only happen if a
25592 warning has been issued as described above. The use of pragma
25593 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25594 some of these checks, meaning that it may be possible (but is not
25595 guaranteed) for a program to be able to call a subprogram whose body
25596 is not yet elaborated, without raising a @code{Program_Error} exception.
25598 @node Controlling Elaboration in GNAT - External Calls
25599 @section Controlling Elaboration in GNAT - External Calls
25601 @noindent
25602 The previous section discussed the case in which the execution of a
25603 particular thread of elaboration code occurred entirely within a
25604 single unit. This is the easy case to handle, because a programmer
25605 has direct and total control over the order of elaboration, and
25606 furthermore, checks need only be generated in cases which are rare
25607 and which the compiler can easily detect.
25608 The situation is more complex when separate compilation is taken into account.
25609 Consider the following:
25611 @smallexample @c ada
25612 @cartouche
25613 @group
25614 package Math is
25615    function Sqrt (Arg : Float) return Float;
25616 end Math;
25618 package body Math is
25619    function Sqrt (Arg : Float) return Float is
25620    begin
25621          @dots{}
25622    end Sqrt;
25623 end Math;
25624 @end group
25625 @group
25626 with Math;
25627 package Stuff is
25628    X : Float := Math.Sqrt (0.5);
25629 end Stuff;
25631 with Stuff;
25632 procedure Main is
25633 begin
25634    @dots{}
25635 end Main;
25636 @end group
25637 @end cartouche
25638 @end smallexample
25640 @noindent
25641 where @code{Main} is the main program. When this program is executed, the
25642 elaboration code must first be executed, and one of the jobs of the
25643 binder is to determine the order in which the units of a program are
25644 to be elaborated. In this case we have four units: the spec and body
25645 of @code{Math},
25646 the spec of @code{Stuff} and the body of @code{Main}).
25647 In what order should the four separate sections of elaboration code
25648 be executed?
25650 There are some restrictions in the order of elaboration that the binder
25651 can choose. In particular, if unit U has a @code{with}
25652 for a package @code{X}, then you
25653 are assured that the spec of @code{X}
25654 is elaborated before U , but you are
25655 not assured that the body of @code{X}
25656 is elaborated before U.
25657 This means that in the above case, the binder is allowed to choose the
25658 order:
25660 @smallexample
25661 spec of Math
25662 spec of Stuff
25663 body of Math
25664 body of Main
25665 @end smallexample
25667 @noindent
25668 but that's not good, because now the call to @code{Math.Sqrt}
25669 that happens during
25670 the elaboration of the @code{Stuff}
25671 spec happens before the body of @code{Math.Sqrt} is
25672 elaborated, and hence causes @code{Program_Error} exception to be raised.
25673 At first glance, one might say that the binder is misbehaving, because
25674 obviously you want to elaborate the body of something you @code{with}
25675 first, but
25676 that is not a general rule that can be followed in all cases. Consider
25678 @smallexample @c ada
25679 @group
25680 @cartouche
25681 package X is @dots{}
25683 package Y is @dots{}
25685 with X;
25686 package body Y is @dots{}
25688 with Y;
25689 package body X is @dots{}
25690 @end cartouche
25691 @end group
25692 @end smallexample
25694 @noindent
25695 This is a common arrangement, and, apart from the order of elaboration
25696 problems that might arise in connection with elaboration code, this works fine.
25697 A rule that says that you must first elaborate the body of anything you
25698 @code{with} cannot work in this case:
25699 the body of @code{X} @code{with}'s @code{Y},
25700 which means you would have to
25701 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
25702 which means
25703 you have to elaborate the body of @code{X} first, but @dots{} and we have a
25704 loop that cannot be broken.
25706 It is true that the binder can in many cases guess an order of elaboration
25707 that is unlikely to cause a @code{Program_Error}
25708 exception to be raised, and it tries to do so (in the
25709 above example of @code{Math/Stuff/Spec}, the GNAT binder will
25710 by default
25711 elaborate the body of @code{Math} right after its spec, so all will be well).
25713 However, a program that blindly relies on the binder to be helpful can
25714 get into trouble, as we discussed in the previous sections, so
25715 GNAT
25716 provides a number of facilities for assisting the programmer in
25717 developing programs that are robust with respect to elaboration order.
25719 @node Default Behavior in GNAT - Ensuring Safety
25720 @section Default Behavior in GNAT - Ensuring Safety
25722 @noindent
25723 The default behavior in GNAT ensures elaboration safety. In its
25724 default mode GNAT implements the
25725 rule we previously described as the right approach. Let's restate it:
25727 @itemize
25728 @item
25729 @emph{If a unit has elaboration code that can directly or indirectly make a
25730 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
25731 package in a @code{with}'ed unit, then if the @code{with}'ed unit
25732 does not have pragma @code{Pure} or
25733 @code{Preelaborate}, then the client should have an
25734 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
25736 @emph{In the case of instantiating a generic subprogram, it is always
25737 sufficient to have only an @code{Elaborate} pragma for the
25738 @code{with}'ed unit.}
25739 @end itemize
25741 @noindent
25742 By following this rule a client is assured that calls and instantiations
25743 can be made without risk of an exception.
25745 In this mode GNAT traces all calls that are potentially made from
25746 elaboration code, and puts in any missing implicit @code{Elaborate}
25747 and @code{Elaborate_All} pragmas.
25748 The advantage of this approach is that no elaboration problems
25749 are possible if the binder can find an elaboration order that is
25750 consistent with these implicit @code{Elaborate} and
25751 @code{Elaborate_All} pragmas. The
25752 disadvantage of this approach is that no such order may exist.
25754 If the binder does not generate any diagnostics, then it means that it has
25755 found an elaboration order that is guaranteed to be safe. However, the binder
25756 may still be relying on implicitly generated @code{Elaborate} and
25757 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
25758 guaranteed.
25760 If it is important to guarantee portability, then the compilations should
25761 use the
25762 @option{-gnatwl}
25763 (warn on elaboration problems) switch. This will cause warning messages
25764 to be generated indicating the missing @code{Elaborate} and
25765 @code{Elaborate_All} pragmas.
25766 Consider the following source program:
25768 @smallexample @c ada
25769 @group
25770 @cartouche
25771 with k;
25772 package j is
25773   m : integer := k.r;
25774 end;
25775 @end cartouche
25776 @end group
25777 @end smallexample
25779 @noindent
25780 where it is clear that there
25781 should be a pragma @code{Elaborate_All}
25782 for unit @code{k}. An implicit pragma will be generated, and it is
25783 likely that the binder will be able to honor it. However, if you want
25784 to port this program to some other Ada compiler than GNAT.
25785 it is safer to include the pragma explicitly in the source. If this
25786 unit is compiled with the
25787 @option{-gnatwl}
25788 switch, then the compiler outputs a warning:
25790 @smallexample
25791 @group
25792 @cartouche
25793 1. with k;
25794 2. package j is
25795 3.   m : integer := k.r;
25796                      |
25797    >>> warning: call to "r" may raise Program_Error
25798    >>> warning: missing pragma Elaborate_All for "k"
25800 4. end;
25801 @end cartouche
25802 @end group
25803 @end smallexample
25805 @noindent
25806 and these warnings can be used as a guide for supplying manually
25807 the missing pragmas. It is usually a bad idea to use this warning
25808 option during development. That's because it will warn you when
25809 you need to put in a pragma, but cannot warn you when it is time
25810 to take it out. So the use of pragma @code{Elaborate_All} may lead to
25811 unnecessary dependencies and even false circularities.
25813 This default mode is more restrictive than the Ada Reference
25814 Manual, and it is possible to construct programs which will compile
25815 using the dynamic model described there, but will run into a
25816 circularity using the safer static model we have described.
25818 Of course any Ada compiler must be able to operate in a mode
25819 consistent with the requirements of the Ada Reference Manual,
25820 and in particular must have the capability of implementing the
25821 standard dynamic model of elaboration with run-time checks.
25823 In GNAT, this standard mode can be achieved either by the use of
25824 the @option{-gnatE} switch on the compiler (@command{gcc} or
25825 @command{gnatmake}) command, or by the use of the configuration pragma:
25827 @smallexample @c ada
25828 pragma Elaboration_Checks (DYNAMIC);
25829 @end smallexample
25831 @noindent
25832 Either approach will cause the unit affected to be compiled using the
25833 standard dynamic run-time elaboration checks described in the Ada
25834 Reference Manual. The static model is generally preferable, since it
25835 is clearly safer to rely on compile and link time checks rather than
25836 run-time checks. However, in the case of legacy code, it may be
25837 difficult to meet the requirements of the static model. This
25838 issue is further discussed in
25839 @ref{What to Do If the Default Elaboration Behavior Fails}.
25841 Note that the static model provides a strict subset of the allowed
25842 behavior and programs of the Ada Reference Manual, so if you do
25843 adhere to the static model and no circularities exist,
25844 then you are assured that your program will
25845 work using the dynamic model, providing that you remove any
25846 pragma Elaborate statements from the source.
25848 @node Treatment of Pragma Elaborate
25849 @section Treatment of Pragma Elaborate
25850 @cindex Pragma Elaborate
25852 @noindent
25853 The use of @code{pragma Elaborate}
25854 should generally be avoided in Ada 95 and Ada 2005 programs,
25855 since there is no guarantee that transitive calls
25856 will be properly handled. Indeed at one point, this pragma was placed
25857 in Annex J (Obsolescent Features), on the grounds that it is never useful.
25859 Now that's a bit restrictive. In practice, the case in which
25860 @code{pragma Elaborate} is useful is when the caller knows that there
25861 are no transitive calls, or that the called unit contains all necessary
25862 transitive @code{pragma Elaborate} statements, and legacy code often
25863 contains such uses.
25865 Strictly speaking the static mode in GNAT should ignore such pragmas,
25866 since there is no assurance at compile time that the necessary safety
25867 conditions are met. In practice, this would cause GNAT to be incompatible
25868 with correctly written Ada 83 code that had all necessary
25869 @code{pragma Elaborate} statements in place. Consequently, we made the
25870 decision that GNAT in its default mode will believe that if it encounters
25871 a @code{pragma Elaborate} then the programmer knows what they are doing,
25872 and it will trust that no elaboration errors can occur.
25874 The result of this decision is two-fold. First to be safe using the
25875 static mode, you should remove all @code{pragma Elaborate} statements.
25876 Second, when fixing circularities in existing code, you can selectively
25877 use @code{pragma Elaborate} statements to convince the static mode of
25878 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
25879 statement.
25881 When using the static mode with @option{-gnatwl}, any use of
25882 @code{pragma Elaborate} will generate a warning about possible
25883 problems.
25885 @node Elaboration Issues for Library Tasks
25886 @section Elaboration Issues for Library Tasks
25887 @cindex Library tasks, elaboration issues
25888 @cindex Elaboration of library tasks
25890 @noindent
25891 In this section we examine special elaboration issues that arise for
25892 programs that declare library level tasks.
25894 Generally the model of execution of an Ada program is that all units are
25895 elaborated, and then execution of the program starts. However, the
25896 declaration of library tasks definitely does not fit this model. The
25897 reason for this is that library tasks start as soon as they are declared
25898 (more precisely, as soon as the statement part of the enclosing package
25899 body is reached), that is to say before elaboration
25900 of the program is complete. This means that if such a task calls a
25901 subprogram, or an entry in another task, the callee may or may not be
25902 elaborated yet, and in the standard
25903 Reference Manual model of dynamic elaboration checks, you can even
25904 get timing dependent Program_Error exceptions, since there can be
25905 a race between the elaboration code and the task code.
25907 The static model of elaboration in GNAT seeks to avoid all such
25908 dynamic behavior, by being conservative, and the conservative
25909 approach in this particular case is to assume that all the code
25910 in a task body is potentially executed at elaboration time if
25911 a task is declared at the library level.
25913 This can definitely result in unexpected circularities. Consider
25914 the following example
25916 @smallexample @c ada
25917 package Decls is
25918   task Lib_Task is
25919      entry Start;
25920   end Lib_Task;
25922   type My_Int is new Integer;
25924   function Ident (M : My_Int) return My_Int;
25925 end Decls;
25927 with Utils;
25928 package body Decls is
25929   task body Lib_Task is
25930   begin
25931      accept Start;
25932      Utils.Put_Val (2);
25933   end Lib_Task;
25935   function Ident (M : My_Int) return My_Int is
25936   begin
25937      return M;
25938   end Ident;
25939 end Decls;
25941 with Decls;
25942 package Utils is
25943   procedure Put_Val (Arg : Decls.My_Int);
25944 end Utils;
25946 with Text_IO;
25947 package body Utils is
25948   procedure Put_Val (Arg : Decls.My_Int) is
25949   begin
25950      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25951   end Put_Val;
25952 end Utils;
25954 with Decls;
25955 procedure Main is
25956 begin
25957    Decls.Lib_Task.Start;
25958 end;
25959 @end smallexample
25961 @noindent
25962 If the above example is compiled in the default static elaboration
25963 mode, then a circularity occurs. The circularity comes from the call
25964 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
25965 this call occurs in elaboration code, we need an implicit pragma
25966 @code{Elaborate_All} for @code{Utils}. This means that not only must
25967 the spec and body of @code{Utils} be elaborated before the body
25968 of @code{Decls}, but also the spec and body of any unit that is
25969 @code{with'ed} by the body of @code{Utils} must also be elaborated before
25970 the body of @code{Decls}. This is the transitive implication of
25971 pragma @code{Elaborate_All} and it makes sense, because in general
25972 the body of @code{Put_Val} might have a call to something in a
25973 @code{with'ed} unit.
25975 In this case, the body of Utils (actually its spec) @code{with's}
25976 @code{Decls}. Unfortunately this means that the body of @code{Decls}
25977 must be elaborated before itself, in case there is a call from the
25978 body of @code{Utils}.
25980 Here is the exact chain of events we are worrying about:
25982 @enumerate
25983 @item
25984 In the body of @code{Decls} a call is made from within the body of a library
25985 task to a subprogram in the package @code{Utils}. Since this call may
25986 occur at elaboration time (given that the task is activated at elaboration
25987 time), we have to assume the worst, i.e., that the
25988 call does happen at elaboration time.
25990 @item
25991 This means that the body and spec of @code{Util} must be elaborated before
25992 the body of @code{Decls} so that this call does not cause an access before
25993 elaboration.
25995 @item
25996 Within the body of @code{Util}, specifically within the body of
25997 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
25998 by this package.
26000 @item
26001 One such @code{with}'ed package is package @code{Decls}, so there
26002 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26003 In fact there is such a call in this example, but we would have to
26004 assume that there was such a call even if it were not there, since
26005 we are not supposed to write the body of @code{Decls} knowing what
26006 is in the body of @code{Utils}; certainly in the case of the
26007 static elaboration model, the compiler does not know what is in
26008 other bodies and must assume the worst.
26010 @item
26011 This means that the spec and body of @code{Decls} must also be
26012 elaborated before we elaborate the unit containing the call, but
26013 that unit is @code{Decls}! This means that the body of @code{Decls}
26014 must be elaborated before itself, and that's a circularity.
26015 @end enumerate
26017 @noindent
26018 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26019 the body of @code{Decls} you will get a true Ada Reference Manual
26020 circularity that makes the program illegal.
26022 In practice, we have found that problems with the static model of
26023 elaboration in existing code often arise from library tasks, so
26024 we must address this particular situation.
26026 Note that if we compile and run the program above, using the dynamic model of
26027 elaboration (that is to say use the @option{-gnatE} switch),
26028 then it compiles, binds,
26029 links, and runs, printing the expected result of 2. Therefore in some sense
26030 the circularity here is only apparent, and we need to capture
26031 the properties of this program that  distinguish it from other library-level
26032 tasks that have real elaboration problems.
26034 We have four possible answers to this question:
26036 @itemize @bullet
26038 @item
26039 Use the dynamic model of elaboration.
26041 If we use the @option{-gnatE} switch, then as noted above, the program works.
26042 Why is this? If we examine the task body, it is apparent that the task cannot
26043 proceed past the
26044 @code{accept} statement until after elaboration has been completed, because
26045 the corresponding entry call comes from the main program, not earlier.
26046 This is why the dynamic model works here. But that's really giving
26047 up on a precise analysis, and we prefer to take this approach only if we cannot
26048 solve the
26049 problem in any other manner. So let us examine two ways to reorganize
26050 the program to avoid the potential elaboration problem.
26052 @item
26053 Split library tasks into separate packages.
26055 Write separate packages, so that library tasks are isolated from
26056 other declarations as much as possible. Let us look at a variation on
26057 the above program.
26059 @smallexample @c ada
26060 package Decls1 is
26061   task Lib_Task is
26062      entry Start;
26063   end Lib_Task;
26064 end Decls1;
26066 with Utils;
26067 package body Decls1 is
26068   task body Lib_Task is
26069   begin
26070      accept Start;
26071      Utils.Put_Val (2);
26072   end Lib_Task;
26073 end Decls1;
26075 package Decls2 is
26076   type My_Int is new Integer;
26077   function Ident (M : My_Int) return My_Int;
26078 end Decls2;
26080 with Utils;
26081 package body Decls2 is
26082   function Ident (M : My_Int) return My_Int is
26083   begin
26084      return M;
26085   end Ident;
26086 end Decls2;
26088 with Decls2;
26089 package Utils is
26090   procedure Put_Val (Arg : Decls2.My_Int);
26091 end Utils;
26093 with Text_IO;
26094 package body Utils is
26095   procedure Put_Val (Arg : Decls2.My_Int) is
26096   begin
26097      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26098   end Put_Val;
26099 end Utils;
26101 with Decls1;
26102 procedure Main is
26103 begin
26104    Decls1.Lib_Task.Start;
26105 end;
26106 @end smallexample
26108 @noindent
26109 All we have done is to split @code{Decls} into two packages, one
26110 containing the library task, and one containing everything else. Now
26111 there is no cycle, and the program compiles, binds, links and executes
26112 using the default static model of elaboration.
26114 @item
26115 Declare separate task types.
26117 A significant part of the problem arises because of the use of the
26118 single task declaration form. This means that the elaboration of
26119 the task type, and the elaboration of the task itself (i.e.@: the
26120 creation of the task) happen at the same time. A good rule
26121 of style in Ada is to always create explicit task types. By
26122 following the additional step of placing task objects in separate
26123 packages from the task type declaration, many elaboration problems
26124 are avoided. Here is another modified example of the example program:
26126 @smallexample @c ada
26127 package Decls is
26128   task type Lib_Task_Type is
26129      entry Start;
26130   end Lib_Task_Type;
26132   type My_Int is new Integer;
26134   function Ident (M : My_Int) return My_Int;
26135 end Decls;
26137 with Utils;
26138 package body Decls is
26139   task body Lib_Task_Type is
26140   begin
26141      accept Start;
26142      Utils.Put_Val (2);
26143   end Lib_Task_Type;
26145   function Ident (M : My_Int) return My_Int is
26146   begin
26147      return M;
26148   end Ident;
26149 end Decls;
26151 with Decls;
26152 package Utils is
26153   procedure Put_Val (Arg : Decls.My_Int);
26154 end Utils;
26156 with Text_IO;
26157 package body Utils is
26158   procedure Put_Val (Arg : Decls.My_Int) is
26159   begin
26160      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26161   end Put_Val;
26162 end Utils;
26164 with Decls;
26165 package Declst is
26166    Lib_Task : Decls.Lib_Task_Type;
26167 end Declst;
26169 with Declst;
26170 procedure Main is
26171 begin
26172    Declst.Lib_Task.Start;
26173 end;
26174 @end smallexample
26176 @noindent
26177 What we have done here is to replace the @code{task} declaration in
26178 package @code{Decls} with a @code{task type} declaration. Then we
26179 introduce a separate package @code{Declst} to contain the actual
26180 task object. This separates the elaboration issues for
26181 the @code{task type}
26182 declaration, which causes no trouble, from the elaboration issues
26183 of the task object, which is also unproblematic, since it is now independent
26184 of the elaboration of  @code{Utils}.
26185 This separation of concerns also corresponds to
26186 a generally sound engineering principle of separating declarations
26187 from instances. This version of the program also compiles, binds, links,
26188 and executes, generating the expected output.
26190 @item
26191 Use No_Entry_Calls_In_Elaboration_Code restriction.
26192 @cindex No_Entry_Calls_In_Elaboration_Code
26194 The previous two approaches described how a program can be restructured
26195 to avoid the special problems caused by library task bodies. in practice,
26196 however, such restructuring may be difficult to apply to existing legacy code,
26197 so we must consider solutions that do not require massive rewriting.
26199 Let us consider more carefully why our original sample program works
26200 under the dynamic model of elaboration. The reason is that the code
26201 in the task body blocks immediately on the @code{accept}
26202 statement. Now of course there is nothing to prohibit elaboration
26203 code from making entry calls (for example from another library level task),
26204 so we cannot tell in isolation that
26205 the task will not execute the accept statement  during elaboration.
26207 However, in practice it is very unusual to see elaboration code
26208 make any entry calls, and the pattern of tasks starting
26209 at elaboration time and then immediately blocking on @code{accept} or
26210 @code{select} statements is very common. What this means is that
26211 the compiler is being too pessimistic when it analyzes the
26212 whole package body as though it might be executed at elaboration
26213 time.
26215 If we know that the elaboration code contains no entry calls, (a very safe
26216 assumption most of the time, that could almost be made the default
26217 behavior), then we can compile all units of the program under control
26218 of the following configuration pragma:
26220 @smallexample
26221 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26222 @end smallexample
26224 @noindent
26225 This pragma can be placed in the @file{gnat.adc} file in the usual
26226 manner. If we take our original unmodified program and compile it
26227 in the presence of a @file{gnat.adc} containing the above pragma,
26228 then once again, we can compile, bind, link, and execute, obtaining
26229 the expected result. In the presence of this pragma, the compiler does
26230 not trace calls in a task body, that appear after the first @code{accept}
26231 or @code{select} statement, and therefore does not report a potential
26232 circularity in the original program.
26234 The compiler will check to the extent it can that the above
26235 restriction is not violated, but it is not always possible to do a
26236 complete check at compile time, so it is important to use this
26237 pragma only if the stated restriction is in fact met, that is to say
26238 no task receives an entry call before elaboration of all units is completed.
26240 @end itemize
26242 @node Mixing Elaboration Models
26243 @section Mixing Elaboration Models
26244 @noindent
26245 So far, we have assumed that the entire program is either compiled
26246 using the dynamic model or static model, ensuring consistency. It
26247 is possible to mix the two models, but rules have to be followed
26248 if this mixing is done to ensure that elaboration checks are not
26249 omitted.
26251 The basic rule is that @emph{a unit compiled with the static model cannot
26252 be @code{with'ed} by a unit compiled with the dynamic model}. The
26253 reason for this is that in the static model, a unit assumes that
26254 its clients guarantee to use (the equivalent of) pragma
26255 @code{Elaborate_All} so that no elaboration checks are required
26256 in inner subprograms, and this assumption is violated if the
26257 client is compiled with dynamic checks.
26259 The precise rule is as follows. A unit that is compiled with dynamic
26260 checks can only @code{with} a unit that meets at least one of the
26261 following criteria:
26263 @itemize @bullet
26265 @item
26266 The @code{with'ed} unit is itself compiled with dynamic elaboration
26267 checks (that is with the @option{-gnatE} switch.
26269 @item
26270 The @code{with'ed} unit is an internal GNAT implementation unit from
26271 the System, Interfaces, Ada, or GNAT hierarchies.
26273 @item
26274 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26276 @item
26277 The @code{with'ing} unit (that is the client) has an explicit pragma
26278 @code{Elaborate_All} for the @code{with'ed} unit.
26280 @end itemize
26282 @noindent
26283 If this rule is violated, that is if a unit with dynamic elaboration
26284 checks @code{with's} a unit that does not meet one of the above four
26285 criteria, then the binder (@code{gnatbind}) will issue a warning
26286 similar to that in the following example:
26288 @smallexample
26289 warning: "x.ads" has dynamic elaboration checks and with's
26290 warning:   "y.ads" which has static elaboration checks
26291 @end smallexample
26293 @noindent
26294 These warnings indicate that the rule has been violated, and that as a result
26295 elaboration checks may be missed in the resulting executable file.
26296 This warning may be suppressed using the @option{-ws} binder switch
26297 in the usual manner.
26299 One useful application of this mixing rule is in the case of a subsystem
26300 which does not itself @code{with} units from the remainder of the
26301 application. In this case, the entire subsystem can be compiled with
26302 dynamic checks to resolve a circularity in the subsystem, while
26303 allowing the main application that uses this subsystem to be compiled
26304 using the more reliable default static model.
26306 @node What to Do If the Default Elaboration Behavior Fails
26307 @section What to Do If the Default Elaboration Behavior Fails
26309 @noindent
26310 If the binder cannot find an acceptable order, it outputs detailed
26311 diagnostics. For example:
26312 @smallexample
26313 @group
26314 @iftex
26315 @leftskip=0cm
26316 @end iftex
26317 error: elaboration circularity detected
26318 info:   "proc (body)" must be elaborated before "pack (body)"
26319 info:     reason: Elaborate_All probably needed in unit "pack (body)"
26320 info:     recompile "pack (body)" with -gnatwl
26321 info:                             for full details
26322 info:       "proc (body)"
26323 info:         is needed by its spec:
26324 info:       "proc (spec)"
26325 info:         which is withed by:
26326 info:       "pack (body)"
26327 info:  "pack (body)" must be elaborated before "proc (body)"
26328 info:     reason: pragma Elaborate in unit "proc (body)"
26329 @end group
26331 @end smallexample
26333 @noindent
26334 In this case we have a cycle that the binder cannot break. On the one
26335 hand, there is an explicit pragma Elaborate in @code{proc} for
26336 @code{pack}. This means that the body of @code{pack} must be elaborated
26337 before the body of @code{proc}. On the other hand, there is elaboration
26338 code in @code{pack} that calls a subprogram in @code{proc}. This means
26339 that for maximum safety, there should really be a pragma
26340 Elaborate_All in @code{pack} for @code{proc} which would require that
26341 the body of @code{proc} be elaborated before the body of
26342 @code{pack}. Clearly both requirements cannot be satisfied.
26343 Faced with a circularity of this kind, you have three different options.
26345 @table @asis
26346 @item Fix the program
26347 The most desirable option from the point of view of long-term maintenance
26348 is to rearrange the program so that the elaboration problems are avoided.
26349 One useful technique is to place the elaboration code into separate
26350 child packages. Another is to move some of the initialization code to
26351 explicitly called subprograms, where the program controls the order
26352 of initialization explicitly. Although this is the most desirable option,
26353 it may be impractical and involve too much modification, especially in
26354 the case of complex legacy code.
26356 @item Perform dynamic checks
26357 If the compilations are done using the
26358 @option{-gnatE}
26359 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26360 manner. Dynamic checks are generated for all calls that could possibly result
26361 in raising an exception. With this switch, the compiler does not generate
26362 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26363 exactly as specified in the @cite{Ada Reference Manual}.
26364 The binder will generate
26365 an executable program that may or may not raise @code{Program_Error}, and then
26366 it is the programmer's job to ensure that it does not raise an exception. Note
26367 that it is important to compile all units with the switch, it cannot be used
26368 selectively.
26370 @item Suppress checks
26371 The drawback of dynamic checks is that they generate a
26372 significant overhead at run time, both in space and time. If you
26373 are absolutely sure that your program cannot raise any elaboration
26374 exceptions, and you still want to use the dynamic elaboration model,
26375 then you can use the configuration pragma
26376 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26377 example this pragma could be placed in the @file{gnat.adc} file.
26379 @item Suppress checks selectively
26380 When you know that certain calls or instantiations in elaboration code cannot
26381 possibly lead to an elaboration error, and the binder nevertheless complains
26382 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26383 elaboration circularities, it is possible to remove those warnings locally and
26384 obtain a program that will bind. Clearly this can be unsafe, and it is the
26385 responsibility of the programmer to make sure that the resulting program has no
26386 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26387 used with different granularity to suppress warnings and break elaboration
26388 circularities:
26390 @itemize @bullet
26391 @item
26392 Place the pragma that names the called subprogram in the declarative part
26393 that contains the call.
26395 @item
26396 Place the pragma in the declarative part, without naming an entity. This
26397 disables warnings on all calls in the corresponding  declarative region.
26399 @item
26400 Place the pragma in the package spec that declares the called subprogram,
26401 and name the subprogram. This disables warnings on all elaboration calls to
26402 that subprogram.
26404 @item
26405 Place the pragma in the package spec that declares the called subprogram,
26406 without naming any entity. This disables warnings on all elaboration calls to
26407 all subprograms declared in this spec.
26409 @item Use Pragma Elaborate
26410 As previously described in section @xref{Treatment of Pragma Elaborate},
26411 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26412 that no elaboration checks are required on calls to the designated unit.
26413 There may be cases in which the caller knows that no transitive calls
26414 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26415 case where @code{pragma Elaborate_All} would cause a circularity.
26416 @end itemize
26418 @noindent
26419 These five cases are listed in order of decreasing safety, and therefore
26420 require increasing programmer care in their application. Consider the
26421 following program:
26423 @smallexample @c adanocomment
26424 package Pack1 is
26425   function F1 return Integer;
26426   X1 : Integer;
26427 end Pack1;
26429 package Pack2 is
26430   function F2 return Integer;
26431   function Pure (x : integer) return integer;
26432   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
26433   --  pragma Suppress (Elaboration_Check);              -- (4)
26434 end Pack2;
26436 with Pack2;
26437 package body Pack1 is
26438   function F1 return Integer is
26439   begin
26440     return 100;
26441   end F1;
26442   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
26443 begin
26444   declare
26445     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
26446     --  pragma Suppress(Elaboration_Check);             -- (2)
26447   begin
26448     X1 := Pack2.F2 + 1;                --  Elab. call (2)
26449   end;
26450 end Pack1;
26452 with Pack1;
26453 package body Pack2 is
26454   function F2 return Integer is
26455   begin
26456      return Pack1.F1;
26457   end F2;
26458   function Pure (x : integer) return integer is
26459   begin
26460      return x ** 3 - 3 * x;
26461   end;
26462 end Pack2;
26464 with Pack1, Ada.Text_IO;
26465 procedure Proc3 is
26466 begin
26467   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26468 end Proc3;
26469 @end smallexample
26470 In the absence of any pragmas, an attempt to bind this program produces
26471 the following diagnostics:
26472 @smallexample
26473 @group
26474 @iftex
26475 @leftskip=.5cm
26476 @end iftex
26477 error: elaboration circularity detected
26478 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
26479 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
26480 info:       recompile "pack1 (body)" with -gnatwl for full details
26481 info:          "pack1 (body)"
26482 info:             must be elaborated along with its spec:
26483 info:          "pack1 (spec)"
26484 info:             which is withed by:
26485 info:          "pack2 (body)"
26486 info:             which must be elaborated along with its spec:
26487 info:          "pack2 (spec)"
26488 info:             which is withed by:
26489 info:          "pack1 (body)"
26490 @end group
26491 @end smallexample
26492 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26493 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26494 F2 is safe, even though F2 calls F1, because the call appears after the
26495 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26496 remove the warning on the call. It is also possible to use pragma (2)
26497 because there are no other potentially unsafe calls in the block.
26499 @noindent
26500 The call to @code{Pure} is safe because this function does not depend on the
26501 state of @code{Pack2}. Therefore any call to this function is safe, and it
26502 is correct to place pragma (3) in the corresponding package spec.
26504 @noindent
26505 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26506 warnings on all calls to functions declared therein. Note that this is not
26507 necessarily safe, and requires more detailed examination of the subprogram
26508 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26509 be already elaborated.
26510 @end table
26512 @noindent
26513 It is hard to generalize on which of these four approaches should be
26514 taken. Obviously if it is possible to fix the program so that the default
26515 treatment works, this is preferable, but this may not always be practical.
26516 It is certainly simple enough to use
26517 @option{-gnatE}
26518 but the danger in this case is that, even if the GNAT binder
26519 finds a correct elaboration order, it may not always do so,
26520 and certainly a binder from another Ada compiler might not. A
26521 combination of testing and analysis (for which the warnings generated
26522 with the
26523 @option{-gnatwl}
26524 switch can be useful) must be used to ensure that the program is free
26525 of errors. One switch that is useful in this testing is the
26526 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26527 switch for
26528 @code{gnatbind}.
26529 Normally the binder tries to find an order that has the best chance
26530 of avoiding elaboration problems. However, if this switch is used, the binder
26531 plays a devil's advocate role, and tries to choose the order that
26532 has the best chance of failing. If your program works even with this
26533 switch, then it has a better chance of being error free, but this is still
26534 not a guarantee.
26536 For an example of this approach in action, consider the C-tests (executable
26537 tests) from the ACVC suite. If these are compiled and run with the default
26538 treatment, then all but one of them succeed without generating any error
26539 diagnostics from the binder. However, there is one test that fails, and
26540 this is not surprising, because the whole point of this test is to ensure
26541 that the compiler can handle cases where it is impossible to determine
26542 a correct order statically, and it checks that an exception is indeed
26543 raised at run time.
26545 This one test must be compiled and run using the
26546 @option{-gnatE}
26547 switch, and then it passes. Alternatively, the entire suite can
26548 be run using this switch. It is never wrong to run with the dynamic
26549 elaboration switch if your code is correct, and we assume that the
26550 C-tests are indeed correct (it is less efficient, but efficiency is
26551 not a factor in running the ACVC tests.)
26553 @node Elaboration for Dispatching Calls
26554 @section Elaboration for Dispatching Calls
26555 @cindex Dispatching calls
26557 @noindent
26558 In rare cases, the static elaboration model fails to prevent
26559 dispatching calls to not-yet-elaborated subprograms. In such cases, we
26560 fall back to run-time checks; premature calls to any primitive
26561 operation of a tagged type before the body of the operation has been
26562 elaborated will raise @code{Program_Error}.
26564 Access-to-subprogram types, however, are handled conservatively, and
26565 do not require run-time checks. This was not true in earlier versions
26566 of the compiler; you can use the @option{-gnatd.U} debug switch to
26567 revert to the old behavior if the new conservative behavior causes
26568 elaboration cycles.
26570 @node Summary of Procedures for Elaboration Control
26571 @section Summary of Procedures for Elaboration Control
26572 @cindex Elaboration control
26574 @noindent
26575 First, compile your program with the default options, using none of
26576 the special elaboration control switches. If the binder successfully
26577 binds your program, then you can be confident that, apart from issues
26578 raised by the use of access-to-subprogram types and dynamic dispatching,
26579 the program is free of elaboration errors. If it is important that the
26580 program be portable, then use the
26581 @option{-gnatwl}
26582 switch to generate warnings about missing @code{Elaborate} or
26583 @code{Elaborate_All} pragmas, and supply the missing pragmas.
26585 If the program fails to bind using the default static elaboration
26586 handling, then you can fix the program to eliminate the binder
26587 message, or recompile the entire program with the
26588 @option{-gnatE} switch to generate dynamic elaboration checks,
26589 and, if you are sure there really are no elaboration problems,
26590 use a global pragma @code{Suppress (Elaboration_Check)}.
26592 @node Other Elaboration Order Considerations
26593 @section Other Elaboration Order Considerations
26594 @noindent
26595 This section has been entirely concerned with the issue of finding a valid
26596 elaboration order, as defined by the Ada Reference Manual. In a case
26597 where several elaboration orders are valid, the task is to find one
26598 of the possible valid elaboration orders (and the static model in GNAT
26599 will ensure that this is achieved).
26601 The purpose of the elaboration rules in the Ada Reference Manual is to
26602 make sure that no entity is accessed before it has been elaborated. For
26603 a subprogram, this means that the spec and body must have been elaborated
26604 before the subprogram is called. For an object, this means that the object
26605 must have been elaborated before its value is read or written. A violation
26606 of either of these two requirements is an access before elaboration order,
26607 and this section has been all about avoiding such errors.
26609 In the case where more than one order of elaboration is possible, in the
26610 sense that access before elaboration errors are avoided, then any one of
26611 the orders is ``correct'' in the sense that it meets the requirements of
26612 the Ada Reference Manual, and no such error occurs.
26614 However, it may be the case for a given program, that there are
26615 constraints on the order of elaboration that come not from consideration
26616 of avoiding elaboration errors, but rather from extra-lingual logic
26617 requirements. Consider this example:
26619 @smallexample @c ada
26620 with Init_Constants;
26621 package Constants is
26622    X : Integer := 0;
26623    Y : Integer := 0;
26624 end Constants;
26626 package Init_Constants is
26627    procedure P; -- require a body
26628 end Init_Constants;
26630 with Constants;
26631 package body Init_Constants is
26632    procedure P is begin null; end;
26633 begin
26634    Constants.X := 3;
26635    Constants.Y := 4;
26636 end Init_Constants;
26638 with Constants;
26639 package Calc is
26640    Z : Integer := Constants.X + Constants.Y;
26641 end Calc;
26643 with Calc;
26644 with Text_IO; use Text_IO;
26645 procedure Main is
26646 begin
26647    Put_Line (Calc.Z'Img);
26648 end Main;
26649 @end smallexample
26651 @noindent
26652 In this example, there is more than one valid order of elaboration. For
26653 example both the following are correct orders:
26655 @smallexample
26656 Init_Constants spec
26657 Constants spec
26658 Calc spec
26659 Init_Constants body
26660 Main body
26662   and
26664 Init_Constants spec
26665 Init_Constants body
26666 Constants spec
26667 Calc spec
26668 Main body
26669 @end smallexample
26671 @noindent
26672 There is no language rule to prefer one or the other, both are correct
26673 from an order of elaboration point of view. But the programmatic effects
26674 of the two orders are very different. In the first, the elaboration routine
26675 of @code{Calc} initializes @code{Z} to zero, and then the main program
26676 runs with this value of zero. But in the second order, the elaboration
26677 routine of @code{Calc} runs after the body of Init_Constants has set
26678 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
26679 runs.
26681 One could perhaps by applying pretty clever non-artificial intelligence
26682 to the situation guess that it is more likely that the second order of
26683 elaboration is the one desired, but there is no formal linguistic reason
26684 to prefer one over the other. In fact in this particular case, GNAT will
26685 prefer the second order, because of the rule that bodies are elaborated
26686 as soon as possible, but it's just luck that this is what was wanted
26687 (if indeed the second order was preferred).
26689 If the program cares about the order of elaboration routines in a case like
26690 this, it is important to specify the order required. In this particular
26691 case, that could have been achieved by adding to the spec of Calc:
26693 @smallexample @c ada
26694 pragma Elaborate_All (Constants);
26695 @end smallexample
26697 @noindent
26698 which requires that the body (if any) and spec of @code{Constants},
26699 as well as the body and spec of any unit @code{with}'ed by
26700 @code{Constants} be elaborated before @code{Calc} is elaborated.
26702 Clearly no automatic method can always guess which alternative you require,
26703 and if you are working with legacy code that had constraints of this kind
26704 which were not properly specified by adding @code{Elaborate} or
26705 @code{Elaborate_All} pragmas, then indeed it is possible that two different
26706 compilers can choose different orders.
26708 However, GNAT does attempt to diagnose the common situation where there
26709 are uninitialized variables in the visible part of a package spec, and the
26710 corresponding package body has an elaboration block that directly or
26711 indirectly initialized one or more of these variables. This is the situation
26712 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
26713 a warning that suggests this addition if it detects this situation.
26715 The @code{gnatbind}
26716 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
26717 out problems. This switch causes bodies to be elaborated as late as possible
26718 instead of as early as possible. In the example above, it would have forced
26719 the choice of the first elaboration order. If you get different results
26720 when using this switch, and particularly if one set of results is right,
26721 and one is wrong as far as you are concerned, it shows that you have some
26722 missing @code{Elaborate} pragmas. For the example above, we have the
26723 following output:
26725 @smallexample
26726 gnatmake -f -q main
26727 main
26729 gnatmake -f -q main -bargs -p
26730 main
26732 @end smallexample
26734 @noindent
26735 It is of course quite unlikely that both these results are correct, so
26736 it is up to you in a case like this to investigate the source of the
26737 difference, by looking at the two elaboration orders that are chosen,
26738 and figuring out which is correct, and then adding the necessary
26739 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
26742 @c **********************************
26743 @node Overflow Check Handling in GNAT
26744 @appendix Overflow Check Handling in GNAT
26745 @cindex Overflow checks
26746 @cindex Checks (overflow)
26747 @c **********************************
26749 @menu
26750 * Background::
26751 * Overflow Checking Modes in GNAT::
26752 * Specifying the Desired Mode::
26753 * Default Settings::
26754 * Implementation Notes::
26755 @end menu
26758 @node Background
26759 @section Background
26761 @noindent
26762 Overflow checks are checks that the compiler may make to ensure
26763 that intermediate results are not out of range. For example:
26765 @smallexample @c ada
26766    A : Integer;
26767    ...
26768    A := A + 1;
26769 @end smallexample
26771 @noindent
26772 if @code{A} has the value @code{Integer'Last}, then the addition may cause
26773 overflow since the result is out of range of the type @code{Integer}.
26774 In this case @code{Constraint_Error} will be raised if checks are
26775 enabled.
26777 A trickier situation arises in examples like the following:
26779 @smallexample @c ada
26780   A, C : Integer;
26781   ...
26782   A := (A + 1) + C;
26783 @end smallexample
26785 @noindent
26786 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
26787 Now the final result of the expression on the right hand side is
26788 @code{Integer'Last} which is in range, but the question arises whether the
26789 intermediate addition of @code{(A + 1)} raises an overflow error.
26791 The (perhaps surprising) answer is that the Ada language
26792 definition does not answer this question. Instead it leaves
26793 it up to the implementation to do one of two things if overflow
26794 checks are enabled.
26796 @itemize @bullet
26797 @item
26798 raise an exception (@code{Constraint_Error}), or
26800 @item
26801 yield the correct mathematical result which is then used in
26802 subsequent operations.
26803 @end itemize
26805 @noindent
26806 If the compiler chooses the first approach, then the assignment of this
26807 example will indeed raise @code{Constraint_Error} if overflow checking is
26808 enabled, or result in erroneous execution if overflow checks are suppressed.
26810 But if the compiler
26811 chooses the second approach, then it can perform both additions yielding
26812 the correct mathematical result, which is in range, so no exception
26813 will be raised, and the right result is obtained, regardless of whether
26814 overflow checks are suppressed.
26816 Note that in the first example an
26817 exception will be raised in either case, since if the compiler
26818 gives the correct mathematical result for the addition, it will
26819 be out of range of the target type of the assignment, and thus
26820 fails the range check.
26822 This lack of specified behavior in the handling of overflow for
26823 intermediate results is a source of non-portability, and can thus
26824 be problematic when programs are ported. Most typically this arises
26825 in a situation where the original compiler did not raise an exception,
26826 and then the application is moved to a compiler where the check is
26827 performed on the intermediate result and an unexpected exception is
26828 raised.
26830 Furthermore, when using Ada 2012's preconditions and other
26831 assertion forms, another issue arises. Consider:
26833 @smallexample @c ada
26834      procedure P (A, B : Integer) with
26835        Pre => A + B <= Integer'Last;
26836 @end smallexample
26838 @noindent
26839 One often wants to regard arithmetic in a context like this from
26840 a mathematical point of view. So for example, if the two actual parameters
26841 for a call to @code{P} are both @code{Integer'Last}, then
26842 the precondition should be regarded as False. If we are executing
26843 in a mode with run-time checks enabled for preconditions, then we would
26844 like this precondition to fail, rather than raising an exception
26845 because of the intermediate overflow.
26847 However, the language definition leaves the specification of
26848 whether the above condition fails (raising @code{Assert_Error}) or
26849 causes an intermediate overflow (raising @code{Constraint_Error})
26850 up to the implementation.
26852 The situation is worse in a case such as the following:
26854 @smallexample @c ada
26855      procedure Q (A, B, C : Integer) with
26856        Pre => A + B + C <= Integer'Last;
26857 @end smallexample
26859 @noindent
26860 Consider the call
26862 @smallexample @c ada
26863      Q (A => Integer'Last, B => 1, C => -1);
26864 @end smallexample
26866 @noindent
26867 From a mathematical point of view the precondition
26868 is True, but at run time we may (but are not guaranteed to) get an
26869 exception raised because of the intermediate overflow (and we really
26870 would prefer this precondition to be considered True at run time).
26872 @node Overflow Checking Modes in GNAT
26873 @section Overflow Checking Modes in GNAT
26875 @noindent
26876 To deal with the portability issue, and with the problem of
26877 mathematical versus run-time interpretation of the expressions in
26878 assertions, GNAT provides comprehensive control over the handling
26879 of intermediate overflow. GNAT can operate in three modes, and
26880 furthemore, permits separate selection of operating modes for
26881 the expressions within assertions (here the term ``assertions''
26882 is used in the technical sense, which includes preconditions and so forth)
26883 and for expressions appearing outside assertions.
26885 The three modes are:
26887 @itemize @bullet
26888 @item   @i{Use base type for intermediate operations} (@code{STRICT})
26890      In this mode, all intermediate results for predefined arithmetic
26891      operators are computed using the base type, and the result must
26892      be in range of the base type. If this is not the
26893      case then either an exception is raised (if overflow checks are
26894      enabled) or the execution is erroneous (if overflow checks are suppressed).
26895      This is the normal default mode.
26897 @item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
26899      In this mode, the compiler attempts to avoid intermediate overflows by
26900      using a larger integer type, typically @code{Long_Long_Integer},
26901      as the type in which arithmetic is
26902      performed for predefined arithmetic operators. This may be slightly more
26903      expensive at
26904      run time (compared to suppressing intermediate overflow checks), though
26905      the cost is negligible on modern 64-bit machines. For the examples given
26906      earlier, no intermediate overflows would have resulted in exceptions,
26907      since the intermediate results are all in the range of
26908      @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
26909      of GNAT). In addition, if checks are enabled, this reduces the number of
26910      checks that must be made, so this choice may actually result in an
26911      improvement in space and time behavior.
26913      However, there are cases where @code{Long_Long_Integer} is not large
26914      enough, consider the following example:
26916 @smallexample @c ada
26917        procedure R (A, B, C, D : Integer) with
26918          Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
26919 @end smallexample
26921      where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
26922      Now the intermediate results are
26923      out of the range of @code{Long_Long_Integer} even though the final result
26924      is in range and the precondition is True (from a mathematical point
26925      of view). In such a case, operating in this mode, an overflow occurs
26926      for the intermediate computation (which is why this mode
26927      says @i{most} intermediate overflows are avoided). In this case,
26928      an exception is raised if overflow checks are enabled, and the
26929      execution is erroneous if overflow checks are suppressed.
26931 @item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
26933      In this mode, the compiler  avoids all intermediate overflows
26934      by using arbitrary precision arithmetic as required. In this
26935      mode, the above example with @code{A**2 * B**2} would
26936      not cause intermediate overflow, because the intermediate result
26937      would be evaluated using sufficient precision, and the result
26938      of evaluating the precondition would be True.
26940      This mode has the advantage of avoiding any intermediate
26941      overflows, but at the expense of significant run-time overhead,
26942      including the use of a library (included automatically in this
26943      mode) for multiple-precision arithmetic.
26945      This mode provides cleaner semantics for assertions, since now
26946      the run-time behavior emulates true arithmetic behavior for the
26947      predefined arithmetic operators, meaning that there is never a
26948      conflict between the mathematical view of the assertion, and its
26949      run-time behavior.
26951      Note that in this mode, the behavior is unaffected by whether or
26952      not overflow checks are suppressed, since overflow does not occur.
26953      It is possible for gigantic intermediate expressions to raise
26954      @code{Storage_Error} as a result of attempting to compute the
26955      results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
26956      but overflow is impossible.
26959 @end itemize
26961 @noindent
26962   Note that these modes apply only to the evaluation of predefined
26963   arithmetic, membership, and comparison operators for signed integer
26964   aritmetic.
26966   For fixed-point arithmetic, checks can be suppressed. But if checks
26967   are enabled
26968   then fixed-point values are always checked for overflow against the
26969   base type for intermediate expressions (that is such checks always
26970   operate in the equivalent of @code{STRICT} mode).
26972   For floating-point, on nearly all architectures, @code{Machine_Overflows}
26973   is False, and IEEE infinities are generated, so overflow exceptions
26974   are never raised. If you want to avoid infinities, and check that
26975   final results of expressions are in range, then you can declare a
26976   constrained floating-point type, and range checks will be carried
26977   out in the normal manner (with infinite values always failing all
26978   range checks).
26981 @c -------------------------
26982 @node Specifying the Desired Mode
26983 @section Specifying the Desired Mode
26985 @noindent
26986 The desired mode of for handling intermediate overflow can be specified using
26987 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
26988 The pragma has the form
26989 @cindex pragma @code{Overflow_Mode}
26991 @smallexample @c ada
26992     pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
26993 @end smallexample
26995 @noindent
26996 where @code{MODE} is one of
26998 @itemize @bullet
26999 @item   @code{STRICT}:  intermediate overflows checked (using base type)
27000 @item   @code{MINIMIZED}: minimize intermediate overflows
27001 @item   @code{ELIMINATED}: eliminate intermediate overflows
27002 @end itemize
27004 @noindent
27005 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
27006 @code{minimized} all have the same effect.
27008 If only the @code{General} parameter is present, then the given @code{MODE}
27009 applies
27010 to expressions both within and outside assertions. If both arguments
27011 are present, then @code{General} applies to expressions outside assertions,
27012 and @code{Assertions} applies to expressions within assertions. For example:
27014 @smallexample @c ada
27015    pragma Overflow_Mode
27016      (General => Minimized, Assertions => Eliminated);
27017 @end smallexample
27019 @noindent
27020 specifies that general expressions outside assertions be evaluated
27021 in ``minimize intermediate overflows'' mode, and expressions within
27022 assertions be evaluated in ``eliminate intermediate overflows'' mode.
27023 This is often a reasonable choice, avoiding excessive overhead
27024 outside assertions, but assuring a high degree of portability
27025 when importing code from another compiler, while incurring
27026 the extra overhead for assertion expressions to ensure that
27027 the behavior at run time matches the expected mathematical
27028 behavior.
27030 The @code{Overflow_Mode} pragma has the same scoping and placement
27031 rules as pragma @code{Suppress}, so it can occur either as a
27032 configuration pragma, specifying a default for the whole
27033 program, or in a declarative scope, where it applies to the
27034 remaining declarations and statements in that scope.
27036 Note that pragma @code{Overflow_Mode} does not affect whether
27037 overflow checks are enabled or suppressed. It only controls the
27038 method used to compute intermediate values. To control whether
27039 overflow checking is enabled or suppressed, use pragma @code{Suppress}
27040 or @code{Unsuppress} in the usual manner
27042 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
27043 can be used to control the checking mode default (which can be subsequently
27044 overridden using pragmas).
27045 @cindex @option{-gnato?} (gcc)
27046 @cindex @option{-gnato??} (gcc)
27048 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
27050 @itemize @bullet
27051 @item   @code{1}:
27052 use base type for intermediate operations (@code{STRICT})
27053 @item   @code{2}:
27054 minimize intermediate overflows (@code{MINIMIZED})
27055 @item   @code{3}:
27056 eliminate intermediate overflows (@code{ELIMINATED})
27057 @end itemize
27059 @noindent
27060 As with the pragma, if only one digit appears then it applies to all
27061 cases; if two digits are given, then the first applies outside
27062 assertions, and the second within assertions. Thus the equivalent
27063 of the example pragma above would be
27064 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
27066 If no digits follow the @option{-gnato}, then it is equivalent to
27067 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
27068 causing all intermediate operations to be computed using the base
27069 type (@code{STRICT} mode).
27071 In addition to setting the mode used for computation of intermediate
27072 results, the @code{-gnato} switch also enables overflow checking (which
27073 is suppressed by default). It thus combines the effect of using
27074 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
27077 @c -------------------------
27078 @node Default Settings
27079 @section Default Settings
27081 The default mode for overflow checks is
27083 @smallexample
27084    General => Strict
27085 @end smallexample
27087 @noindent
27088 which causes all computations both inside and outside assertions to use
27089 the base type. In addition overflow checks are suppressed.
27091 This retains compatibility with previous versions of
27092 GNAT which suppressed overflow checks by default and always
27093 used the base type for computation of intermediate results.
27095 The switch @option{-gnato} (with no digits following) is equivalent to
27096 @cindex @option{-gnato} (gcc)
27098 @smallexample
27099    General => Strict
27100 @end smallexample
27102 @noindent
27103 which causes overflow checking of all intermediate overflows
27104 both inside and outside assertions against the base type.
27105 This provides compatibility
27106 with this switch as implemented in previous versions of GNAT.
27108 The pragma @code{Suppress (Overflow_Check)} disables overflow
27109 checking, but it has no effect on the method used for computing
27110 intermediate results.
27112 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
27113 checking, but it has no effect on the method used for computing
27114 intermediate results.
27116 @c -------------------------
27117 @node Implementation Notes
27118 @section Implementation Notes
27120 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
27121 reasonably efficient, and can be generally used. It also helps
27122 to ensure compatibility with code imported from some other
27123 compiler to GNAT.
27125 Setting all intermediate overflows checking (@code{CHECKED} mode)
27126 makes sense if you want to
27127 make sure that your code is compatible with any other possible
27128 Ada implementation. This may be useful in ensuring portability
27129 for code that is to be exported to some other compiler than GNAT.
27132 The Ada standard allows the reassociation of expressions at
27133 the same precedence level if no parentheses are present. For
27134 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
27135 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
27136 introducing or eliminating an overflow exception. The GNAT
27137 compiler never takes advantage of this freedom, and the
27138 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
27139 If you need the other order, you can write the parentheses
27140 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
27142 The use of @code{ELIMINATED} mode will cause the compiler to
27143 automatically include an appropriate arbitrary precision
27144 integer arithmetic package. The compiler will make calls
27145 to this package, though only in cases where it cannot be
27146 sure that @code{Long_Long_Integer} is sufficient to guard against
27147 intermediate overflows. This package does not use dynamic
27148 alllocation, but it does use the secondary stack, so an
27149 appropriate secondary stack package must be present (this
27150 is always true for standard full Ada, but may require
27151 specific steps for restricted run times such as ZFP).
27153 Although @code{ELIMINATED} mode causes expressions to use arbitrary
27154 precision arithmetic, avoiding overflow, the final result
27155 must be in an appropriate range. This is true even if the
27156 final result is of type @code{[Long_[Long_]]Integer'Base}, which
27157 still has the same bounds as its associated constrained
27158 type at run-time.
27160 Currently, the @code{ELIMINATED} mode is only available on target
27161 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
27162 platforms).
27164 @c *******************************
27165 @node Conditional Compilation
27166 @appendix Conditional Compilation
27167 @c *******************************
27168 @cindex Conditional compilation
27170 @noindent
27171 It is often necessary to arrange for a single source program
27172 to serve multiple purposes, where it is compiled in different
27173 ways to achieve these different goals. Some examples of the
27174 need for this feature are
27176 @itemize @bullet
27177 @item  Adapting a program to a different hardware environment
27178 @item  Adapting a program to a different target architecture
27179 @item  Turning debugging features on and off
27180 @item  Arranging for a program to compile with different compilers
27181 @end itemize
27183 @noindent
27184 In C, or C++, the typical approach would be to use the preprocessor
27185 that is defined as part of the language. The Ada language does not
27186 contain such a feature. This is not an oversight, but rather a very
27187 deliberate design decision, based on the experience that overuse of
27188 the preprocessing features in C and C++ can result in programs that
27189 are extremely difficult to maintain. For example, if we have ten
27190 switches that can be on or off, this means that there are a thousand
27191 separate programs, any one of which might not even be syntactically
27192 correct, and even if syntactically correct, the resulting program
27193 might not work correctly. Testing all combinations can quickly become
27194 impossible.
27196 Nevertheless, the need to tailor programs certainly exists, and in
27197 this Appendix we will discuss how this can
27198 be achieved using Ada in general, and GNAT in particular.
27200 @menu
27201 * Use of Boolean Constants::
27202 * Debugging - A Special Case::
27203 * Conditionalizing Declarations::
27204 * Use of Alternative Implementations::
27205 * Preprocessing::
27206 @end menu
27208 @node Use of Boolean Constants
27209 @section Use of Boolean Constants
27211 @noindent
27212 In the case where the difference is simply which code
27213 sequence is executed, the cleanest solution is to use Boolean
27214 constants to control which code is executed.
27216 @smallexample @c ada
27217 @group
27218 FP_Initialize_Required : constant Boolean := True;
27219 @dots{}
27220 if FP_Initialize_Required then
27221 @dots{}
27222 end if;
27223 @end group
27224 @end smallexample
27226 @noindent
27227 Not only will the code inside the @code{if} statement not be executed if
27228 the constant Boolean is @code{False}, but it will also be completely
27229 deleted from the program.
27230 However, the code is only deleted after the @code{if} statement
27231 has been checked for syntactic and semantic correctness.
27232 (In contrast, with preprocessors the code is deleted before the
27233 compiler ever gets to see it, so it is not checked until the switch
27234 is turned on.)
27235 @cindex Preprocessors (contrasted with conditional compilation)
27237 Typically the Boolean constants will be in a separate package,
27238 something like:
27240 @smallexample @c ada
27241 @group
27242 package Config is
27243    FP_Initialize_Required : constant Boolean := True;
27244    Reset_Available        : constant Boolean := False;
27245    @dots{}
27246 end Config;
27247 @end group
27248 @end smallexample
27250 @noindent
27251 The @code{Config} package exists in multiple forms for the various targets,
27252 with an appropriate script selecting the version of @code{Config} needed.
27253 Then any other unit requiring conditional compilation can do a @code{with}
27254 of @code{Config} to make the constants visible.
27257 @node Debugging - A Special Case
27258 @section Debugging - A Special Case
27260 @noindent
27261 A common use of conditional code is to execute statements (for example
27262 dynamic checks, or output of intermediate results) under control of a
27263 debug switch, so that the debugging behavior can be turned on and off.
27264 This can be done using a Boolean constant to control whether the code
27265 is active:
27267 @smallexample @c ada
27268 @group
27269 if Debugging then
27270    Put_Line ("got to the first stage!");
27271 end if;
27272 @end group
27273 @end smallexample
27275 @noindent
27278 @smallexample @c ada
27279 @group
27280 if Debugging and then Temperature > 999.0 then
27281    raise Temperature_Crazy;
27282 end if;
27283 @end group
27284 @end smallexample
27286 @noindent
27287 Since this is a common case, there are special features to deal with
27288 this in a convenient manner. For the case of tests, Ada 2005 has added
27289 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27290 @cindex pragma @code{Assert}
27291 on the @code{Assert} pragma that has always been available in GNAT, so this
27292 feature may be used with GNAT even if you are not using Ada 2005 features.
27293 The use of pragma @code{Assert} is described in
27294 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27295 example, the last test could be written:
27297 @smallexample @c ada
27298 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27299 @end smallexample
27301 @noindent
27302 or simply
27304 @smallexample @c ada
27305 pragma Assert (Temperature <= 999.0);
27306 @end smallexample
27308 @noindent
27309 In both cases, if assertions are active and the temperature is excessive,
27310 the exception @code{Assert_Failure} will be raised, with the given string in
27311 the first case or a string indicating the location of the pragma in the second
27312 case used as the exception message.
27314 You can turn assertions on and off by using the @code{Assertion_Policy}
27315 pragma.
27316 @cindex pragma @code{Assertion_Policy}
27317 This is an Ada 2005 pragma which is implemented in all modes by
27318 GNAT, but only in the latest versions of GNAT which include Ada 2005
27319 capability. Alternatively, you can use the @option{-gnata} switch
27320 @cindex @option{-gnata} switch
27321 to enable assertions from the command line (this is recognized by all versions
27322 of GNAT).
27324 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27325 @code{Debug} can be used:
27326 @cindex pragma @code{Debug}
27328 @smallexample @c ada
27329 pragma Debug (Put_Line ("got to the first stage!"));
27330 @end smallexample
27332 @noindent
27333 If debug pragmas are enabled, the argument, which must be of the form of
27334 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27335 Only one call can be present, but of course a special debugging procedure
27336 containing any code you like can be included in the program and then
27337 called in a pragma @code{Debug} argument as needed.
27339 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27340 construct is that pragma @code{Debug} can appear in declarative contexts,
27341 such as at the very beginning of a procedure, before local declarations have
27342 been elaborated.
27344 Debug pragmas are enabled using either the @option{-gnata} switch that also
27345 controls assertions, or with a separate Debug_Policy pragma.
27346 @cindex pragma @code{Debug_Policy}
27347 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27348 in Ada 95 and Ada 83 programs as well), and is analogous to
27349 pragma @code{Assertion_Policy} to control assertions.
27351 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27352 and thus they can appear in @file{gnat.adc} if you are not using a
27353 project file, or in the file designated to contain configuration pragmas
27354 in a project file.
27355 They then apply to all subsequent compilations. In practice the use of
27356 the @option{-gnata} switch is often the most convenient method of controlling
27357 the status of these pragmas.
27359 Note that a pragma is not a statement, so in contexts where a statement
27360 sequence is required, you can't just write a pragma on its own. You have
27361 to add a @code{null} statement.
27363 @smallexample @c ada
27364 @group
27365 if @dots{} then
27366    @dots{} -- some statements
27367 else
27368    pragma Assert (Num_Cases < 10);
27369    null;
27370 end if;
27371 @end group
27372 @end smallexample
27375 @node Conditionalizing Declarations
27376 @section Conditionalizing Declarations
27378 @noindent
27379 In some cases, it may be necessary to conditionalize declarations to meet
27380 different requirements. For example we might want a bit string whose length
27381 is set to meet some hardware message requirement.
27383 In some cases, it may be possible to do this using declare blocks controlled
27384 by conditional constants:
27386 @smallexample @c ada
27387 @group
27388 if Small_Machine then
27389    declare
27390       X : Bit_String (1 .. 10);
27391    begin
27392       @dots{}
27393    end;
27394 else
27395    declare
27396       X : Large_Bit_String (1 .. 1000);
27397    begin
27398       @dots{}
27399    end;
27400 end if;
27401 @end group
27402 @end smallexample
27404 @noindent
27405 Note that in this approach, both declarations are analyzed by the
27406 compiler so this can only be used where both declarations are legal,
27407 even though one of them will not be used.
27409 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27410 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27411 that are parameterized by these constants. For example
27413 @smallexample @c ada
27414 @group
27415 for Rec use
27416   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27417 end record;
27418 @end group
27419 @end smallexample
27421 @noindent
27422 If @code{Bits_Per_Word} is set to 32, this generates either
27424 @smallexample @c ada
27425 @group
27426 for Rec use
27427   Field1 at 0 range 0 .. 32;
27428 end record;
27429 @end group
27430 @end smallexample
27432 @noindent
27433 for the big endian case, or
27435 @smallexample @c ada
27436 @group
27437 for Rec use record
27438   Field1 at 0 range 10 .. 32;
27439 end record;
27440 @end group
27441 @end smallexample
27443 @noindent
27444 for the little endian case. Since a powerful subset of Ada expression
27445 notation is usable for creating static constants, clever use of this
27446 feature can often solve quite difficult problems in conditionalizing
27447 compilation (note incidentally that in Ada 95, the little endian
27448 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27449 need to define this one yourself).
27452 @node Use of Alternative Implementations
27453 @section Use of Alternative Implementations
27455 @noindent
27456 In some cases, none of the approaches described above are adequate. This
27457 can occur for example if the set of declarations required is radically
27458 different for two different configurations.
27460 In this situation, the official Ada way of dealing with conditionalizing
27461 such code is to write separate units for the different cases. As long as
27462 this does not result in excessive duplication of code, this can be done
27463 without creating maintenance problems. The approach is to share common
27464 code as far as possible, and then isolate the code and declarations
27465 that are different. Subunits are often a convenient method for breaking
27466 out a piece of a unit that is to be conditionalized, with separate files
27467 for different versions of the subunit for different targets, where the
27468 build script selects the right one to give to the compiler.
27469 @cindex Subunits (and conditional compilation)
27471 As an example, consider a situation where a new feature in Ada 2005
27472 allows something to be done in a really nice way. But your code must be able
27473 to compile with an Ada 95 compiler. Conceptually you want to say:
27475 @smallexample @c ada
27476 @group
27477 if Ada_2005 then
27478    @dots{} neat Ada 2005 code
27479 else
27480    @dots{} not quite as neat Ada 95 code
27481 end if;
27482 @end group
27483 @end smallexample
27485 @noindent
27486 where @code{Ada_2005} is a Boolean constant.
27488 But this won't work when @code{Ada_2005} is set to @code{False},
27489 since the @code{then} clause will be illegal for an Ada 95 compiler.
27490 (Recall that although such unreachable code would eventually be deleted
27491 by the compiler, it still needs to be legal.  If it uses features
27492 introduced in Ada 2005, it will be illegal in Ada 95.)
27494 So instead we write
27496 @smallexample @c ada
27497 procedure Insert is separate;
27498 @end smallexample
27500 @noindent
27501 Then we have two files for the subunit @code{Insert}, with the two sets of
27502 code.
27503 If the package containing this is called @code{File_Queries}, then we might
27504 have two files
27506 @itemize @bullet
27507 @item    @file{file_queries-insert-2005.adb}
27508 @item    @file{file_queries-insert-95.adb}
27509 @end itemize
27511 @noindent
27512 and the build script renames the appropriate file to
27514 @smallexample
27515 file_queries-insert.adb
27516 @end smallexample
27518 @noindent
27519 and then carries out the compilation.
27521 This can also be done with project files' naming schemes. For example:
27523 @smallexample @c project
27524 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27525 @end smallexample
27527 @noindent
27528 Note also that with project files it is desirable to use a different extension
27529 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27530 conflict may arise through another commonly used feature: to declare as part
27531 of the project a set of directories containing all the sources obeying the
27532 default naming scheme.
27534 The use of alternative units is certainly feasible in all situations,
27535 and for example the Ada part of the GNAT run-time is conditionalized
27536 based on the target architecture using this approach. As a specific example,
27537 consider the implementation of the AST feature in VMS. There is one
27538 spec:
27540 @smallexample
27541 s-asthan.ads
27542 @end smallexample
27544 @noindent
27545 which is the same for all architectures, and three bodies:
27547 @table @file
27548 @item    s-asthan.adb
27549 used for all non-VMS operating systems
27550 @item    s-asthan-vms-alpha.adb
27551 used for VMS on the Alpha
27552 @item    s-asthan-vms-ia64.adb
27553 used for VMS on the ia64
27554 @end table
27556 @noindent
27557 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27558 this operating system feature is not available, and the two remaining
27559 versions interface with the corresponding versions of VMS to provide
27560 VMS-compatible AST handling. The GNAT build script knows the architecture
27561 and operating system, and automatically selects the right version,
27562 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
27564 Another style for arranging alternative implementations is through Ada's
27565 access-to-subprogram facility.
27566 In case some functionality is to be conditionally included,
27567 you can declare an access-to-procedure variable @code{Ref} that is initialized
27568 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
27569 when appropriate.
27570 In some library package, set @code{Ref} to @code{Proc'Access} for some
27571 procedure @code{Proc} that performs the relevant processing.
27572 The initialization only occurs if the library package is included in the
27573 program.
27574 The same idea can also be implemented using tagged types and dispatching
27575 calls.
27578 @node Preprocessing
27579 @section Preprocessing
27580 @cindex Preprocessing
27582 @noindent
27583 Although it is quite possible to conditionalize code without the use of
27584 C-style preprocessing, as described earlier in this section, it is
27585 nevertheless convenient in some cases to use the C approach. Moreover,
27586 older Ada compilers have often provided some preprocessing capability,
27587 so legacy code may depend on this approach, even though it is not
27588 standard.
27590 To accommodate such use, GNAT provides a preprocessor (modeled to a large
27591 extent on the various preprocessors that have been used
27592 with legacy code on other compilers, to enable easier transition).
27594 The preprocessor may be used in two separate modes. It can be used quite
27595 separately from the compiler, to generate a separate output source file
27596 that is then fed to the compiler as a separate step. This is the
27597 @code{gnatprep} utility, whose use is fully described in
27598 @ref{Preprocessing with gnatprep}.
27599 @cindex @code{gnatprep}
27601 The preprocessing language allows such constructs as
27603 @smallexample
27604 @group
27605 #if DEBUG or else (PRIORITY > 4) then
27606    bunch of declarations
27607 #else
27608    completely different bunch of declarations
27609 #end if;
27610 @end group
27611 @end smallexample
27613 @noindent
27614 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
27615 defined either on the command line or in a separate file.
27617 The other way of running the preprocessor is even closer to the C style and
27618 often more convenient. In this approach the preprocessing is integrated into
27619 the compilation process. The compiler is fed the preprocessor input which
27620 includes @code{#if} lines etc, and then the compiler carries out the
27621 preprocessing internally and processes the resulting output.
27622 For more details on this approach, see @ref{Integrated Preprocessing}.
27625 @c *******************************
27626 @node Inline Assembler
27627 @appendix Inline Assembler
27628 @c *******************************
27630 @noindent
27631 If you need to write low-level software that interacts directly
27632 with the hardware, Ada provides two ways to incorporate assembly
27633 language code into your program.  First, you can import and invoke
27634 external routines written in assembly language, an Ada feature fully
27635 supported by GNAT@.  However, for small sections of code it may be simpler
27636 or more efficient to include assembly language statements directly
27637 in your Ada source program, using the facilities of the implementation-defined
27638 package @code{System.Machine_Code}, which incorporates the gcc
27639 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
27640 including the following:
27642 @itemize @bullet
27643 @item No need to use non-Ada tools
27644 @item Consistent interface over different targets
27645 @item Automatic usage of the proper calling conventions
27646 @item Access to Ada constants and variables
27647 @item Definition of intrinsic routines
27648 @item Possibility of inlining a subprogram comprising assembler code
27649 @item Code optimizer can take Inline Assembler code into account
27650 @end itemize
27652 This chapter presents a series of examples to show you how to use
27653 the Inline Assembler.  Although it focuses on the Intel x86,
27654 the general approach applies also to other processors.
27655 It is assumed that you are familiar with Ada
27656 and with assembly language programming.
27658 @menu
27659 * Basic Assembler Syntax::
27660 * A Simple Example of Inline Assembler::
27661 * Output Variables in Inline Assembler::
27662 * Input Variables in Inline Assembler::
27663 * Inlining Inline Assembler Code::
27664 * Other Asm Functionality::
27665 @end menu
27667 @c ---------------------------------------------------------------------------
27668 @node Basic Assembler Syntax
27669 @section Basic Assembler Syntax
27671 @noindent
27672 The assembler used by GNAT and gcc is based not on the Intel assembly
27673 language, but rather on a language that descends from the AT&T Unix
27674 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
27675 The following table summarizes the main features of @emph{as} syntax
27676 and points out the differences from the Intel conventions.
27677 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
27678 pre-processor) documentation for further information.
27680 @table @asis
27681 @item Register names
27682 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
27684 Intel: No extra punctuation; for example @code{eax}
27686 @item Immediate operand
27687 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
27689 Intel: No extra punctuation; for example @code{4}
27691 @item Address
27692 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
27694 Intel: No extra punctuation; for example @code{loc}
27696 @item Memory contents
27697 gcc / @emph{as}: No extra punctuation; for example @code{loc}
27699 Intel: Square brackets; for example @code{[loc]}
27701 @item Register contents
27702 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
27704 Intel: Square brackets; for example @code{[eax]}
27706 @item Hexadecimal numbers
27707 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
27709 Intel: Trailing ``h''; for example @code{A0h}
27711 @item Operand size
27712 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
27713 a 16-bit word
27715 Intel: Implicit, deduced by assembler; for example @code{mov}
27717 @item Instruction repetition
27718 gcc / @emph{as}: Split into two lines; for example
27720 @code{rep}
27722 @code{stosl}
27724 Intel: Keep on one line; for example @code{rep stosl}
27726 @item Order of operands
27727 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
27729 Intel: Destination first; for example @code{mov eax, 4}
27730 @end table
27732 @c ---------------------------------------------------------------------------
27733 @node A Simple Example of Inline Assembler
27734 @section A Simple Example of Inline Assembler
27736 @noindent
27737 The following example will generate a single assembly language statement,
27738 @code{nop}, which does nothing.  Despite its lack of run-time effect,
27739 the example will be useful in illustrating the basics of
27740 the Inline Assembler facility.
27742 @smallexample @c ada
27743 @group
27744 with System.Machine_Code; use System.Machine_Code;
27745 procedure Nothing is
27746 begin
27747    Asm ("nop");
27748 end Nothing;
27749 @end group
27750 @end smallexample
27752 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
27753 here it takes one parameter, a @emph{template string} that must be a static
27754 expression and that will form the generated instruction.
27755 @code{Asm} may be regarded as a compile-time procedure that parses
27756 the template string and additional parameters (none here),
27757 from which it generates a sequence of assembly language instructions.
27759 The examples in this chapter will illustrate several of the forms
27760 for invoking @code{Asm}; a complete specification of the syntax
27761 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
27762 Manual}.
27764 Under the standard GNAT conventions, the @code{Nothing} procedure
27765 should be in a file named @file{nothing.adb}.
27766 You can build the executable in the usual way:
27767 @smallexample
27768 gnatmake nothing
27769 @end smallexample
27770 However, the interesting aspect of this example is not its run-time behavior
27771 but rather the generated assembly code.
27772 To see this output, invoke the compiler as follows:
27773 @smallexample
27774    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
27775 @end smallexample
27776 where the options are:
27778 @table @code
27779 @item -c
27780 compile only (no bind or link)
27781 @item -S
27782 generate assembler listing
27783 @item -fomit-frame-pointer
27784 do not set up separate stack frames
27785 @item -gnatp
27786 do not add runtime checks
27787 @end table
27789 This gives a human-readable assembler version of the code. The resulting
27790 file will have the same name as the Ada source file, but with a @code{.s}
27791 extension. In our example, the file @file{nothing.s} has the following
27792 contents:
27794 @smallexample
27795 @group
27796 .file "nothing.adb"
27797 gcc2_compiled.:
27798 ___gnu_compiled_ada:
27799 .text
27800    .align 4
27801 .globl __ada_nothing
27802 __ada_nothing:
27803 #APP
27804    nop
27805 #NO_APP
27806    jmp L1
27807    .align 2,0x90
27809    ret
27810 @end group
27811 @end smallexample
27813 The assembly code you included is clearly indicated by
27814 the compiler, between the @code{#APP} and @code{#NO_APP}
27815 delimiters. The character before the 'APP' and 'NOAPP'
27816 can differ on different targets. For example, GNU/Linux uses '#APP' while
27817 on NT you will see '/APP'.
27819 If you make a mistake in your assembler code (such as using the
27820 wrong size modifier, or using a wrong operand for the instruction) GNAT
27821 will report this error in a temporary file, which will be deleted when
27822 the compilation is finished.  Generating an assembler file will help
27823 in such cases, since you can assemble this file separately using the
27824 @emph{as} assembler that comes with gcc.
27826 Assembling the file using the command
27828 @smallexample
27829 as @file{nothing.s}
27830 @end smallexample
27831 @noindent
27832 will give you error messages whose lines correspond to the assembler
27833 input file, so you can easily find and correct any mistakes you made.
27834 If there are no errors, @emph{as} will generate an object file
27835 @file{nothing.out}.
27837 @c ---------------------------------------------------------------------------
27838 @node Output Variables in Inline Assembler
27839 @section Output Variables in Inline Assembler
27841 @noindent
27842 The examples in this section, showing how to access the processor flags,
27843 illustrate how to specify the destination operands for assembly language
27844 statements.
27846 @smallexample @c ada
27847 @group
27848 with Interfaces; use Interfaces;
27849 with Ada.Text_IO; use Ada.Text_IO;
27850 with System.Machine_Code; use System.Machine_Code;
27851 procedure Get_Flags is
27852    Flags : Unsigned_32;
27853    use ASCII;
27854 begin
27855    Asm ("pushfl"          & LF & HT & -- push flags on stack
27856         "popl %%eax"      & LF & HT & -- load eax with flags
27857         "movl %%eax, %0",             -- store flags in variable
27858         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27859    Put_Line ("Flags register:" & Flags'Img);
27860 end Get_Flags;
27861 @end group
27862 @end smallexample
27864 In order to have a nicely aligned assembly listing, we have separated
27865 multiple assembler statements in the Asm template string with linefeed
27866 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
27867 The resulting section of the assembly output file is:
27869 @smallexample
27870 @group
27871 #APP
27872    pushfl
27873    popl %eax
27874    movl %eax, -40(%ebp)
27875 #NO_APP
27876 @end group
27877 @end smallexample
27879 It would have been legal to write the Asm invocation as:
27881 @smallexample
27882 Asm ("pushfl popl %%eax movl %%eax, %0")
27883 @end smallexample
27885 but in the generated assembler file, this would come out as:
27887 @smallexample
27888 #APP
27889    pushfl popl %eax movl %eax, -40(%ebp)
27890 #NO_APP
27891 @end smallexample
27893 which is not so convenient for the human reader.
27895 We use Ada comments
27896 at the end of each line to explain what the assembler instructions
27897 actually do.  This is a useful convention.
27899 When writing Inline Assembler instructions, you need to precede each register
27900 and variable name with a percent sign.  Since the assembler already requires
27901 a percent sign at the beginning of a register name, you need two consecutive
27902 percent signs for such names in the Asm template string, thus @code{%%eax}.
27903 In the generated assembly code, one of the percent signs will be stripped off.
27905 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
27906 variables: operands you later define using @code{Input} or @code{Output}
27907 parameters to @code{Asm}.
27908 An output variable is illustrated in
27909 the third statement in the Asm template string:
27910 @smallexample
27911 movl %%eax, %0
27912 @end smallexample
27913 The intent is to store the contents of the eax register in a variable that can
27914 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
27915 necessarily work, since the compiler might optimize by using a register
27916 to hold Flags, and the expansion of the @code{movl} instruction would not be
27917 aware of this optimization.  The solution is not to store the result directly
27918 but rather to advise the compiler to choose the correct operand form;
27919 that is the purpose of the @code{%0} output variable.
27921 Information about the output variable is supplied in the @code{Outputs}
27922 parameter to @code{Asm}:
27923 @smallexample
27924 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27925 @end smallexample
27927 The output is defined by the @code{Asm_Output} attribute of the target type;
27928 the general format is
27929 @smallexample
27930 Type'Asm_Output (constraint_string, variable_name)
27931 @end smallexample
27933 The constraint string directs the compiler how
27934 to store/access the associated variable.  In the example
27935 @smallexample
27936 Unsigned_32'Asm_Output ("=m", Flags);
27937 @end smallexample
27938 the @code{"m"} (memory) constraint tells the compiler that the variable
27939 @code{Flags} should be stored in a memory variable, thus preventing
27940 the optimizer from keeping it in a register.  In contrast,
27941 @smallexample
27942 Unsigned_32'Asm_Output ("=r", Flags);
27943 @end smallexample
27944 uses the @code{"r"} (register) constraint, telling the compiler to
27945 store the variable in a register.
27947 If the constraint is preceded by the equal character (@strong{=}), it tells
27948 the compiler that the variable will be used to store data into it.
27950 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
27951 allowing the optimizer to choose whatever it deems best.
27953 There are a fairly large number of constraints, but the ones that are
27954 most useful (for the Intel x86 processor) are the following:
27956 @table @code
27957 @item =
27958 output constraint
27959 @item g
27960 global (i.e.@: can be stored anywhere)
27961 @item m
27962 in memory
27963 @item I
27964 a constant
27965 @item a
27966 use eax
27967 @item b
27968 use ebx
27969 @item c
27970 use ecx
27971 @item d
27972 use edx
27973 @item S
27974 use esi
27975 @item D
27976 use edi
27977 @item r
27978 use one of eax, ebx, ecx or edx
27979 @item q
27980 use one of eax, ebx, ecx, edx, esi or edi
27981 @end table
27983 The full set of constraints is described in the gcc and @emph{as}
27984 documentation; note that it is possible to combine certain constraints
27985 in one constraint string.
27987 You specify the association of an output variable with an assembler operand
27988 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
27989 integer.  Thus in
27990 @smallexample @c ada
27991 @group
27992 Asm ("pushfl"          & LF & HT & -- push flags on stack
27993      "popl %%eax"      & LF & HT & -- load eax with flags
27994      "movl %%eax, %0",             -- store flags in variable
27995      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27996 @end group
27997 @end smallexample
27998 @noindent
27999 @code{%0} will be replaced in the expanded code by the appropriate operand,
28000 whatever
28001 the compiler decided for the @code{Flags} variable.
28003 In general, you may have any number of output variables:
28004 @itemize @bullet
28005 @item
28006 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28007 @item
28008 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28009 of @code{Asm_Output} attributes
28010 @end itemize
28012 For example:
28013 @smallexample @c ada
28014 @group
28015 Asm ("movl %%eax, %0" & LF & HT &
28016      "movl %%ebx, %1" & LF & HT &
28017      "movl %%ecx, %2",
28018      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
28019                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
28020                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
28021 @end group
28022 @end smallexample
28023 @noindent
28024 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28025 in the Ada program.
28027 As a variation on the @code{Get_Flags} example, we can use the constraints
28028 string to direct the compiler to store the eax register into the @code{Flags}
28029 variable, instead of including the store instruction explicitly in the
28030 @code{Asm} template string:
28032 @smallexample @c ada
28033 @group
28034 with Interfaces; use Interfaces;
28035 with Ada.Text_IO; use Ada.Text_IO;
28036 with System.Machine_Code; use System.Machine_Code;
28037 procedure Get_Flags_2 is
28038    Flags : Unsigned_32;
28039    use ASCII;
28040 begin
28041    Asm ("pushfl"      & LF & HT & -- push flags on stack
28042         "popl %%eax",             -- save flags in eax
28043         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28044    Put_Line ("Flags register:" & Flags'Img);
28045 end Get_Flags_2;
28046 @end group
28047 @end smallexample
28049 @noindent
28050 The @code{"a"} constraint tells the compiler that the @code{Flags}
28051 variable will come from the eax register. Here is the resulting code:
28053 @smallexample
28054 @group
28055 #APP
28056    pushfl
28057    popl %eax
28058 #NO_APP
28059    movl %eax,-40(%ebp)
28060 @end group
28061 @end smallexample
28063 @noindent
28064 The compiler generated the store of eax into Flags after
28065 expanding the assembler code.
28067 Actually, there was no need to pop the flags into the eax register;
28068 more simply, we could just pop the flags directly into the program variable:
28070 @smallexample @c ada
28071 @group
28072 with Interfaces; use Interfaces;
28073 with Ada.Text_IO; use Ada.Text_IO;
28074 with System.Machine_Code; use System.Machine_Code;
28075 procedure Get_Flags_3 is
28076    Flags : Unsigned_32;
28077    use ASCII;
28078 begin
28079    Asm ("pushfl"  & LF & HT & -- push flags on stack
28080         "pop %0",             -- save flags in Flags
28081         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28082    Put_Line ("Flags register:" & Flags'Img);
28083 end Get_Flags_3;
28084 @end group
28085 @end smallexample
28087 @c ---------------------------------------------------------------------------
28088 @node Input Variables in Inline Assembler
28089 @section Input Variables in Inline Assembler
28091 @noindent
28092 The example in this section illustrates how to specify the source operands
28093 for assembly language statements.
28094 The program simply increments its input value by 1:
28096 @smallexample @c ada
28097 @group
28098 with Interfaces; use Interfaces;
28099 with Ada.Text_IO; use Ada.Text_IO;
28100 with System.Machine_Code; use System.Machine_Code;
28101 procedure Increment is
28103    function Incr (Value : Unsigned_32) return Unsigned_32 is
28104       Result : Unsigned_32;
28105    begin
28106       Asm ("incl %0",
28107            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28108            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28109       return Result;
28110    end Incr;
28112    Value : Unsigned_32;
28114 begin
28115    Value := 5;
28116    Put_Line ("Value before is" & Value'Img);
28117    Value := Incr (Value);
28118    Put_Line ("Value after is" & Value'Img);
28119 end Increment;
28120 @end group
28121 @end smallexample
28123 The @code{Outputs} parameter to @code{Asm} specifies
28124 that the result will be in the eax register and that it is to be stored
28125 in the @code{Result} variable.
28127 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28128 but with an @code{Asm_Input} attribute.
28129 The @code{"="} constraint, indicating an output value, is not present.
28131 You can have multiple input variables, in the same way that you can have more
28132 than one output variable.
28134 The parameter count (%0, %1) etc, still starts at the first output statement,
28135 and continues with the input statements.
28137 Just as the @code{Outputs} parameter causes the register to be stored into the
28138 target variable after execution of the assembler statements, so does the
28139 @code{Inputs} parameter cause its variable to be loaded into the register
28140 before execution of the assembler statements.
28142 Thus the effect of the @code{Asm} invocation is:
28143 @enumerate
28144 @item load the 32-bit value of @code{Value} into eax
28145 @item execute the @code{incl %eax} instruction
28146 @item store the contents of eax into the @code{Result} variable
28147 @end enumerate
28149 The resulting assembler file (with @option{-O2} optimization) contains:
28150 @smallexample
28151 @group
28152 _increment__incr.1:
28153    subl $4,%esp
28154    movl 8(%esp),%eax
28155 #APP
28156    incl %eax
28157 #NO_APP
28158    movl %eax,%edx
28159    movl %ecx,(%esp)
28160    addl $4,%esp
28161    ret
28162 @end group
28163 @end smallexample
28165 @c ---------------------------------------------------------------------------
28166 @node Inlining Inline Assembler Code
28167 @section Inlining Inline Assembler Code
28169 @noindent
28170 For a short subprogram such as the @code{Incr} function in the previous
28171 section, the overhead of the call and return (creating / deleting the stack
28172 frame) can be significant, compared to the amount of code in the subprogram
28173 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28174 which directs the compiler to expand invocations of the subprogram at the
28175 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28176 Here is the resulting program:
28178 @smallexample @c ada
28179 @group
28180 with Interfaces; use Interfaces;
28181 with Ada.Text_IO; use Ada.Text_IO;
28182 with System.Machine_Code; use System.Machine_Code;
28183 procedure Increment_2 is
28185    function Incr (Value : Unsigned_32) return Unsigned_32 is
28186       Result : Unsigned_32;
28187    begin
28188       Asm ("incl %0",
28189            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28190            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28191       return Result;
28192    end Incr;
28193    pragma Inline (Increment);
28195    Value : Unsigned_32;
28197 begin
28198    Value := 5;
28199    Put_Line ("Value before is" & Value'Img);
28200    Value := Increment (Value);
28201    Put_Line ("Value after is" & Value'Img);
28202 end Increment_2;
28203 @end group
28204 @end smallexample
28206 Compile the program with both optimization (@option{-O2}) and inlining
28207 (@option{-gnatn}) enabled.
28209 The @code{Incr} function is still compiled as usual, but at the
28210 point in @code{Increment} where our function used to be called:
28212 @smallexample
28213 @group
28214 pushl %edi
28215 call _increment__incr.1
28216 @end group
28217 @end smallexample
28219 @noindent
28220 the code for the function body directly appears:
28222 @smallexample
28223 @group
28224 movl %esi,%eax
28225 #APP
28226    incl %eax
28227 #NO_APP
28228    movl %eax,%edx
28229 @end group
28230 @end smallexample
28232 @noindent
28233 thus saving the overhead of stack frame setup and an out-of-line call.
28235 @c ---------------------------------------------------------------------------
28236 @node Other Asm Functionality
28237 @section Other @code{Asm} Functionality
28239 @noindent
28240 This section describes two important parameters to the @code{Asm}
28241 procedure: @code{Clobber}, which identifies register usage;
28242 and @code{Volatile}, which inhibits unwanted optimizations.
28244 @menu
28245 * The Clobber Parameter::
28246 * The Volatile Parameter::
28247 @end menu
28249 @c ---------------------------------------------------------------------------
28250 @node The Clobber Parameter
28251 @subsection The @code{Clobber} Parameter
28253 @noindent
28254 One of the dangers of intermixing assembly language and a compiled language
28255 such as Ada is that the compiler needs to be aware of which registers are
28256 being used by the assembly code.  In some cases, such as the earlier examples,
28257 the constraint string is sufficient to indicate register usage (e.g.,
28258 @code{"a"} for
28259 the eax register).  But more generally, the compiler needs an explicit
28260 identification of the registers that are used by the Inline Assembly
28261 statements.
28263 Using a register that the compiler doesn't know about
28264 could be a side effect of an instruction (like @code{mull}
28265 storing its result in both eax and edx).
28266 It can also arise from explicit register usage in your
28267 assembly code; for example:
28268 @smallexample
28269 @group
28270 Asm ("movl %0, %%ebx" & LF & HT &
28271      "movl %%ebx, %1",
28272      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28273      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
28274 @end group
28275 @end smallexample
28276 @noindent
28277 where the compiler (since it does not analyze the @code{Asm} template string)
28278 does not know you are using the ebx register.
28280 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28281 to identify the registers that will be used by your assembly code:
28283 @smallexample
28284 @group
28285 Asm ("movl %0, %%ebx" & LF & HT &
28286      "movl %%ebx, %1",
28287      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28288      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
28289      Clobber => "ebx");
28290 @end group
28291 @end smallexample
28293 The Clobber parameter is a static string expression specifying the
28294 register(s) you are using.  Note that register names are @emph{not} prefixed
28295 by a percent sign. Also, if more than one register is used then their names
28296 are separated by commas; e.g., @code{"eax, ebx"}
28298 The @code{Clobber} parameter has several additional uses:
28299 @enumerate
28300 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28301 @item Use ``register'' name @code{memory} if you changed a memory location
28302 @end enumerate
28304 @c ---------------------------------------------------------------------------
28305 @node The Volatile Parameter
28306 @subsection The @code{Volatile} Parameter
28307 @cindex Volatile parameter
28309 @noindent
28310 Compiler optimizations in the presence of Inline Assembler may sometimes have
28311 unwanted effects.  For example, when an @code{Asm} invocation with an input
28312 variable is inside a loop, the compiler might move the loading of the input
28313 variable outside the loop, regarding it as a one-time initialization.
28315 If this effect is not desired, you can disable such optimizations by setting
28316 the @code{Volatile} parameter to @code{True}; for example:
28318 @smallexample @c ada
28319 @group
28320 Asm ("movl %0, %%ebx" & LF & HT &
28321      "movl %%ebx, %1",
28322      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
28323      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
28324      Clobber  => "ebx",
28325      Volatile => True);
28326 @end group
28327 @end smallexample
28329 By default, @code{Volatile} is set to @code{False} unless there is no
28330 @code{Outputs} parameter.
28332 Although setting @code{Volatile} to @code{True} prevents unwanted
28333 optimizations, it will also disable other optimizations that might be
28334 important for efficiency. In general, you should set @code{Volatile}
28335 to @code{True} only if the compiler's optimizations have created
28336 problems.
28337 @c END OF INLINE ASSEMBLER CHAPTER
28338 @c ===============================
28340 @c ***********************************
28341 @c * Compatibility and Porting Guide *
28342 @c ***********************************
28343 @node Compatibility and Porting Guide
28344 @appendix Compatibility and Porting Guide
28346 @noindent
28347 This chapter describes the compatibility issues that may arise between
28348 GNAT and other Ada compilation systems (including those for Ada 83),
28349 and shows how GNAT can expedite porting
28350 applications developed in other Ada environments.
28352 @menu
28353 * Compatibility with Ada 83::
28354 * Compatibility between Ada 95 and Ada 2005::
28355 * Implementation-dependent characteristics::
28356 * Compatibility with Other Ada Systems::
28357 * Representation Clauses::
28358 @ifclear vms
28359 @c Brief section is only in non-VMS version
28360 @c Full chapter is in VMS version
28361 * Compatibility with HP Ada 83::
28362 @end ifclear
28363 @ifset vms
28364 * Transitioning to 64-Bit GNAT for OpenVMS::
28365 @end ifset
28366 @end menu
28368 @node Compatibility with Ada 83
28369 @section Compatibility with Ada 83
28370 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28372 @noindent
28373 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
28374 particular, the design intention was that the difficulties associated
28375 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28376 that occur when moving from one Ada 83 system to another.
28378 However, there are a number of points at which there are minor
28379 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
28380 full details of these issues,
28381 and should be consulted for a complete treatment.
28382 In practice the
28383 following subsections treat the most likely issues to be encountered.
28385 @menu
28386 * Legal Ada 83 programs that are illegal in Ada 95::
28387 * More deterministic semantics::
28388 * Changed semantics::
28389 * Other language compatibility issues::
28390 @end menu
28392 @node Legal Ada 83 programs that are illegal in Ada 95
28393 @subsection Legal Ada 83 programs that are illegal in Ada 95
28395 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28396 Ada 95 and thus also in Ada 2005:
28398 @table @emph
28399 @item Character literals
28400 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
28401 @code{Wide_Character} as a new predefined character type, some uses of
28402 character literals that were legal in Ada 83 are illegal in Ada 95.
28403 For example:
28404 @smallexample @c ada
28405    for Char in 'A' .. 'Z' loop @dots{} end loop;
28406 @end smallexample
28408 @noindent
28409 The problem is that @code{'A'} and @code{'Z'} could be from either
28410 @code{Character} or @code{Wide_Character}.  The simplest correction
28411 is to make the type explicit; e.g.:
28412 @smallexample @c ada
28413    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28414 @end smallexample
28416 @item New reserved words
28417 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28418 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28419 Existing Ada 83 code using any of these identifiers must be edited to
28420 use some alternative name.
28422 @item Freezing rules
28423 The rules in Ada 95 are slightly different with regard to the point at
28424 which entities are frozen, and representation pragmas and clauses are
28425 not permitted past the freeze point.  This shows up most typically in
28426 the form of an error message complaining that a representation item
28427 appears too late, and the appropriate corrective action is to move
28428 the item nearer to the declaration of the entity to which it refers.
28430 A particular case is that representation pragmas
28431 @ifset vms
28432 (including the
28433 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28434 @end ifset
28435 cannot be applied to a subprogram body.  If necessary, a separate subprogram
28436 declaration must be introduced to which the pragma can be applied.
28438 @item Optional bodies for library packages
28439 In Ada 83, a package that did not require a package body was nevertheless
28440 allowed to have one.  This lead to certain surprises in compiling large
28441 systems (situations in which the body could be unexpectedly ignored by the
28442 binder).  In Ada 95, if a package does not require a body then it is not
28443 permitted to have a body.  To fix this problem, simply remove a redundant
28444 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28445 into the spec that makes the body required.  One approach is to add a private
28446 part to the package declaration (if necessary), and define a parameterless
28447 procedure called @code{Requires_Body}, which must then be given a dummy
28448 procedure body in the package body, which then becomes required.
28449 Another approach (assuming that this does not introduce elaboration
28450 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28451 since one effect of this pragma is to require the presence of a package body.
28453 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28454 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28455 @code{Constraint_Error}.
28456 This means that it is illegal to have separate exception handlers for
28457 the two exceptions.  The fix is simply to remove the handler for the
28458 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28459 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28461 @item Indefinite subtypes in generics
28462 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28463 as the actual for a generic formal private type, but then the instantiation
28464 would be illegal if there were any instances of declarations of variables
28465 of this type in the generic body.  In Ada 95, to avoid this clear violation
28466 of the methodological principle known as the ``contract model'',
28467 the generic declaration explicitly indicates whether
28468 or not such instantiations are permitted.  If a generic formal parameter
28469 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28470 subtype name, then it can be instantiated with indefinite types, but no
28471 stand-alone variables can be declared of this type.  Any attempt to declare
28472 such a variable will result in an illegality at the time the generic is
28473 declared.  If the @code{(<>)} notation is not used, then it is illegal
28474 to instantiate the generic with an indefinite type.
28475 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28476 It will show up as a compile time error, and
28477 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28478 @end table
28480 @node More deterministic semantics
28481 @subsection More deterministic semantics
28483 @table @emph
28484 @item Conversions
28485 Conversions from real types to integer types round away from 0.  In Ada 83
28486 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
28487 implementation freedom was intended to support unbiased rounding in
28488 statistical applications, but in practice it interfered with portability.
28489 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28490 is required.  Numeric code may be affected by this change in semantics.
28491 Note, though, that this issue is no worse than already existed in Ada 83
28492 when porting code from one vendor to another.
28494 @item Tasking
28495 The Real-Time Annex introduces a set of policies that define the behavior of
28496 features that were implementation dependent in Ada 83, such as the order in
28497 which open select branches are executed.
28498 @end table
28500 @node Changed semantics
28501 @subsection Changed semantics
28503 @noindent
28504 The worst kind of incompatibility is one where a program that is legal in
28505 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28506 possible in Ada 83.  Fortunately this is extremely rare, but the one
28507 situation that you should be alert to is the change in the predefined type
28508 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28510 @table @emph
28511 @item Range of type @code{Character}
28512 The range of @code{Standard.Character} is now the full 256 characters
28513 of Latin-1, whereas in most Ada 83 implementations it was restricted
28514 to 128 characters. Although some of the effects of
28515 this change will be manifest in compile-time rejection of legal
28516 Ada 83 programs it is possible for a working Ada 83 program to have
28517 a different effect in Ada 95, one that was not permitted in Ada 83.
28518 As an example, the expression
28519 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28520 delivers @code{255} as its value.
28521 In general, you should look at the logic of any
28522 character-processing Ada 83 program and see whether it needs to be adapted
28523 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
28524 character handling package that may be relevant if code needs to be adapted
28525 to account for the additional Latin-1 elements.
28526 The desirable fix is to
28527 modify the program to accommodate the full character set, but in some cases
28528 it may be convenient to define a subtype or derived type of Character that
28529 covers only the restricted range.
28530 @cindex Latin-1
28531 @end table
28533 @node Other language compatibility issues
28534 @subsection Other language compatibility issues
28536 @table @emph
28537 @item @option{-gnat83} switch
28538 All implementations of GNAT provide a switch that causes GNAT to operate
28539 in Ada 83 mode.  In this mode, some but not all compatibility problems
28540 of the type described above are handled automatically.  For example, the
28541 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28542 as identifiers as in Ada 83.
28543 However,
28544 in practice, it is usually advisable to make the necessary modifications
28545 to the program to remove the need for using this switch.
28546 See @ref{Compiling Different Versions of Ada}.
28548 @item Support for removed Ada 83 pragmas and attributes
28549 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28550 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
28551 compilers are allowed, but not required, to implement these missing
28552 elements.  In contrast with some other compilers, GNAT implements all
28553 such pragmas and attributes, eliminating this compatibility concern.  These
28554 include @code{pragma Interface} and the floating point type attributes
28555 (@code{Emax}, @code{Mantissa}, etc.), among other items.
28556 @end table
28559 @node Compatibility between Ada 95 and Ada 2005
28560 @section Compatibility between Ada 95 and Ada 2005
28561 @cindex Compatibility between Ada 95 and Ada 2005
28563 @noindent
28564 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
28565 a number of incompatibilities. Several are enumerated below;
28566 for a complete description please see the
28567 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
28568 @cite{Rationale for Ada 2005}.
28570 @table @emph
28571 @item New reserved words.
28572 The words @code{interface}, @code{overriding} and @code{synchronized} are
28573 reserved in Ada 2005.
28574 A pre-Ada 2005 program that uses any of these as an identifier will be
28575 illegal.
28577 @item New declarations in predefined packages.
28578 A number of packages in the predefined environment contain new declarations:
28579 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
28580 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
28581 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
28582 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
28583 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
28584 If an Ada 95 program does a @code{with} and @code{use} of any of these
28585 packages, the new declarations may cause name clashes.
28587 @item Access parameters.
28588 A nondispatching subprogram with an access parameter cannot be renamed
28589 as a dispatching operation.  This was permitted in Ada 95.
28591 @item Access types, discriminants, and constraints.
28592 Rule changes in this area have led to some incompatibilities; for example,
28593 constrained subtypes of some access types are not permitted in Ada 2005.
28595 @item Aggregates for limited types.
28596 The allowance of aggregates for limited types in Ada 2005 raises the
28597 possibility of ambiguities in legal Ada 95 programs, since additional types
28598 now need to be considered in expression resolution.
28600 @item Fixed-point multiplication and division.
28601 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
28602 were legal in Ada 95 and invoked the predefined versions of these operations,
28603 are now ambiguous.
28604 The ambiguity may be resolved either by applying a type conversion to the
28605 expression, or by explicitly invoking the operation from package
28606 @code{Standard}.
28608 @item Return-by-reference types.
28609 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
28610 can declare a function returning a value from an anonymous access type.
28611 @end table
28614 @node Implementation-dependent characteristics
28615 @section Implementation-dependent characteristics
28616 @noindent
28617 Although the Ada language defines the semantics of each construct as
28618 precisely as practical, in some situations (for example for reasons of
28619 efficiency, or where the effect is heavily dependent on the host or target
28620 platform) the implementation is allowed some freedom.  In porting Ada 83
28621 code to GNAT, you need to be aware of whether / how the existing code
28622 exercised such implementation dependencies.  Such characteristics fall into
28623 several categories, and GNAT offers specific support in assisting the
28624 transition from certain Ada 83 compilers.
28626 @menu
28627 * Implementation-defined pragmas::
28628 * Implementation-defined attributes::
28629 * Libraries::
28630 * Elaboration order::
28631 * Target-specific aspects::
28632 @end menu
28634 @node Implementation-defined pragmas
28635 @subsection Implementation-defined pragmas
28637 @noindent
28638 Ada compilers are allowed to supplement the language-defined pragmas, and
28639 these are a potential source of non-portability.  All GNAT-defined pragmas
28640 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
28641 Reference Manual}, and these include several that are specifically
28642 intended to correspond to other vendors' Ada 83 pragmas.
28643 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
28644 For compatibility with HP Ada 83, GNAT supplies the pragmas
28645 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
28646 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
28647 and @code{Volatile}.
28648 Other relevant pragmas include @code{External} and @code{Link_With}.
28649 Some vendor-specific
28650 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
28651 recognized, thus
28652 avoiding compiler rejection of units that contain such pragmas; they are not
28653 relevant in a GNAT context and hence are not otherwise implemented.
28655 @node Implementation-defined attributes
28656 @subsection Implementation-defined attributes
28658 Analogous to pragmas, the set of attributes may be extended by an
28659 implementation.  All GNAT-defined attributes are described in
28660 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
28661 Manual}, and these include several that are specifically intended
28662 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
28663 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
28664 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
28665 @code{Type_Class}.
28667 @node Libraries
28668 @subsection Libraries
28669 @noindent
28670 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
28671 code uses vendor-specific libraries then there are several ways to manage
28672 this in Ada 95 or Ada 2005:
28673 @enumerate
28674 @item
28675 If the source code for the libraries (specs and bodies) are
28676 available, then the libraries can be migrated in the same way as the
28677 application.
28678 @item
28679 If the source code for the specs but not the bodies are
28680 available, then you can reimplement the bodies.
28681 @item
28682 Some features introduced by Ada 95 obviate the need for library support.  For
28683 example most Ada 83 vendors supplied a package for unsigned integers.  The
28684 Ada 95 modular type feature is the preferred way to handle this need, so
28685 instead of migrating or reimplementing the unsigned integer package it may
28686 be preferable to retrofit the application using modular types.
28687 @end enumerate
28689 @node Elaboration order
28690 @subsection Elaboration order
28691 @noindent
28692 The implementation can choose any elaboration order consistent with the unit
28693 dependency relationship.  This freedom means that some orders can result in
28694 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
28695 to invoke a subprogram its body has been elaborated, or to instantiate a
28696 generic before the generic body has been elaborated.  By default GNAT
28697 attempts to choose a safe order (one that will not encounter access before
28698 elaboration problems) by implicitly inserting @code{Elaborate} or
28699 @code{Elaborate_All} pragmas where
28700 needed.  However, this can lead to the creation of elaboration circularities
28701 and a resulting rejection of the program by gnatbind.  This issue is
28702 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
28703 In brief, there are several
28704 ways to deal with this situation:
28706 @itemize @bullet
28707 @item
28708 Modify the program to eliminate the circularities, e.g.@: by moving
28709 elaboration-time code into explicitly-invoked procedures
28710 @item
28711 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
28712 @code{Elaborate} pragmas, and then inhibit the generation of implicit
28713 @code{Elaborate_All}
28714 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
28715 (by selectively suppressing elaboration checks via pragma
28716 @code{Suppress(Elaboration_Check)} when it is safe to do so).
28717 @end itemize
28719 @node Target-specific aspects
28720 @subsection Target-specific aspects
28721 @noindent
28722 Low-level applications need to deal with machine addresses, data
28723 representations, interfacing with assembler code, and similar issues.  If
28724 such an Ada 83 application is being ported to different target hardware (for
28725 example where the byte endianness has changed) then you will need to
28726 carefully examine the program logic; the porting effort will heavily depend
28727 on the robustness of the original design.  Moreover, Ada 95 (and thus
28728 Ada 2005) are sometimes
28729 incompatible with typical Ada 83 compiler practices regarding implicit
28730 packing, the meaning of the Size attribute, and the size of access values.
28731 GNAT's approach to these issues is described in @ref{Representation Clauses}.
28733 @node Compatibility with Other Ada Systems
28734 @section Compatibility with Other Ada Systems
28736 @noindent
28737 If programs avoid the use of implementation dependent and
28738 implementation defined features, as documented in the @cite{Ada
28739 Reference Manual}, there should be a high degree of portability between
28740 GNAT and other Ada systems.  The following are specific items which
28741 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
28742 compilers, but do not affect porting code to GNAT@.
28743 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
28744 the following issues may or may not arise for Ada 2005 programs
28745 when other compilers appear.)
28747 @table @emph
28748 @item Ada 83 Pragmas and Attributes
28749 Ada 95 compilers are allowed, but not required, to implement the missing
28750 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
28751 GNAT implements all such pragmas and attributes, eliminating this as
28752 a compatibility concern, but some other Ada 95 compilers reject these
28753 pragmas and attributes.
28755 @item Specialized Needs Annexes
28756 GNAT implements the full set of special needs annexes.  At the
28757 current time, it is the only Ada 95 compiler to do so.  This means that
28758 programs making use of these features may not be portable to other Ada
28759 95 compilation systems.
28761 @item Representation Clauses
28762 Some other Ada 95 compilers implement only the minimal set of
28763 representation clauses required by the Ada 95 reference manual.  GNAT goes
28764 far beyond this minimal set, as described in the next section.
28765 @end table
28767 @node Representation Clauses
28768 @section Representation Clauses
28770 @noindent
28771 The Ada 83 reference manual was quite vague in describing both the minimal
28772 required implementation of representation clauses, and also their precise
28773 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
28774 minimal set of capabilities required is still quite limited.
28776 GNAT implements the full required set of capabilities in
28777 Ada 95 and Ada 2005, but also goes much further, and in particular
28778 an effort has been made to be compatible with existing Ada 83 usage to the
28779 greatest extent possible.
28781 A few cases exist in which Ada 83 compiler behavior is incompatible with
28782 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
28783 intentional or accidental dependence on specific implementation dependent
28784 characteristics of these Ada 83 compilers.  The following is a list of
28785 the cases most likely to arise in existing Ada 83 code.
28787 @table @emph
28788 @item Implicit Packing
28789 Some Ada 83 compilers allowed a Size specification to cause implicit
28790 packing of an array or record.  This could cause expensive implicit
28791 conversions for change of representation in the presence of derived
28792 types, and the Ada design intends to avoid this possibility.
28793 Subsequent AI's were issued to make it clear that such implicit
28794 change of representation in response to a Size clause is inadvisable,
28795 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
28796 Reference Manuals as implementation advice that is followed by GNAT@.
28797 The problem will show up as an error
28798 message rejecting the size clause.  The fix is simply to provide
28799 the explicit pragma @code{Pack}, or for more fine tuned control, provide
28800 a Component_Size clause.
28802 @item Meaning of Size Attribute
28803 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
28804 the minimal number of bits required to hold values of the type.  For example,
28805 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
28806 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
28807 some 32 in this situation.  This problem will usually show up as a compile
28808 time error, but not always.  It is a good idea to check all uses of the
28809 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
28810 Object_Size can provide a useful way of duplicating the behavior of
28811 some Ada 83 compiler systems.
28813 @item Size of Access Types
28814 A common assumption in Ada 83 code is that an access type is in fact a pointer,
28815 and that therefore it will be the same size as a System.Address value.  This
28816 assumption is true for GNAT in most cases with one exception.  For the case of
28817 a pointer to an unconstrained array type (where the bounds may vary from one
28818 value of the access type to another), the default is to use a ``fat pointer'',
28819 which is represented as two separate pointers, one to the bounds, and one to
28820 the array.  This representation has a number of advantages, including improved
28821 efficiency.  However, it may cause some difficulties in porting existing Ada 83
28822 code which makes the assumption that, for example, pointers fit in 32 bits on
28823 a machine with 32-bit addressing.
28825 To get around this problem, GNAT also permits the use of ``thin pointers'' for
28826 access types in this case (where the designated type is an unconstrained array
28827 type).  These thin pointers are indeed the same size as a System.Address value.
28828 To specify a thin pointer, use a size clause for the type, for example:
28830 @smallexample @c ada
28831 type X is access all String;
28832 for X'Size use Standard'Address_Size;
28833 @end smallexample
28835 @noindent
28836 which will cause the type X to be represented using a single pointer.
28837 When using this representation, the bounds are right behind the array.
28838 This representation is slightly less efficient, and does not allow quite
28839 such flexibility in the use of foreign pointers or in using the
28840 Unrestricted_Access attribute to create pointers to non-aliased objects.
28841 But for any standard portable use of the access type it will work in
28842 a functionally correct manner and allow porting of existing code.
28843 Note that another way of forcing a thin pointer representation
28844 is to use a component size clause for the element size in an array,
28845 or a record representation clause for an access field in a record.
28846 @end table
28848 @ifclear vms
28849 @c This brief section is only in the non-VMS version
28850 @c The complete chapter on HP Ada is in the VMS version
28851 @node Compatibility with HP Ada 83
28852 @section Compatibility with HP Ada 83
28854 @noindent
28855 The VMS version of GNAT fully implements all the pragmas and attributes
28856 provided by HP Ada 83, as well as providing the standard HP Ada 83
28857 libraries, including Starlet.  In addition, data layouts and parameter
28858 passing conventions are highly compatible.  This means that porting
28859 existing HP Ada 83 code to GNAT in VMS systems should be easier than
28860 most other porting efforts.  The following are some of the most
28861 significant differences between GNAT and HP Ada 83.
28863 @table @emph
28864 @item Default floating-point representation
28865 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
28866 it is VMS format.  GNAT does implement the necessary pragmas
28867 (Long_Float, Float_Representation) for changing this default.
28869 @item System
28870 The package System in GNAT exactly corresponds to the definition in the
28871 Ada 95 reference manual, which means that it excludes many of the
28872 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
28873 that contains the additional definitions, and a special pragma,
28874 Extend_System allows this package to be treated transparently as an
28875 extension of package System.
28877 @item To_Address
28878 The definitions provided by Aux_DEC are exactly compatible with those
28879 in the HP Ada 83 version of System, with one exception.
28880 HP Ada provides the following declarations:
28882 @smallexample @c ada
28883 TO_ADDRESS (INTEGER)
28884 TO_ADDRESS (UNSIGNED_LONGWORD)
28885 TO_ADDRESS (@i{universal_integer})
28886 @end smallexample
28888 @noindent
28889 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
28890 an extension to Ada 83 not strictly compatible with the reference manual.
28891 In GNAT, we are constrained to be exactly compatible with the standard,
28892 and this means we cannot provide this capability.  In HP Ada 83, the
28893 point of this definition is to deal with a call like:
28895 @smallexample @c ada
28896 TO_ADDRESS (16#12777#);
28897 @end smallexample
28899 @noindent
28900 Normally, according to the Ada 83 standard, one would expect this to be
28901 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
28902 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
28903 definition using @i{universal_integer} takes precedence.
28905 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
28906 is not possible to be 100% compatible.  Since there are many programs using
28907 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
28908 to change the name of the function in the UNSIGNED_LONGWORD case, so the
28909 declarations provided in the GNAT version of AUX_Dec are:
28911 @smallexample @c ada
28912 function To_Address (X : Integer) return Address;
28913 pragma Pure_Function (To_Address);
28915 function To_Address_Long (X : Unsigned_Longword)
28916  return Address;
28917 pragma Pure_Function (To_Address_Long);
28918 @end smallexample
28920 @noindent
28921 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
28922 change the name to TO_ADDRESS_LONG@.
28924 @item Task_Id values
28925 The Task_Id values assigned will be different in the two systems, and GNAT
28926 does not provide a specified value for the Task_Id of the environment task,
28927 which in GNAT is treated like any other declared task.
28928 @end table
28930 @noindent
28931 For full details on these and other less significant compatibility issues,
28932 see appendix E of the HP publication entitled @cite{HP Ada, Technical
28933 Overview and Comparison on HP Platforms}.
28935 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
28936 attributes are recognized, although only a subset of them can sensibly
28937 be implemented.  The description of pragmas in @ref{Implementation
28938 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
28939 indicates whether or not they are applicable to non-VMS systems.
28940 @end ifclear
28942 @ifset vms
28943 @node Transitioning to 64-Bit GNAT for OpenVMS
28944 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
28946 @noindent
28947 This section is meant to assist users of pre-2006 @value{EDITION}
28948 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
28949 the version of the GNAT technology supplied in 2006 and later for
28950 OpenVMS on both Alpha and I64.
28952 @menu
28953 * Introduction to transitioning::
28954 * Migration of 32 bit code::
28955 * Taking advantage of 64 bit addressing::
28956 * Technical details::
28957 @end menu
28959 @node Introduction to transitioning
28960 @subsection Introduction
28962 @noindent
28963 64-bit @value{EDITION} for Open VMS has been designed to meet
28964 three main goals:
28966 @enumerate
28967 @item
28968 Providing a full conforming implementation of Ada 95 and Ada 2005
28970 @item
28971 Allowing maximum backward compatibility, thus easing migration of existing
28972 Ada source code
28974 @item
28975 Supplying a path for exploiting the full 64-bit address range
28976 @end enumerate
28978 @noindent
28979 Ada's strong typing semantics has made it
28980 impractical to have different 32-bit and 64-bit modes. As soon as
28981 one object could possibly be outside the 32-bit address space, this
28982 would make it necessary for the @code{System.Address} type to be 64 bits.
28983 In particular, this would cause inconsistencies if 32-bit code is
28984 called from 64-bit code that raises an exception.
28986 This issue has been resolved by always using 64-bit addressing
28987 at the system level, but allowing for automatic conversions between
28988 32-bit and 64-bit addresses where required. Thus users who
28989 do not currently require 64-bit addressing capabilities, can
28990 recompile their code with only minimal changes (and indeed
28991 if the code is written in portable Ada, with no assumptions about
28992 the size of the @code{Address} type, then no changes at all are necessary).
28993 At the same time,
28994 this approach provides a simple, gradual upgrade path to future
28995 use of larger memories than available for 32-bit systems.
28996 Also, newly written applications or libraries will by default
28997 be fully compatible with future systems exploiting 64-bit
28998 addressing capabilities.
29000 @ref{Migration of 32 bit code}, will focus on porting applications
29001 that do not require more than 2 GB of
29002 addressable memory. This code will be referred to as
29003 @emph{32-bit code}.
29004 For applications intending to exploit the full 64-bit address space,
29005 @ref{Taking advantage of 64 bit addressing},
29006 will consider further changes that may be required.
29007 Such code will be referred to below as @emph{64-bit code}.
29009 @node Migration of 32 bit code
29010 @subsection Migration of 32-bit code
29012 @menu
29013 * Address types::
29014 * Access types and 32/64-bit allocation::
29015 * Unchecked conversions::
29016 * Predefined constants::
29017 * Interfacing with C::
29018 * 32/64-bit descriptors::
29019 * Experience with source compatibility::
29020 @end menu
29022 @node Address types
29023 @subsubsection Address types
29025 @noindent
29026 To solve the problem of mixing 64-bit and 32-bit addressing,
29027 while maintaining maximum backward compatibility, the following
29028 approach has been taken:
29030 @itemize @bullet
29031 @item
29032 @code{System.Address} always has a size of 64 bits
29033 @cindex @code{System.Address} size
29034 @cindex @code{Address} size
29036 @item
29037 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29038 @cindex @code{System.Short_Address} size
29039 @cindex @code{Short_Address} size
29040 @end itemize
29042 @noindent
29043 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29044 a @code{Short_Address}
29045 may be used where an @code{Address} is required, and vice versa, without
29046 needing explicit type conversions.
29047 By virtue of the Open VMS parameter passing conventions,
29048 even imported
29049 and exported subprograms that have 32-bit address parameters are
29050 compatible with those that have 64-bit address parameters.
29051 (See @ref{Making code 64 bit clean} for details.)
29053 The areas that may need attention are those where record types have
29054 been defined that contain components of the type @code{System.Address}, and
29055 where objects of this type are passed to code expecting a record layout with
29056 32-bit addresses.
29058 Different compilers on different platforms cannot be
29059 expected to represent the same type in the same way,
29060 since alignment constraints
29061 and other system-dependent properties affect the compiler's decision.
29062 For that reason, Ada code
29063 generally uses representation clauses to specify the expected
29064 layout where required.
29066 If such a representation clause uses 32 bits for a component having
29067 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29068 will detect that error and produce a specific diagnostic message.
29069 The developer should then determine whether the representation
29070 should be 64 bits or not and make either of two changes:
29071 change the size to 64 bits and leave the type as @code{System.Address}, or
29072 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29073 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29074 required in any code setting or accessing the field; the compiler will
29075 automatically perform any needed conversions between address
29076 formats.
29078 @node Access types and 32/64-bit allocation
29079 @subsubsection Access types and 32/64-bit allocation
29080 @cindex 32-bit allocation
29081 @cindex 64-bit allocation
29083 @noindent
29084 By default, objects designated by access values are always allocated in
29085 the 64-bit address space, and access values themselves are represented
29086 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
29087 is required (for example if the address of an allocated object is assigned
29088 to a @code{Short_Address} variable), then several alternatives are available:
29090 @itemize @bullet
29091 @item
29092 A pool-specific access type (ie, an @w{Ada 83} access type, whose
29093 definition is @code{access T} versus @code{access all T} or
29094 @code{access constant T}), may be declared with a @code{'Size} representation
29095 clause that establishes the size as 32 bits.
29096 In such circumstances allocations for that type will
29097 be from the 32-bit heap.  Such a clause is not permitted
29098 for a general access type (declared with @code{access all} or
29099 @code{access constant}) as values of such types must be able to refer
29100 to any object of the designated type, including objects residing outside
29101 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
29102 type definitions, however, since general access types were introduced
29103 in @w{Ada 95}.
29105 @item
29106 Switches for @command{GNAT BIND} control whether the internal GNAT
29107 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
29108 @cindex @code{__gnat_malloc}
29109 The switches are respectively @option{-H64} (the default) and
29110 @option{-H32}.
29111 @cindex @option{-H32} (@command{gnatbind})
29112 @cindex @option{-H64} (@command{gnatbind})
29114 @item
29115 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
29116 @cindex @code{GNAT$NO_MALLOC_64} environment variable
29117 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
29118 If this variable is left
29119 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
29120 then the default (64-bit) allocation is used.
29121 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
29122 then 32-bit allocation is used.  The gnatbind qualifiers described above
29123 override this logical name.
29125 @item
29126 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
29127 @cindex @option{-mno-malloc64} (^gcc^gcc^)
29128 at a low level to convert explicit calls to @code{malloc} and related
29129 functions from the C run-time library so that they perform allocations
29130 in the 32-bit heap.
29131 Since all internal allocations from GNAT use @code{__gnat_malloc},
29132 this switch is not required unless the program makes explicit calls on
29133 @code{malloc} (or related functions) from interfaced C code.
29134 @end itemize
29137 @node Unchecked conversions
29138 @subsubsection Unchecked conversions
29140 @noindent
29141 In the case of an @code{Unchecked_Conversion} where the source type is a
29142 64-bit access type or the type @code{System.Address}, and the target
29143 type is a 32-bit type, the compiler will generate a warning.
29144 Even though the generated code will still perform the required
29145 conversions, it is highly recommended in these cases to use
29146 respectively a 32-bit access type or @code{System.Short_Address}
29147 as the source type.
29149 @node Predefined constants
29150 @subsubsection Predefined constants
29152 @noindent
29153 The following table shows the correspondence between pre-2006 versions of
29154 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29155 (``New''):
29157 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29158 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
29159 @item   @code{System.Word_Size}          @tab 32      @tab 64
29160 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
29161 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
29162 @item   @code{System.Address_Size}       @tab 32      @tab 64
29163 @end multitable
29165 @noindent
29166 If you need to refer to the specific
29167 memory size of a 32-bit implementation, instead of the
29168 actual memory size, use @code{System.Short_Memory_Size}
29169 rather than @code{System.Memory_Size}.
29170 Similarly, references to @code{System.Address_Size} may need
29171 to be replaced by @code{System.Short_Address'Size}.
29172 The program @command{gnatfind} may be useful for locating
29173 references to the above constants, so that you can verify that they
29174 are still correct.
29176 @node Interfacing with C
29177 @subsubsection Interfacing with C
29179 @noindent
29180 In order to minimize the impact of the transition to 64-bit addresses on
29181 legacy programs, some fundamental types in the @code{Interfaces.C}
29182 package hierarchy continue to be represented in 32 bits.
29183 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29184 This eases integration with the default HP C layout choices, for example
29185 as found in the system routines in @code{DECC$SHR.EXE}.
29186 Because of this implementation choice, the type fully compatible with
29187 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29188 Depending on the context the compiler will issue a
29189 warning or an error when type @code{Address} is used, alerting the user to a
29190 potential problem. Otherwise 32-bit programs that use
29191 @code{Interfaces.C} should normally not require code modifications
29193 The other issue arising with C interfacing concerns pragma @code{Convention}.
29194 For VMS 64-bit systems, there is an issue of the appropriate default size
29195 of C convention pointers in the absence of an explicit size clause. The HP
29196 C compiler can choose either 32 or 64 bits depending on compiler options.
29197 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29198 clause is given. This proves a better choice for porting 32-bit legacy
29199 applications. In order to have a 64-bit representation, it is necessary to
29200 specify a size representation clause. For example:
29202 @smallexample @c ada
29203 type int_star is access Interfaces.C.int;
29204 pragma Convention(C, int_star);
29205 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
29206 @end smallexample
29208 @node 32/64-bit descriptors
29209 @subsubsection 32/64-bit descriptors
29211 @noindent
29212 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
29213 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
29214 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
29215 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
29216 @cindex @code{Short_Descriptor} mechanism for imported subprograms
29218 If the configuration pragma @code{Short_Descriptors} is supplied, then
29219 all descriptors will be 32 bits.
29220 @cindex pragma @code{Short_Descriptors}
29222 @node Experience with source compatibility
29223 @subsubsection Experience with source compatibility
29225 @noindent
29226 The Security Server and STARLET on I64 provide an interesting ``test case''
29227 for source compatibility issues, since it is in such system code
29228 where assumptions about @code{Address} size might be expected to occur.
29229 Indeed, there were a small number of occasions in the Security Server
29230 file @file{jibdef.ads}
29231 where a representation clause for a record type specified
29232 32 bits for a component of type @code{Address}.
29233 All of these errors were detected by the compiler.
29234 The repair was obvious and immediate; to simply replace @code{Address} by
29235 @code{Short_Address}.
29237 In the case of STARLET, there were several record types that should
29238 have had representation clauses but did not.  In these record types
29239 there was an implicit assumption that an @code{Address} value occupied
29240 32 bits.
29241 These compiled without error, but their usage resulted in run-time error
29242 returns from STARLET system calls.
29243 Future GNAT technology enhancements may include a tool that detects and flags
29244 these sorts of potential source code porting problems.
29246 @c ****************************************
29247 @node Taking advantage of 64 bit addressing
29248 @subsection Taking advantage of 64-bit addressing
29250 @menu
29251 * Making code 64 bit clean::
29252 * Allocating memory from the 64 bit storage pool::
29253 * Restrictions on use of 64 bit objects::
29254 * STARLET and other predefined libraries::
29255 @end menu
29257 @node Making code 64 bit clean
29258 @subsubsection Making code 64-bit clean
29260 @noindent
29261 In order to prevent problems that may occur when (parts of) a
29262 system start using memory outside the 32-bit address range,
29263 we recommend some additional guidelines:
29265 @itemize @bullet
29266 @item
29267 For imported subprograms that take parameters of the
29268 type @code{System.Address}, ensure that these subprograms can
29269 indeed handle 64-bit addresses. If not, or when in doubt,
29270 change the subprogram declaration to specify
29271 @code{System.Short_Address} instead.
29273 @item
29274 Resolve all warnings related to size mismatches in
29275 unchecked conversions. Failing to do so causes
29276 erroneous execution if the source object is outside
29277 the 32-bit address space.
29279 @item
29280 (optional) Explicitly use the 32-bit storage pool
29281 for access types used in a 32-bit context, or use
29282 generic access types where possible
29283 (@pxref{Restrictions on use of 64 bit objects}).
29284 @end itemize
29286 @noindent
29287 If these rules are followed, the compiler will automatically insert
29288 any necessary checks to ensure that no addresses or access values
29289 passed to 32-bit code ever refer to objects outside the 32-bit
29290 address range.
29291 Any attempt to do this will raise @code{Constraint_Error}.
29293 @node Allocating memory from the 64 bit storage pool
29294 @subsubsection Allocating memory from the 64-bit storage pool
29296 @noindent
29297 By default, all allocations -- for both pool-specific and general
29298 access types -- use the 64-bit storage pool.  To override
29299 this default, for an individual access type or globally, see
29300 @ref{Access types and 32/64-bit allocation}.
29302 @node Restrictions on use of 64 bit objects
29303 @subsubsection Restrictions on use of 64-bit objects
29305 @noindent
29306 Taking the address of an object allocated from a 64-bit storage pool,
29307 and then passing this address to a subprogram expecting
29308 @code{System.Short_Address},
29309 or assigning it to a variable of type @code{Short_Address}, will cause
29310 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29311 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29312 no exception is raised and execution
29313 will become erroneous.
29315 @node STARLET and other predefined libraries
29316 @subsubsection STARLET and other predefined libraries
29318 @noindent
29319 All code that comes as part of GNAT is 64-bit clean, but the
29320 restrictions given in @ref{Restrictions on use of 64 bit objects},
29321 still apply. Look at the package
29322 specs to see in which contexts objects allocated
29323 in 64-bit address space are acceptable.
29325 @node Technical details
29326 @subsection Technical details
29328 @noindent
29329 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29330 Ada standard with respect to the type of @code{System.Address}. Previous
29331 versions of @value{EDITION} have defined this type as private and implemented it as a
29332 modular type.
29334 In order to allow defining @code{System.Short_Address} as a proper subtype,
29335 and to match the implicit sign extension in parameter passing,
29336 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29337 visible (i.e., non-private) integer type.
29338 Standard operations on the type, such as the binary operators ``+'', ``-'',
29339 etc., that take @code{Address} operands and return an @code{Address} result,
29340 have been hidden by declaring these
29341 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29342 ambiguities that would otherwise result from overloading.
29343 (Note that, although @code{Address} is a visible integer type,
29344 good programming practice dictates against exploiting the type's
29345 integer properties such as literals, since this will compromise
29346 code portability.)
29348 Defining @code{Address} as a visible integer type helps achieve
29349 maximum compatibility for existing Ada code,
29350 without sacrificing the capabilities of the 64-bit architecture.
29351 @end ifset
29353 @c ************************************************
29354 @node Microsoft Windows Topics
29355 @appendix Microsoft Windows Topics
29356 @cindex Windows NT
29357 @cindex Windows 95
29358 @cindex Windows 98
29360 @noindent
29361 This chapter describes topics that are specific to the Microsoft Windows
29362 platforms (NT, 2000, and XP Professional).
29364 @menu
29365 @ifclear FSFEDITION
29366 * Installing from the Command Line::
29367 @end ifclear
29368 * Using GNAT on Windows::
29369 * Using a network installation of GNAT::
29370 * CONSOLE and WINDOWS subsystems::
29371 * Temporary Files::
29372 * Mixed-Language Programming on Windows::
29373 * Windows Calling Conventions::
29374 * Introduction to Dynamic Link Libraries (DLLs)::
29375 * Using DLLs with GNAT::
29376 * Building DLLs with GNAT Project files::
29377 * Building DLLs with GNAT::
29378 * Building DLLs with gnatdll::
29379 * GNAT and Windows Resources::
29380 * Debugging a DLL::
29381 * Setting Stack Size from gnatlink::
29382 * Setting Heap Size from gnatlink::
29383 @end menu
29385 @ifclear FSFEDITION
29386 @node Installing from the Command Line
29387 @section Installing from the Command Line
29388 @cindex Batch installation
29389 @cindex Silent installation
29390 @cindex Unassisted installation
29392 @noindent
29393 By default the @value{EDITION} installers display a GUI that prompts the user
29394 to enter installation path and similar information, and guide him through the
29395 installation process. It is also possible to perform silent installations
29396 using the command-line interface.
29398 In order to install one of the @value{EDITION} installers from the command
29399 line you should pass parameter @code{/S} (and, optionally,
29400 @code{/D=<directory>}) as command-line arguments.
29402 @ifset PROEDITION
29403 For example, for an unattended installation of
29404 @value{EDITION} 7.0.2 into the default directory
29405 @code{C:\GNATPRO\7.0.2} you would run:
29407 @smallexample
29408 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29409 @end smallexample
29411 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29413 @smallexample
29414 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29415 @end smallexample
29416 @end ifset
29418 @ifset GPLEDITION
29419 For example, for an unattended installation of
29420 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
29422 @smallexample
29423 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29424 @end smallexample
29425 @end ifset
29427 You can use the same syntax for all installers.
29429 Note that unattended installations don't modify system path, nor create file
29430 associations, so such activities need to be done by hand.
29431 @end ifclear
29433 @node Using GNAT on Windows
29434 @section Using GNAT on Windows
29436 @noindent
29437 One of the strengths of the GNAT technology is that its tool set
29438 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29439 @code{gdb} debugger, etc.) is used in the same way regardless of the
29440 platform.
29442 On Windows this tool set is complemented by a number of Microsoft-specific
29443 tools that have been provided to facilitate interoperability with Windows
29444 when this is required. With these tools:
29446 @itemize @bullet
29448 @item
29449 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29450 subsystems.
29452 @item
29453 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29454 relocatable and non-relocatable DLLs are supported).
29456 @item
29457 You can build Ada DLLs for use in other applications. These applications
29458 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29459 relocatable and non-relocatable Ada DLLs are supported.
29461 @item
29462 You can include Windows resources in your Ada application.
29464 @item
29465 You can use or create COM/DCOM objects.
29466 @end itemize
29468 @noindent
29469 Immediately below are listed all known general GNAT-for-Windows restrictions.
29470 Other restrictions about specific features like Windows Resources and DLLs
29471 are listed in separate sections below.
29473 @itemize @bullet
29475 @item
29476 It is not possible to use @code{GetLastError} and @code{SetLastError}
29477 when tasking, protected records, or exceptions are used. In these
29478 cases, in order to implement Ada semantics, the GNAT run-time system
29479 calls certain Win32 routines that set the last error variable to 0 upon
29480 success. It should be possible to use @code{GetLastError} and
29481 @code{SetLastError} when tasking, protected record, and exception
29482 features are not used, but it is not guaranteed to work.
29484 @item
29485 It is not possible to link against Microsoft C++ libraries except for
29486 import libraries. Interfacing must be done by the mean of DLLs.
29488 @item
29489 It is possible to link against Microsoft C libraries. Yet the preferred
29490 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
29491 doesn't require having two different development environments and makes the
29492 inter-language debugging experience smoother.
29494 @item
29495 When the compilation environment is located on FAT32 drives, users may
29496 experience recompilations of the source files that have not changed if
29497 Daylight Saving Time (DST) state has changed since the last time files
29498 were compiled. NTFS drives do not have this problem.
29500 @item
29501 No components of the GNAT toolset use any entries in the Windows
29502 registry. The only entries that can be created are file associations and
29503 PATH settings, provided the user has chosen to create them at installation
29504 time, as well as some minimal book-keeping information needed to correctly
29505 uninstall or integrate different GNAT products.
29506 @end itemize
29508 @node Using a network installation of GNAT
29509 @section Using a network installation of GNAT
29511 @noindent
29512 Make sure the system on which GNAT is installed is accessible from the
29513 current machine, i.e., the install location is shared over the network.
29514 Shared resources are accessed on Windows by means of UNC paths, which
29515 have the format @code{\\server\sharename\path}
29517 In order to use such a network installation, simply add the UNC path of the
29518 @file{bin} directory of your GNAT installation in front of your PATH. For
29519 example, if GNAT is installed in @file{\GNAT} directory of a share location
29520 called @file{c-drive} on a machine @file{LOKI}, the following command will
29521 make it available:
29523 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29525 Be aware that every compilation using the network installation results in the
29526 transfer of large amounts of data across the network and will likely cause
29527 serious performance penalty.
29529 @node CONSOLE and WINDOWS subsystems
29530 @section CONSOLE and WINDOWS subsystems
29531 @cindex CONSOLE Subsystem
29532 @cindex WINDOWS Subsystem
29533 @cindex -mwindows
29535 @noindent
29536 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29537 (which is the default subsystem) will always create a console when
29538 launching the application. This is not something desirable when the
29539 application has a Windows GUI. To get rid of this console the
29540 application must be using the @code{WINDOWS} subsystem. To do so
29541 the @option{-mwindows} linker option must be specified.
29543 @smallexample
29544 $ gnatmake winprog -largs -mwindows
29545 @end smallexample
29547 @node Temporary Files
29548 @section Temporary Files
29549 @cindex Temporary files
29551 @noindent
29552 It is possible to control where temporary files gets created by setting
29553 the @env{TMP} environment variable. The file will be created:
29555 @itemize
29556 @item Under the directory pointed to by the @env{TMP} environment variable if
29557 this directory exists.
29559 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
29560 set (or not pointing to a directory) and if this directory exists.
29562 @item Under the current working directory otherwise.
29563 @end itemize
29565 @noindent
29566 This allows you to determine exactly where the temporary
29567 file will be created. This is particularly useful in networked
29568 environments where you may not have write access to some
29569 directories.
29571 @node Mixed-Language Programming on Windows
29572 @section Mixed-Language Programming on Windows
29574 @noindent
29575 Developing pure Ada applications on Windows is no different than on
29576 other GNAT-supported platforms. However, when developing or porting an
29577 application that contains a mix of Ada and C/C++, the choice of your
29578 Windows C/C++ development environment conditions your overall
29579 interoperability strategy.
29581 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
29582 your application, there are no Windows-specific restrictions that
29583 affect the overall interoperability with your Ada code. If you do want
29584 to use the Microsoft tools for your C++ code, you have two choices:
29586 @enumerate
29587 @item
29588 Encapsulate your C++ code in a DLL to be linked with your Ada
29589 application. In this case, use the Microsoft or whatever environment to
29590 build the DLL and use GNAT to build your executable
29591 (@pxref{Using DLLs with GNAT}).
29593 @item
29594 Or you can encapsulate your Ada code in a DLL to be linked with the
29595 other part of your application. In this case, use GNAT to build the DLL
29596 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
29597 or whatever environment to build your executable.
29598 @end enumerate
29600 In addition to the description about C main in
29601 @pxref{Mixed Language Programming} section, if the C main uses a
29602 stand-alone library it is required on x86-windows to
29603 setup the SEH context. For this the C main must looks like this:
29605 @smallexample
29606 /* main.c */
29607 extern void adainit (void);
29608 extern void adafinal (void);
29609 extern void __gnat_initialize(void*);
29610 extern void call_to_ada (void);
29612 int main (int argc, char *argv[])
29614   int SEH [2];
29616   /* Initialize the SEH context */
29617   __gnat_initialize (&SEH);
29619   adainit();
29621   /* Then call Ada services in the stand-alone library */
29623   call_to_ada();
29625   adafinal();
29627 @end smallexample
29629 Note that this is not needed on x86_64-windows where the Windows
29630 native SEH support is used.
29632 @node Windows Calling Conventions
29633 @section Windows Calling Conventions
29634 @findex Stdcall
29635 @findex APIENTRY
29637 This section pertain only to Win32. On Win64 there is a single native
29638 calling convention. All convention specifiers are ignored on this
29639 platform.
29641 @menu
29642 * C Calling Convention::
29643 * Stdcall Calling Convention::
29644 * Win32 Calling Convention::
29645 * DLL Calling Convention::
29646 @end menu
29648 @noindent
29649 When a subprogram @code{F} (caller) calls a subprogram @code{G}
29650 (callee), there are several ways to push @code{G}'s parameters on the
29651 stack and there are several possible scenarios to clean up the stack
29652 upon @code{G}'s return. A calling convention is an agreed upon software
29653 protocol whereby the responsibilities between the caller (@code{F}) and
29654 the callee (@code{G}) are clearly defined. Several calling conventions
29655 are available for Windows:
29657 @itemize @bullet
29658 @item
29659 @code{C} (Microsoft defined)
29661 @item
29662 @code{Stdcall} (Microsoft defined)
29664 @item
29665 @code{Win32} (GNAT specific)
29667 @item
29668 @code{DLL} (GNAT specific)
29669 @end itemize
29671 @node C Calling Convention
29672 @subsection @code{C} Calling Convention
29674 @noindent
29675 This is the default calling convention used when interfacing to C/C++
29676 routines compiled with either @command{gcc} or Microsoft Visual C++.
29678 In the @code{C} calling convention subprogram parameters are pushed on the
29679 stack by the caller from right to left. The caller itself is in charge of
29680 cleaning up the stack after the call. In addition, the name of a routine
29681 with @code{C} calling convention is mangled by adding a leading underscore.
29683 The name to use on the Ada side when importing (or exporting) a routine
29684 with @code{C} calling convention is the name of the routine. For
29685 instance the C function:
29687 @smallexample
29688 int get_val (long);
29689 @end smallexample
29691 @noindent
29692 should be imported from Ada as follows:
29694 @smallexample @c ada
29695 @group
29696 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29697 pragma Import (C, Get_Val, External_Name => "get_val");
29698 @end group
29699 @end smallexample
29701 @noindent
29702 Note that in this particular case the @code{External_Name} parameter could
29703 have been omitted since, when missing, this parameter is taken to be the
29704 name of the Ada entity in lower case. When the @code{Link_Name} parameter
29705 is missing, as in the above example, this parameter is set to be the
29706 @code{External_Name} with a leading underscore.
29708 When importing a variable defined in C, you should always use the @code{C}
29709 calling convention unless the object containing the variable is part of a
29710 DLL (in which case you should use the @code{Stdcall} calling
29711 convention, @pxref{Stdcall Calling Convention}).
29713 @node Stdcall Calling Convention
29714 @subsection @code{Stdcall} Calling Convention
29716 @noindent
29717 This convention, which was the calling convention used for Pascal
29718 programs, is used by Microsoft for all the routines in the Win32 API for
29719 efficiency reasons. It must be used to import any routine for which this
29720 convention was specified.
29722 In the @code{Stdcall} calling convention subprogram parameters are pushed
29723 on the stack by the caller from right to left. The callee (and not the
29724 caller) is in charge of cleaning the stack on routine exit. In addition,
29725 the name of a routine with @code{Stdcall} calling convention is mangled by
29726 adding a leading underscore (as for the @code{C} calling convention) and a
29727 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
29728 bytes) of the parameters passed to the routine.
29730 The name to use on the Ada side when importing a C routine with a
29731 @code{Stdcall} calling convention is the name of the C routine. The leading
29732 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
29733 the compiler. For instance the Win32 function:
29735 @smallexample
29736 @b{APIENTRY} int get_val (long);
29737 @end smallexample
29739 @noindent
29740 should be imported from Ada as follows:
29742 @smallexample @c ada
29743 @group
29744 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29745 pragma Import (Stdcall, Get_Val);
29746 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
29747 @end group
29748 @end smallexample
29750 @noindent
29751 As for the @code{C} calling convention, when the @code{External_Name}
29752 parameter is missing, it is taken to be the name of the Ada entity in lower
29753 case. If instead of writing the above import pragma you write:
29755 @smallexample @c ada
29756 @group
29757 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29758 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
29759 @end group
29760 @end smallexample
29762 @noindent
29763 then the imported routine is @code{_retrieve_val@@4}. However, if instead
29764 of specifying the @code{External_Name} parameter you specify the
29765 @code{Link_Name} as in the following example:
29767 @smallexample @c ada
29768 @group
29769 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29770 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
29771 @end group
29772 @end smallexample
29774 @noindent
29775 then the imported routine is @code{retrieve_val}, that is, there is no
29776 decoration at all. No leading underscore and no Stdcall suffix
29777 @code{@@}@code{@var{nn}}.
29779 @noindent
29780 This is especially important as in some special cases a DLL's entry
29781 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
29782 name generated for a call has it.
29784 @noindent
29785 It is also possible to import variables defined in a DLL by using an
29786 import pragma for a variable. As an example, if a DLL contains a
29787 variable defined as:
29789 @smallexample
29790 int my_var;
29791 @end smallexample
29793 @noindent
29794 then, to access this variable from Ada you should write:
29796 @smallexample @c ada
29797 @group
29798 My_Var : Interfaces.C.int;
29799 pragma Import (Stdcall, My_Var);
29800 @end group
29801 @end smallexample
29803 @noindent
29804 Note that to ease building cross-platform bindings this convention
29805 will be handled as a @code{C} calling convention on non-Windows platforms.
29807 @node Win32 Calling Convention
29808 @subsection @code{Win32} Calling Convention
29810 @noindent
29811 This convention, which is GNAT-specific is fully equivalent to the
29812 @code{Stdcall} calling convention described above.
29814 @node DLL Calling Convention
29815 @subsection @code{DLL} Calling Convention
29817 @noindent
29818 This convention, which is GNAT-specific is fully equivalent to the
29819 @code{Stdcall} calling convention described above.
29821 @node Introduction to Dynamic Link Libraries (DLLs)
29822 @section Introduction to Dynamic Link Libraries (DLLs)
29823 @findex DLL
29825 @noindent
29826 A Dynamically Linked Library (DLL) is a library that can be shared by
29827 several applications running under Windows. A DLL can contain any number of
29828 routines and variables.
29830 One advantage of DLLs is that you can change and enhance them without
29831 forcing all the applications that depend on them to be relinked or
29832 recompiled. However, you should be aware than all calls to DLL routines are
29833 slower since, as you will understand below, such calls are indirect.
29835 To illustrate the remainder of this section, suppose that an application
29836 wants to use the services of a DLL @file{API.dll}. To use the services
29837 provided by @file{API.dll} you must statically link against the DLL or
29838 an import library which contains a jump table with an entry for each
29839 routine and variable exported by the DLL. In the Microsoft world this
29840 import library is called @file{API.lib}. When using GNAT this import
29841 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
29842 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
29844 After you have linked your application with the DLL or the import library
29845 and you run your application, here is what happens:
29847 @enumerate
29848 @item
29849 Your application is loaded into memory.
29851 @item
29852 The DLL @file{API.dll} is mapped into the address space of your
29853 application. This means that:
29855 @itemize @bullet
29856 @item
29857 The DLL will use the stack of the calling thread.
29859 @item
29860 The DLL will use the virtual address space of the calling process.
29862 @item
29863 The DLL will allocate memory from the virtual address space of the calling
29864 process.
29866 @item
29867 Handles (pointers) can be safely exchanged between routines in the DLL
29868 routines and routines in the application using the DLL.
29869 @end itemize
29871 @item
29872 The entries in the jump table (from the import library @file{libAPI.dll.a}
29873 or @file{API.lib} or automatically created when linking against a DLL)
29874 which is part of your application are initialized with the addresses
29875 of the routines and variables in @file{API.dll}.
29877 @item
29878 If present in @file{API.dll}, routines @code{DllMain} or
29879 @code{DllMainCRTStartup} are invoked. These routines typically contain
29880 the initialization code needed for the well-being of the routines and
29881 variables exported by the DLL.
29882 @end enumerate
29884 @noindent
29885 There is an additional point which is worth mentioning. In the Windows
29886 world there are two kind of DLLs: relocatable and non-relocatable
29887 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
29888 in the target application address space. If the addresses of two
29889 non-relocatable DLLs overlap and these happen to be used by the same
29890 application, a conflict will occur and the application will run
29891 incorrectly. Hence, when possible, it is always preferable to use and
29892 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
29893 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
29894 User's Guide) removes the debugging symbols from the DLL but the DLL can
29895 still be relocated.
29897 As a side note, an interesting difference between Microsoft DLLs and
29898 Unix shared libraries, is the fact that on most Unix systems all public
29899 routines are exported by default in a Unix shared library, while under
29900 Windows it is possible (but not required) to list exported routines in
29901 a definition file (@pxref{The Definition File}).
29903 @node Using DLLs with GNAT
29904 @section Using DLLs with GNAT
29906 @menu
29907 * Creating an Ada Spec for the DLL Services::
29908 * Creating an Import Library::
29909 @end menu
29911 @noindent
29912 To use the services of a DLL, say @file{API.dll}, in your Ada application
29913 you must have:
29915 @enumerate
29916 @item
29917 The Ada spec for the routines and/or variables you want to access in
29918 @file{API.dll}. If not available this Ada spec must be built from the C/C++
29919 header files provided with the DLL.
29921 @item
29922 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
29923 mentioned an import library is a statically linked library containing the
29924 import table which will be filled at load time to point to the actual
29925 @file{API.dll} routines. Sometimes you don't have an import library for the
29926 DLL you want to use. The following sections will explain how to build
29927 one. Note that this is optional.
29929 @item
29930 The actual DLL, @file{API.dll}.
29931 @end enumerate
29933 @noindent
29934 Once you have all the above, to compile an Ada application that uses the
29935 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
29936 you simply issue the command
29938 @smallexample
29939 $ gnatmake my_ada_app -largs -lAPI
29940 @end smallexample
29942 @noindent
29943 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
29944 tells the GNAT linker to look for an import library. The linker will
29945 look for a library name in this specific order:
29947 @enumerate
29948 @item @file{libAPI.dll.a}
29949 @item @file{API.dll.a}
29950 @item @file{libAPI.a}
29951 @item @file{API.lib}
29952 @item @file{libAPI.dll}
29953 @item @file{API.dll}
29954 @end enumerate
29956 The first three are the GNU style import libraries. The third is the
29957 Microsoft style import libraries. The last two are the actual DLL names.
29959 Note that if the Ada package spec for @file{API.dll} contains the
29960 following pragma
29962 @smallexample @c ada
29963 pragma Linker_Options ("-lAPI");
29964 @end smallexample
29966 @noindent
29967 you do not have to add @option{-largs -lAPI} at the end of the
29968 @command{gnatmake} command.
29970 If any one of the items above is missing you will have to create it
29971 yourself. The following sections explain how to do so using as an
29972 example a fictitious DLL called @file{API.dll}.
29974 @node Creating an Ada Spec for the DLL Services
29975 @subsection Creating an Ada Spec for the DLL Services
29977 @noindent
29978 A DLL typically comes with a C/C++ header file which provides the
29979 definitions of the routines and variables exported by the DLL. The Ada
29980 equivalent of this header file is a package spec that contains definitions
29981 for the imported entities. If the DLL you intend to use does not come with
29982 an Ada spec you have to generate one such spec yourself. For example if
29983 the header file of @file{API.dll} is a file @file{api.h} containing the
29984 following two definitions:
29986 @smallexample
29987 @group
29988 @cartouche
29989 int some_var;
29990 int get (char *);
29991 @end cartouche
29992 @end group
29993 @end smallexample
29995 @noindent
29996 then the equivalent Ada spec could be:
29998 @smallexample @c ada
29999 @group
30000 @cartouche
30001 with Interfaces.C.Strings;
30002 package API is
30003    use Interfaces;
30005    Some_Var : C.int;
30006    function Get (Str : C.Strings.Chars_Ptr) return C.int;
30008 private
30009    pragma Import (C, Get);
30010    pragma Import (DLL, Some_Var);
30011 end API;
30012 @end cartouche
30013 @end group
30014 @end smallexample
30016 @node Creating an Import Library
30017 @subsection Creating an Import Library
30018 @cindex Import library
30020 @menu
30021 * The Definition File::
30022 * GNAT-Style Import Library::
30023 * Microsoft-Style Import Library::
30024 @end menu
30026 @noindent
30027 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30028 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30029 with @file{API.dll} you can skip this section. You can also skip this
30030 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30031 as in this case it is possible to link directly against the
30032 DLL. Otherwise read on.
30034 @node The Definition File
30035 @subsubsection The Definition File
30036 @cindex Definition file
30037 @findex .def
30039 @noindent
30040 As previously mentioned, and unlike Unix systems, the list of symbols
30041 that are exported from a DLL must be provided explicitly in Windows.
30042 The main goal of a definition file is precisely that: list the symbols
30043 exported by a DLL. A definition file (usually a file with a @code{.def}
30044 suffix) has the following structure:
30046 @smallexample
30047 @group
30048 @cartouche
30049 @r{[}LIBRARY @var{name}@r{]}
30050 @r{[}DESCRIPTION @var{string}@r{]}
30051 EXPORTS
30052    @var{symbol1}
30053    @var{symbol2}
30054    @dots{}
30055 @end cartouche
30056 @end group
30057 @end smallexample
30059 @table @code
30060 @item LIBRARY @var{name}
30061 This section, which is optional, gives the name of the DLL.
30063 @item DESCRIPTION @var{string}
30064 This section, which is optional, gives a description string that will be
30065 embedded in the import library.
30067 @item EXPORTS
30068 This section gives the list of exported symbols (procedures, functions or
30069 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30070 section of @file{API.def} looks like:
30072 @smallexample
30073 @group
30074 @cartouche
30075 EXPORTS
30076    some_var
30077    get
30078 @end cartouche
30079 @end group
30080 @end smallexample
30081 @end table
30083 @noindent
30084 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
30085 (@pxref{Windows Calling Conventions}) for a Stdcall
30086 calling convention function in the exported symbols list.
30088 @noindent
30089 There can actually be other sections in a definition file, but these
30090 sections are not relevant to the discussion at hand.
30092 @node GNAT-Style Import Library
30093 @subsubsection GNAT-Style Import Library
30095 @noindent
30096 To create a static import library from @file{API.dll} with the GNAT tools
30097 you should proceed as follows:
30099 @enumerate
30100 @item
30101 Create the definition file @file{API.def} (@pxref{The Definition File}).
30102 For that use the @code{dll2def} tool as follows:
30104 @smallexample
30105 $ dll2def API.dll > API.def
30106 @end smallexample
30108 @noindent
30109 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30110 to standard output the list of entry points in the DLL. Note that if
30111 some routines in the DLL have the @code{Stdcall} convention
30112 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
30113 suffix then you'll have to edit @file{api.def} to add it, and specify
30114 @option{-k} to @command{gnatdll} when creating the import library.
30116 @noindent
30117 Here are some hints to find the right @code{@@}@var{nn} suffix.
30119 @enumerate
30120 @item
30121 If you have the Microsoft import library (.lib), it is possible to get
30122 the right symbols by using Microsoft @code{dumpbin} tool (see the
30123 corresponding Microsoft documentation for further details).
30125 @smallexample
30126 $ dumpbin /exports api.lib
30127 @end smallexample
30129 @item
30130 If you have a message about a missing symbol at link time the compiler
30131 tells you what symbol is expected. You just have to go back to the
30132 definition file and add the right suffix.
30133 @end enumerate
30135 @item
30136 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30137 (@pxref{Using gnatdll}) as follows:
30139 @smallexample
30140 $ gnatdll -e API.def -d API.dll
30141 @end smallexample
30143 @noindent
30144 @code{gnatdll} takes as input a definition file @file{API.def} and the
30145 name of the DLL containing the services listed in the definition file
30146 @file{API.dll}. The name of the static import library generated is
30147 computed from the name of the definition file as follows: if the
30148 definition file name is @var{xyz}@code{.def}, the import library name will
30149 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
30150 @option{-e} could have been removed because the name of the definition
30151 file (before the ``@code{.def}'' suffix) is the same as the name of the
30152 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30153 @end enumerate
30155 @node Microsoft-Style Import Library
30156 @subsubsection Microsoft-Style Import Library
30158 @noindent
30159 With GNAT you can either use a GNAT-style or Microsoft-style import
30160 library. A Microsoft import library is needed only if you plan to make an
30161 Ada DLL available to applications developed with Microsoft
30162 tools (@pxref{Mixed-Language Programming on Windows}).
30164 To create a Microsoft-style import library for @file{API.dll} you
30165 should proceed as follows:
30167 @enumerate
30168 @item
30169 Create the definition file @file{API.def} from the DLL. For this use either
30170 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30171 tool (see the corresponding Microsoft documentation for further details).
30173 @item
30174 Build the actual import library using Microsoft's @code{lib} utility:
30176 @smallexample
30177 $ lib -machine:IX86 -def:API.def -out:API.lib
30178 @end smallexample
30180 @noindent
30181 If you use the above command the definition file @file{API.def} must
30182 contain a line giving the name of the DLL:
30184 @smallexample
30185 LIBRARY      "API"
30186 @end smallexample
30188 @noindent
30189 See the Microsoft documentation for further details about the usage of
30190 @code{lib}.
30191 @end enumerate
30193 @node Building DLLs with GNAT Project files
30194 @section Building DLLs with GNAT Project files
30195 @cindex DLLs, building
30197 @noindent
30198 There is nothing specific to Windows in the build process.
30199 @pxref{Library Projects}.
30201 @noindent
30202 Due to a system limitation, it is not possible under Windows to create threads
30203 when inside the @code{DllMain} routine which is used for auto-initialization
30204 of shared libraries, so it is not possible to have library level tasks in SALs.
30206 @node Building DLLs with GNAT
30207 @section Building DLLs with GNAT
30208 @cindex DLLs, building
30210 @noindent
30211 This section explain how to build DLLs using the GNAT built-in DLL
30212 support. With the following procedure it is straight forward to build
30213 and use DLLs with GNAT.
30215 @enumerate
30217 @item building object files
30219 The first step is to build all objects files that are to be included
30220 into the DLL. This is done by using the standard @command{gnatmake} tool.
30222 @item building the DLL
30224 To build the DLL you must use @command{gcc}'s @option{-shared} and
30225 @option{-shared-libgcc} options. It is quite simple to use this method:
30227 @smallexample
30228 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
30229 @end smallexample
30231 It is important to note that in this case all symbols found in the
30232 object files are automatically exported. It is possible to restrict
30233 the set of symbols to export by passing to @command{gcc} a definition
30234 file, @pxref{The Definition File}. For example:
30236 @smallexample
30237 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
30238 @end smallexample
30240 If you use a definition file you must export the elaboration procedures
30241 for every package that required one. Elaboration procedures are named
30242 using the package name followed by "_E".
30244 @item preparing DLL to be used
30246 For the DLL to be used by client programs the bodies must be hidden
30247 from it and the .ali set with read-only attribute. This is very important
30248 otherwise GNAT will recompile all packages and will not actually use
30249 the code in the DLL. For example:
30251 @smallexample
30252 $ mkdir apilib
30253 $ copy *.ads *.ali api.dll apilib
30254 $ attrib +R apilib\*.ali
30255 @end smallexample
30257 @end enumerate
30259 At this point it is possible to use the DLL by directly linking
30260 against it. Note that you must use the GNAT shared runtime when using
30261 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30262 option.
30264 @smallexample
30265 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30266 @end smallexample
30268 @node Building DLLs with gnatdll
30269 @section Building DLLs with gnatdll
30270 @cindex DLLs, building
30272 @menu
30273 * Limitations When Using Ada DLLs from Ada::
30274 * Exporting Ada Entities::
30275 * Ada DLLs and Elaboration::
30276 * Ada DLLs and Finalization::
30277 * Creating a Spec for Ada DLLs::
30278 * Creating the Definition File::
30279 * Using gnatdll::
30280 @end menu
30282 @noindent
30283 Note that it is preferred to use GNAT Project files
30284 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30285 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30287 This section explains how to build DLLs containing Ada code using
30288 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30289 remainder of this section.
30291 The steps required to build an Ada DLL that is to be used by Ada as well as
30292 non-Ada applications are as follows:
30294 @enumerate
30295 @item
30296 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30297 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30298 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30299 skip this step if you plan to use the Ada DLL only from Ada applications.
30301 @item
30302 Your Ada code must export an initialization routine which calls the routine
30303 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30304 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30305 routine exported by the Ada DLL must be invoked by the clients of the DLL
30306 to initialize the DLL.
30308 @item
30309 When useful, the DLL should also export a finalization routine which calls
30310 routine @code{adafinal} generated by @command{gnatbind} to perform the
30311 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30312 The finalization routine exported by the Ada DLL must be invoked by the
30313 clients of the DLL when the DLL services are no further needed.
30315 @item
30316 You must provide a spec for the services exported by the Ada DLL in each
30317 of the programming languages to which you plan to make the DLL available.
30319 @item
30320 You must provide a definition file listing the exported entities
30321 (@pxref{The Definition File}).
30323 @item
30324 Finally you must use @code{gnatdll} to produce the DLL and the import
30325 library (@pxref{Using gnatdll}).
30326 @end enumerate
30328 @noindent
30329 Note that a relocatable DLL stripped using the @code{strip}
30330 binutils tool will not be relocatable anymore. To build a DLL without
30331 debug information pass @code{-largs -s} to @code{gnatdll}. This
30332 restriction does not apply to a DLL built using a Library Project.
30333 @pxref{Library Projects}.
30335 @node Limitations When Using Ada DLLs from Ada
30336 @subsection Limitations When Using Ada DLLs from Ada
30338 @noindent
30339 When using Ada DLLs from Ada applications there is a limitation users
30340 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30341 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30342 each Ada DLL includes the services of the GNAT run time that are necessary
30343 to the Ada code inside the DLL. As a result, when an Ada program uses an
30344 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30345 one in the main program.
30347 It is therefore not possible to exchange GNAT run-time objects between the
30348 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30349 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30350 types, etc.
30352 It is completely safe to exchange plain elementary, array or record types,
30353 Windows object handles, etc.
30355 @node Exporting Ada Entities
30356 @subsection Exporting Ada Entities
30357 @cindex Export table
30359 @noindent
30360 Building a DLL is a way to encapsulate a set of services usable from any
30361 application. As a result, the Ada entities exported by a DLL should be
30362 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30363 any Ada name mangling. As an example here is an Ada package
30364 @code{API}, spec and body, exporting two procedures, a function, and a
30365 variable:
30367 @smallexample @c ada
30368 @group
30369 @cartouche
30370 with Interfaces.C; use Interfaces;
30371 package API is
30372    Count : C.int := 0;
30373    function Factorial (Val : C.int) return C.int;
30375    procedure Initialize_API;
30376    procedure Finalize_API;
30377    --  Initialization & Finalization routines. More in the next section.
30378 private
30379    pragma Export (C, Initialize_API);
30380    pragma Export (C, Finalize_API);
30381    pragma Export (C, Count);
30382    pragma Export (C, Factorial);
30383 end API;
30384 @end cartouche
30385 @end group
30386 @end smallexample
30388 @smallexample @c ada
30389 @group
30390 @cartouche
30391 package body API is
30392    function Factorial (Val : C.int) return C.int is
30393       Fact : C.int := 1;
30394    begin
30395       Count := Count + 1;
30396       for K in 1 .. Val loop
30397          Fact := Fact * K;
30398       end loop;
30399       return Fact;
30400    end Factorial;
30402    procedure Initialize_API is
30403       procedure Adainit;
30404       pragma Import (C, Adainit);
30405    begin
30406       Adainit;
30407    end Initialize_API;
30409    procedure Finalize_API is
30410       procedure Adafinal;
30411       pragma Import (C, Adafinal);
30412    begin
30413       Adafinal;
30414    end Finalize_API;
30415 end API;
30416 @end cartouche
30417 @end group
30418 @end smallexample
30420 @noindent
30421 If the Ada DLL you are building will only be used by Ada applications
30422 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30423 convention. As an example, the previous package could be written as
30424 follows:
30426 @smallexample @c ada
30427 @group
30428 @cartouche
30429 package API is
30430    Count : Integer := 0;
30431    function Factorial (Val : Integer) return Integer;
30433    procedure Initialize_API;
30434    procedure Finalize_API;
30435    --  Initialization and Finalization routines.
30436 end API;
30437 @end cartouche
30438 @end group
30439 @end smallexample
30441 @smallexample @c ada
30442 @group
30443 @cartouche
30444 package body API is
30445    function Factorial (Val : Integer) return Integer is
30446       Fact : Integer := 1;
30447    begin
30448       Count := Count + 1;
30449       for K in 1 .. Val loop
30450          Fact := Fact * K;
30451       end loop;
30452       return Fact;
30453    end Factorial;
30455    @dots{}
30456    --  The remainder of this package body is unchanged.
30457 end API;
30458 @end cartouche
30459 @end group
30460 @end smallexample
30462 @noindent
30463 Note that if you do not export the Ada entities with a @code{C} or
30464 @code{Stdcall} convention you will have to provide the mangled Ada names
30465 in the definition file of the Ada DLL
30466 (@pxref{Creating the Definition File}).
30468 @node Ada DLLs and Elaboration
30469 @subsection Ada DLLs and Elaboration
30470 @cindex DLLs and elaboration
30472 @noindent
30473 The DLL that you are building contains your Ada code as well as all the
30474 routines in the Ada library that are needed by it. The first thing a
30475 user of your DLL must do is elaborate the Ada code
30476 (@pxref{Elaboration Order Handling in GNAT}).
30478 To achieve this you must export an initialization routine
30479 (@code{Initialize_API} in the previous example), which must be invoked
30480 before using any of the DLL services. This elaboration routine must call
30481 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30482 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30483 @code{Initialize_Api} for an example. Note that the GNAT binder is
30484 automatically invoked during the DLL build process by the @code{gnatdll}
30485 tool (@pxref{Using gnatdll}).
30487 When a DLL is loaded, Windows systematically invokes a routine called
30488 @code{DllMain}. It would therefore be possible to call @code{adainit}
30489 directly from @code{DllMain} without having to provide an explicit
30490 initialization routine. Unfortunately, it is not possible to call
30491 @code{adainit} from the @code{DllMain} if your program has library level
30492 tasks because access to the @code{DllMain} entry point is serialized by
30493 the system (that is, only a single thread can execute ``through'' it at a
30494 time), which means that the GNAT run time will deadlock waiting for the
30495 newly created task to complete its initialization.
30497 @node Ada DLLs and Finalization
30498 @subsection Ada DLLs and Finalization
30499 @cindex DLLs and finalization
30501 @noindent
30502 When the services of an Ada DLL are no longer needed, the client code should
30503 invoke the DLL finalization routine, if available. The DLL finalization
30504 routine is in charge of releasing all resources acquired by the DLL. In the
30505 case of the Ada code contained in the DLL, this is achieved by calling
30506 routine @code{adafinal} generated by the GNAT binder
30507 (@pxref{Binding with Non-Ada Main Programs}).
30508 See the body of @code{Finalize_Api} for an
30509 example. As already pointed out the GNAT binder is automatically invoked
30510 during the DLL build process by the @code{gnatdll} tool
30511 (@pxref{Using gnatdll}).
30513 @node Creating a Spec for Ada DLLs
30514 @subsection Creating a Spec for Ada DLLs
30516 @noindent
30517 To use the services exported by the Ada DLL from another programming
30518 language (e.g.@: C), you have to translate the specs of the exported Ada
30519 entities in that language. For instance in the case of @code{API.dll},
30520 the corresponding C header file could look like:
30522 @smallexample
30523 @group
30524 @cartouche
30525 extern int *_imp__count;
30526 #define count (*_imp__count)
30527 int factorial (int);
30528 @end cartouche
30529 @end group
30530 @end smallexample
30532 @noindent
30533 It is important to understand that when building an Ada DLL to be used by
30534 other Ada applications, you need two different specs for the packages
30535 contained in the DLL: one for building the DLL and the other for using
30536 the DLL. This is because the @code{DLL} calling convention is needed to
30537 use a variable defined in a DLL, but when building the DLL, the variable
30538 must have either the @code{Ada} or @code{C} calling convention. As an
30539 example consider a DLL comprising the following package @code{API}:
30541 @smallexample @c ada
30542 @group
30543 @cartouche
30544 package API is
30545    Count : Integer := 0;
30546    @dots{}
30547    --  Remainder of the package omitted.
30548 end API;
30549 @end cartouche
30550 @end group
30551 @end smallexample
30553 @noindent
30554 After producing a DLL containing package @code{API}, the spec that
30555 must be used to import @code{API.Count} from Ada code outside of the
30556 DLL is:
30558 @smallexample @c ada
30559 @group
30560 @cartouche
30561 package API is
30562    Count : Integer;
30563    pragma Import (DLL, Count);
30564 end API;
30565 @end cartouche
30566 @end group
30567 @end smallexample
30569 @node Creating the Definition File
30570 @subsection Creating the Definition File
30572 @noindent
30573 The definition file is the last file needed to build the DLL. It lists
30574 the exported symbols. As an example, the definition file for a DLL
30575 containing only package @code{API} (where all the entities are exported
30576 with a @code{C} calling convention) is:
30578 @smallexample
30579 @group
30580 @cartouche
30581 EXPORTS
30582     count
30583     factorial
30584     finalize_api
30585     initialize_api
30586 @end cartouche
30587 @end group
30588 @end smallexample
30590 @noindent
30591 If the @code{C} calling convention is missing from package @code{API},
30592 then the definition file contains the mangled Ada names of the above
30593 entities, which in this case are:
30595 @smallexample
30596 @group
30597 @cartouche
30598 EXPORTS
30599     api__count
30600     api__factorial
30601     api__finalize_api
30602     api__initialize_api
30603 @end cartouche
30604 @end group
30605 @end smallexample
30607 @node Using gnatdll
30608 @subsection Using @code{gnatdll}
30609 @findex gnatdll
30611 @menu
30612 * gnatdll Example::
30613 * gnatdll behind the Scenes::
30614 * Using dlltool::
30615 @end menu
30617 @noindent
30618 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30619 and non-Ada sources that make up your DLL have been compiled.
30620 @code{gnatdll} is actually in charge of two distinct tasks: build the
30621 static import library for the DLL and the actual DLL. The form of the
30622 @code{gnatdll} command is
30624 @smallexample
30625 @cartouche
30626 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30627 @c Expanding @ovar macro inline (explanation in macro def comments)
30628 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30629 @end cartouche
30630 @end smallexample
30632 @noindent
30633 where @var{list-of-files} is a list of ALI and object files. The object
30634 file list must be the exact list of objects corresponding to the non-Ada
30635 sources whose services are to be included in the DLL. The ALI file list
30636 must be the exact list of ALI files for the corresponding Ada sources
30637 whose services are to be included in the DLL. If @var{list-of-files} is
30638 missing, only the static import library is generated.
30640 @noindent
30641 You may specify any of the following switches to @code{gnatdll}:
30643 @table @code
30644 @c @item -a@ovar{address}
30645 @c Expanding @ovar macro inline (explanation in macro def comments)
30646 @item -a@r{[}@var{address}@r{]}
30647 @cindex @option{-a} (@code{gnatdll})
30648 Build a non-relocatable DLL at @var{address}. If @var{address} is not
30649 specified the default address @var{0x11000000} will be used. By default,
30650 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
30651 advise the reader to build relocatable DLL.
30653 @item -b @var{address}
30654 @cindex @option{-b} (@code{gnatdll})
30655 Set the relocatable DLL base address. By default the address is
30656 @code{0x11000000}.
30658 @item -bargs @var{opts}
30659 @cindex @option{-bargs} (@code{gnatdll})
30660 Binder options. Pass @var{opts} to the binder.
30662 @item -d @var{dllfile}
30663 @cindex @option{-d} (@code{gnatdll})
30664 @var{dllfile} is the name of the DLL. This switch must be present for
30665 @code{gnatdll} to do anything. The name of the generated import library is
30666 obtained algorithmically from @var{dllfile} as shown in the following
30667 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
30668 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
30669 by option @option{-e}) is obtained algorithmically from @var{dllfile}
30670 as shown in the following example:
30671 if @var{dllfile} is @code{xyz.dll}, the definition
30672 file used is @code{xyz.def}.
30674 @item -e @var{deffile}
30675 @cindex @option{-e} (@code{gnatdll})
30676 @var{deffile} is the name of the definition file.
30678 @item -g
30679 @cindex @option{-g} (@code{gnatdll})
30680 Generate debugging information. This information is stored in the object
30681 file and copied from there to the final DLL file by the linker,
30682 where it can be read by the debugger. You must use the
30683 @option{-g} switch if you plan on using the debugger or the symbolic
30684 stack traceback.
30686 @item -h
30687 @cindex @option{-h} (@code{gnatdll})
30688 Help mode. Displays @code{gnatdll} switch usage information.
30690 @item -Idir
30691 @cindex @option{-I} (@code{gnatdll})
30692 Direct @code{gnatdll} to search the @var{dir} directory for source and
30693 object files needed to build the DLL.
30694 (@pxref{Search Paths and the Run-Time Library (RTL)}).
30696 @item -k
30697 @cindex @option{-k} (@code{gnatdll})
30698 Removes the @code{@@}@var{nn} suffix from the import library's exported
30699 names, but keeps them for the link names. You must specify this
30700 option if you want to use a @code{Stdcall} function in a DLL for which
30701 the @code{@@}@var{nn} suffix has been removed. This is the case for most
30702 of the Windows NT DLL for example. This option has no effect when
30703 @option{-n} option is specified.
30705 @item -l @var{file}
30706 @cindex @option{-l} (@code{gnatdll})
30707 The list of ALI and object files used to build the DLL are listed in
30708 @var{file}, instead of being given in the command line. Each line in
30709 @var{file} contains the name of an ALI or object file.
30711 @item -n
30712 @cindex @option{-n} (@code{gnatdll})
30713 No Import. Do not create the import library.
30715 @item -q
30716 @cindex @option{-q} (@code{gnatdll})
30717 Quiet mode. Do not display unnecessary messages.
30719 @item -v
30720 @cindex @option{-v} (@code{gnatdll})
30721 Verbose mode. Display extra information.
30723 @item -largs @var{opts}
30724 @cindex @option{-largs} (@code{gnatdll})
30725 Linker options. Pass @var{opts} to the linker.
30726 @end table
30728 @node gnatdll Example
30729 @subsubsection @code{gnatdll} Example
30731 @noindent
30732 As an example the command to build a relocatable DLL from @file{api.adb}
30733 once @file{api.adb} has been compiled and @file{api.def} created is
30735 @smallexample
30736 $ gnatdll -d api.dll api.ali
30737 @end smallexample
30739 @noindent
30740 The above command creates two files: @file{libapi.dll.a} (the import
30741 library) and @file{api.dll} (the actual DLL). If you want to create
30742 only the DLL, just type:
30744 @smallexample
30745 $ gnatdll -d api.dll -n api.ali
30746 @end smallexample
30748 @noindent
30749 Alternatively if you want to create just the import library, type:
30751 @smallexample
30752 $ gnatdll -d api.dll
30753 @end smallexample
30755 @node gnatdll behind the Scenes
30756 @subsubsection @code{gnatdll} behind the Scenes
30758 @noindent
30759 This section details the steps involved in creating a DLL. @code{gnatdll}
30760 does these steps for you. Unless you are interested in understanding what
30761 goes on behind the scenes, you should skip this section.
30763 We use the previous example of a DLL containing the Ada package @code{API},
30764 to illustrate the steps necessary to build a DLL. The starting point is a
30765 set of objects that will make up the DLL and the corresponding ALI
30766 files. In the case of this example this means that @file{api.o} and
30767 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
30768 the following:
30770 @enumerate
30771 @item
30772 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
30773 the information necessary to generate relocation information for the
30774 DLL.
30776 @smallexample
30777 @group
30778 $ gnatbind -n api
30779 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
30780 @end group
30781 @end smallexample
30783 @noindent
30784 In addition to the base file, the @command{gnatlink} command generates an
30785 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
30786 asks @command{gnatlink} to generate the routines @code{DllMain} and
30787 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
30788 is loaded into memory.
30790 @item
30791 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
30792 export table (@file{api.exp}). The export table contains the relocation
30793 information in a form which can be used during the final link to ensure
30794 that the Windows loader is able to place the DLL anywhere in memory.
30796 @smallexample
30797 @group
30798 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30799           --output-exp api.exp
30800 @end group
30801 @end smallexample
30803 @item
30804 @code{gnatdll} builds the base file using the new export table. Note that
30805 @command{gnatbind} must be called once again since the binder generated file
30806 has been deleted during the previous call to @command{gnatlink}.
30808 @smallexample
30809 @group
30810 $ gnatbind -n api
30811 $ gnatlink api -o api.jnk api.exp -mdll
30812       -Wl,--base-file,api.base
30813 @end group
30814 @end smallexample
30816 @item
30817 @code{gnatdll} builds the new export table using the new base file and
30818 generates the DLL import library @file{libAPI.dll.a}.
30820 @smallexample
30821 @group
30822 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30823           --output-exp api.exp --output-lib libAPI.a
30824 @end group
30825 @end smallexample
30827 @item
30828 Finally @code{gnatdll} builds the relocatable DLL using the final export
30829 table.
30831 @smallexample
30832 @group
30833 $ gnatbind -n api
30834 $ gnatlink api api.exp -o api.dll -mdll
30835 @end group
30836 @end smallexample
30837 @end enumerate
30839 @node Using dlltool
30840 @subsubsection Using @code{dlltool}
30842 @noindent
30843 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
30844 DLLs and static import libraries. This section summarizes the most
30845 common @code{dlltool} switches. The form of the @code{dlltool} command
30848 @smallexample
30849 @c $ dlltool @ovar{switches}
30850 @c Expanding @ovar macro inline (explanation in macro def comments)
30851 $ dlltool @r{[}@var{switches}@r{]}
30852 @end smallexample
30854 @noindent
30855 @code{dlltool} switches include:
30857 @table @option
30858 @item --base-file @var{basefile}
30859 @cindex @option{--base-file} (@command{dlltool})
30860 Read the base file @var{basefile} generated by the linker. This switch
30861 is used to create a relocatable DLL.
30863 @item --def @var{deffile}
30864 @cindex @option{--def} (@command{dlltool})
30865 Read the definition file.
30867 @item --dllname @var{name}
30868 @cindex @option{--dllname} (@command{dlltool})
30869 Gives the name of the DLL. This switch is used to embed the name of the
30870 DLL in the static import library generated by @code{dlltool} with switch
30871 @option{--output-lib}.
30873 @item -k
30874 @cindex @option{-k} (@command{dlltool})
30875 Kill @code{@@}@var{nn} from exported names
30876 (@pxref{Windows Calling Conventions}
30877 for a discussion about @code{Stdcall}-style symbols.
30879 @item --help
30880 @cindex @option{--help} (@command{dlltool})
30881 Prints the @code{dlltool} switches with a concise description.
30883 @item --output-exp @var{exportfile}
30884 @cindex @option{--output-exp} (@command{dlltool})
30885 Generate an export file @var{exportfile}. The export file contains the
30886 export table (list of symbols in the DLL) and is used to create the DLL.
30888 @item --output-lib @var{libfile}
30889 @cindex @option{--output-lib} (@command{dlltool})
30890 Generate a static import library @var{libfile}.
30892 @item -v
30893 @cindex @option{-v} (@command{dlltool})
30894 Verbose mode.
30896 @item --as @var{assembler-name}
30897 @cindex @option{--as} (@command{dlltool})
30898 Use @var{assembler-name} as the assembler. The default is @code{as}.
30899 @end table
30901 @node GNAT and Windows Resources
30902 @section GNAT and Windows Resources
30903 @cindex Resources, windows
30905 @menu
30906 * Building Resources::
30907 * Compiling Resources::
30908 * Using Resources::
30909 @end menu
30911 @noindent
30912 Resources are an easy way to add Windows specific objects to your
30913 application. The objects that can be added as resources include:
30915 @itemize @bullet
30916 @item menus
30918 @item accelerators
30920 @item dialog boxes
30922 @item string tables
30924 @item bitmaps
30926 @item cursors
30928 @item icons
30930 @item fonts
30932 @item version information
30933 @end itemize
30935 For example, a version information resource can be defined as follow and
30936 embedded into an executable or DLL:
30938 A version information resource can be used to embed information into an
30939 executable or a DLL. These information can be viewed using the file properties
30940 from the Windows Explorer. Here is an example of a version information
30941 resource:
30943 @smallexample
30944 @group
30945 1 VERSIONINFO
30946 FILEVERSION     1,0,0,0
30947 PRODUCTVERSION  1,0,0,0
30948 BEGIN
30949   BLOCK "StringFileInfo"
30950   BEGIN
30951     BLOCK "080904E4"
30952     BEGIN
30953       VALUE "CompanyName", "My Company Name"
30954       VALUE "FileDescription", "My application"
30955       VALUE "FileVersion", "1.0"
30956       VALUE "InternalName", "my_app"
30957       VALUE "LegalCopyright", "My Name"
30958       VALUE "OriginalFilename", "my_app.exe"
30959       VALUE "ProductName", "My App"
30960       VALUE "ProductVersion", "1.0"
30961     END
30962   END
30964   BLOCK "VarFileInfo"
30965   BEGIN
30966     VALUE "Translation", 0x809, 1252
30967   END
30969 @end group
30970 @end smallexample
30972 The value @code{0809} (langID) is for the U.K English language and
30973 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
30974 multilingual.
30976 @noindent
30977 This section explains how to build, compile and use resources. Note that this
30978 section does not cover all resource objects, for a complete description see
30979 the corresponding Microsoft documentation.
30981 @node Building Resources
30982 @subsection Building Resources
30983 @cindex Resources, building
30985 @noindent
30986 A resource file is an ASCII file. By convention resource files have an
30987 @file{.rc} extension.
30988 The easiest way to build a resource file is to use Microsoft tools
30989 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
30990 @code{dlgedit.exe} to build dialogs.
30991 It is always possible to build an @file{.rc} file yourself by writing a
30992 resource script.
30994 It is not our objective to explain how to write a resource file. A
30995 complete description of the resource script language can be found in the
30996 Microsoft documentation.
30998 @node Compiling Resources
30999 @subsection Compiling Resources
31000 @findex rc
31001 @findex windres
31002 @cindex Resources, compiling
31004 @noindent
31005 This section describes how to build a GNAT-compatible (COFF) object file
31006 containing the resources. This is done using the Resource Compiler
31007 @code{windres} as follows:
31009 @smallexample
31010 $ windres -i myres.rc -o myres.o
31011 @end smallexample
31013 @noindent
31014 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31015 file. You can specify an alternate preprocessor (usually named
31016 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31017 parameter. A list of all possible options may be obtained by entering
31018 the command @code{windres} @option{--help}.
31020 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31021 to produce a @file{.res} file (binary resource file). See the
31022 corresponding Microsoft documentation for further details. In this case
31023 you need to use @code{windres} to translate the @file{.res} file to a
31024 GNAT-compatible object file as follows:
31026 @smallexample
31027 $ windres -i myres.res -o myres.o
31028 @end smallexample
31030 @node Using Resources
31031 @subsection Using Resources
31032 @cindex Resources, using
31034 @noindent
31035 To include the resource file in your program just add the
31036 GNAT-compatible object file for the resource(s) to the linker
31037 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31038 option:
31040 @smallexample
31041 $ gnatmake myprog -largs myres.o
31042 @end smallexample
31044 @node Debugging a DLL
31045 @section Debugging a DLL
31046 @cindex DLL debugging
31048 @menu
31049 * Program and DLL Both Built with GCC/GNAT::
31050 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31051 @end menu
31053 @noindent
31054 Debugging a DLL is similar to debugging a standard program. But
31055 we have to deal with two different executable parts: the DLL and the
31056 program that uses it. We have the following four possibilities:
31058 @enumerate 1
31059 @item
31060 The program and the DLL are built with @code{GCC/GNAT}.
31061 @item
31062 The program is built with foreign tools and the DLL is built with
31063 @code{GCC/GNAT}.
31064 @item
31065 The program is built with @code{GCC/GNAT} and the DLL is built with
31066 foreign tools.
31067 @end enumerate
31069 @noindent
31070 In this section we address only cases one and two above.
31071 There is no point in trying to debug
31072 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31073 information in it. To do so you must use a debugger compatible with the
31074 tools suite used to build the DLL.
31076 @node Program and DLL Both Built with GCC/GNAT
31077 @subsection Program and DLL Both Built with GCC/GNAT
31079 @noindent
31080 This is the simplest case. Both the DLL and the program have @code{GDB}
31081 compatible debugging information. It is then possible to break anywhere in
31082 the process. Let's suppose here that the main procedure is named
31083 @code{ada_main} and that in the DLL there is an entry point named
31084 @code{ada_dll}.
31086 @noindent
31087 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31088 program must have been built with the debugging information (see GNAT -g
31089 switch). Here are the step-by-step instructions for debugging it:
31091 @enumerate 1
31092 @item Launch @code{GDB} on the main program.
31094 @smallexample
31095 $ gdb -nw ada_main
31096 @end smallexample
31098 @item Start the program and stop at the beginning of the main procedure
31100 @smallexample
31101 (gdb) start
31102 @end smallexample
31104 @noindent
31105 This step is required to be able to set a breakpoint inside the DLL. As long
31106 as the program is not run, the DLL is not loaded. This has the
31107 consequence that the DLL debugging information is also not loaded, so it is not
31108 possible to set a breakpoint in the DLL.
31110 @item Set a breakpoint inside the DLL
31112 @smallexample
31113 (gdb) break ada_dll
31114 (gdb) cont
31115 @end smallexample
31117 @end enumerate
31119 @noindent
31120 At this stage a breakpoint is set inside the DLL. From there on
31121 you can use the standard approach to debug the whole program
31122 (@pxref{Running and Debugging Ada Programs}).
31124 @ignore
31125 @c This used to work, probably because the DLLs were non-relocatable
31126 @c keep this section around until the problem is sorted out.
31128 To break on the @code{DllMain} routine it is not possible to follow
31129 the procedure above. At the time the program stop on @code{ada_main}
31130 the @code{DllMain} routine as already been called. Either you can use
31131 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31133 @enumerate 1
31134 @item Launch @code{GDB} on the main program.
31136 @smallexample
31137 $ gdb ada_main
31138 @end smallexample
31140 @item Load DLL symbols
31142 @smallexample
31143 (gdb) add-sym api.dll
31144 @end smallexample
31146 @item Set a breakpoint inside the DLL
31148 @smallexample
31149 (gdb) break ada_dll.adb:45
31150 @end smallexample
31152 Note that at this point it is not possible to break using the routine symbol
31153 directly as the program is not yet running. The solution is to break
31154 on the proper line (break in @file{ada_dll.adb} line 45).
31156 @item Start the program
31158 @smallexample
31159 (gdb) run
31160 @end smallexample
31162 @end enumerate
31163 @end ignore
31165 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31166 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31168 @menu
31169 * Debugging the DLL Directly::
31170 * Attaching to a Running Process::
31171 @end menu
31173 @noindent
31174 In this case things are slightly more complex because it is not possible to
31175 start the main program and then break at the beginning to load the DLL and the
31176 associated DLL debugging information. It is not possible to break at the
31177 beginning of the program because there is no @code{GDB} debugging information,
31178 and therefore there is no direct way of getting initial control. This
31179 section addresses this issue by describing some methods that can be used
31180 to break somewhere in the DLL to debug it.
31182 @noindent
31183 First suppose that the main procedure is named @code{main} (this is for
31184 example some C code built with Microsoft Visual C) and that there is a
31185 DLL named @code{test.dll} containing an Ada entry point named
31186 @code{ada_dll}.
31188 @noindent
31189 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31190 been built with debugging information (see GNAT -g option).
31192 @node Debugging the DLL Directly
31193 @subsubsection Debugging the DLL Directly
31195 @enumerate 1
31196 @item
31197 Find out the executable starting address
31199 @smallexample
31200 $ objdump --file-header main.exe
31201 @end smallexample
31203 The starting address is reported on the last line. For example:
31205 @smallexample
31206 main.exe:     file format pei-i386
31207 architecture: i386, flags 0x0000010a:
31208 EXEC_P, HAS_DEBUG, D_PAGED
31209 start address 0x00401010
31210 @end smallexample
31212 @item
31213 Launch the debugger on the executable.
31215 @smallexample
31216 $ gdb main.exe
31217 @end smallexample
31219 @item
31220 Set a breakpoint at the starting address, and launch the program.
31222 @smallexample
31223 $ (gdb) break *0x00401010
31224 $ (gdb) run
31225 @end smallexample
31227 The program will stop at the given address.
31229 @item
31230 Set a breakpoint on a DLL subroutine.
31232 @smallexample
31233 (gdb) break ada_dll.adb:45
31234 @end smallexample
31236 Or if you want to break using a symbol on the DLL, you need first to
31237 select the Ada language (language used by the DLL).
31239 @smallexample
31240 (gdb) set language ada
31241 (gdb) break ada_dll
31242 @end smallexample
31244 @item
31245 Continue the program.
31247 @smallexample
31248 (gdb) cont
31249 @end smallexample
31251 @noindent
31252 This will run the program until it reaches the breakpoint that has been
31253 set. From that point you can use the standard way to debug a program
31254 as described in (@pxref{Running and Debugging Ada Programs}).
31256 @end enumerate
31258 @noindent
31259 It is also possible to debug the DLL by attaching to a running process.
31261 @node Attaching to a Running Process
31262 @subsubsection Attaching to a Running Process
31263 @cindex DLL debugging, attach to process
31265 @noindent
31266 With @code{GDB} it is always possible to debug a running process by
31267 attaching to it. It is possible to debug a DLL this way. The limitation
31268 of this approach is that the DLL must run long enough to perform the
31269 attach operation. It may be useful for instance to insert a time wasting
31270 loop in the code of the DLL to meet this criterion.
31272 @enumerate 1
31274 @item Launch the main program @file{main.exe}.
31276 @smallexample
31277 $ main
31278 @end smallexample
31280 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31281 that the process PID for @file{main.exe} is 208.
31283 @item Launch gdb.
31285 @smallexample
31286 $ gdb
31287 @end smallexample
31289 @item Attach to the running process to be debugged.
31291 @smallexample
31292 (gdb) attach 208
31293 @end smallexample
31295 @item Load the process debugging information.
31297 @smallexample
31298 (gdb) symbol-file main.exe
31299 @end smallexample
31301 @item Break somewhere in the DLL.
31303 @smallexample
31304 (gdb) break ada_dll
31305 @end smallexample
31307 @item Continue process execution.
31309 @smallexample
31310 (gdb) cont
31311 @end smallexample
31313 @end enumerate
31315 @noindent
31316 This last step will resume the process execution, and stop at
31317 the breakpoint we have set. From there you can use the standard
31318 approach to debug a program as described in
31319 (@pxref{Running and Debugging Ada Programs}).
31321 @node Setting Stack Size from gnatlink
31322 @section Setting Stack Size from @command{gnatlink}
31324 @noindent
31325 It is possible to specify the program stack size at link time. On modern
31326 versions of Windows, starting with XP, this is mostly useful to set the size of
31327 the main stack (environment task). The other task stacks are set with pragma
31328 Storage_Size or with the @command{gnatbind -d} command.
31330 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31331 reserve size of individual tasks, the link-time stack size applies to all
31332 tasks, and pragma Storage_Size has no effect.
31333 In particular, Stack Overflow checks are made against this
31334 link-time specified size.
31336 This setting can be done with
31337 @command{gnatlink} using either:
31339 @itemize @bullet
31341 @item using @option{-Xlinker} linker option
31343 @smallexample
31344 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31345 @end smallexample
31347 This sets the stack reserve size to 0x10000 bytes and the stack commit
31348 size to 0x1000 bytes.
31350 @item using @option{-Wl} linker option
31352 @smallexample
31353 $ gnatlink hello -Wl,--stack=0x1000000
31354 @end smallexample
31356 This sets the stack reserve size to 0x1000000 bytes. Note that with
31357 @option{-Wl} option it is not possible to set the stack commit size
31358 because the coma is a separator for this option.
31360 @end itemize
31362 @node Setting Heap Size from gnatlink
31363 @section Setting Heap Size from @command{gnatlink}
31365 @noindent
31366 Under Windows systems, it is possible to specify the program heap size from
31367 @command{gnatlink} using either:
31369 @itemize @bullet
31371 @item using @option{-Xlinker} linker option
31373 @smallexample
31374 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31375 @end smallexample
31377 This sets the heap reserve size to 0x10000 bytes and the heap commit
31378 size to 0x1000 bytes.
31380 @item using @option{-Wl} linker option
31382 @smallexample
31383 $ gnatlink hello -Wl,--heap=0x1000000
31384 @end smallexample
31386 This sets the heap reserve size to 0x1000000 bytes. Note that with
31387 @option{-Wl} option it is not possible to set the heap commit size
31388 because the coma is a separator for this option.
31390 @end itemize
31392 @node Mac OS Topics
31393 @appendix Mac OS Topics
31394 @cindex OS X
31396 @noindent
31397 This chapter describes topics that are specific to Apple's OS X
31398 platform.
31400 @menu
31401 * Codesigning the Debugger::
31402 @end menu
31404 @node Codesigning the Debugger
31405 @section Codesigning the Debugger
31407 @noindent
31408 The Darwin Kernel requires the debugger to have special permissions
31409 before it is allowed to control other processes. These permissions
31410 are granted by codesigning the GDB executable. Without these
31411 permissions, the debugger will report error messages such as:
31413 @smallexample
31414 Starting program: /x/y/foo
31415 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31416  (please check gdb is codesigned - see taskgated(8))
31417 @end smallexample
31419 Codesigning requires a certificate.  The following procedure explains
31420 how to create one:
31422 @itemize @bullet
31423 @item Start the Keychain Access application (in
31424 /Applications/Utilities/Keychain Access.app)
31426 @item Select the Keychain Access -> Certificate Assistant ->
31427 Create a Certificate... menu
31429 @item Then:
31431 @itemize @bullet
31432 @item Choose a name for the new certificate (this procedure will use
31433 "gdb-cert" as an example)
31435 @item Set "Identity Type" to "Self Signed Root"
31437 @item Set "Certificate Type" to "Code Signing"
31439 @item Activate the "Let me override defaults" option
31441 @end itemize
31443 @item Click several times on "Continue" until the "Specify a Location
31444 For The Certificate" screen appears, then set "Keychain" to "System"
31446 @item Click on "Continue" until the certificate is created
31448 @item Finally, in the view, double-click on the new certificate,
31449 and set "When using this certificate" to "Always Trust"
31451 @item Exit the Keychain Access application and restart the computer
31452 (this is unfortunately required)
31454 @end itemize
31456 Once a certificate has been created, the debugger can be codesigned
31457 as follow. In a Terminal, run the following command...
31459 @smallexample
31460 codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
31461 @end smallexample
31463 ... where "gdb-cert" should be replaced by the actual certificate
31464 name chosen above, and <gnat_install_prefix> should be replaced by
31465 the location where you installed GNAT.
31467 @c **********************************
31468 @c * GNU Free Documentation License *
31469 @c **********************************
31470 @include fdl.texi
31471 @c GNU Free Documentation License
31473 @node Index
31474 @unnumbered Index
31476 @printindex cp
31478 @contents
31479 @c Put table of contents at end, otherwise it precedes the "title page" in
31480 @c the .txt version
31481 @c Edit the pdf file to move the contents to the beginning, after the title
31482 @c page
31484 @bye