PR ipa/64481
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob17f2414ea4923642cb8abe828fc15c66b04bc3c3
2 \input texinfo   @c -*-texinfo-*-
3 @c %**start of header
5 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c                                                                            o
7 @c                            GNAT DOCUMENTATION                              o
8 @c                                                                            o
9 @c                             G N A T _ U G N                                o
10 @c                                                                            o
11 @c           Copyright (C) 1992-2015, Free Software Foundation, Inc.          o
12 @c                                                                            o
13 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
15 @setfilename gnat_ugn.info
17 @copying
18 Copyright @copyright{} 1995-2015 Free Software Foundation,
19 Inc.
21 Permission is granted to copy, distribute and/or modify this document
22 under the terms of the GNU Free Documentation License, Version 1.3 or
23 any later version published by the Free Software Foundation; with no
24 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
25 Texts.  A copy of the license is included in the section entitled
26 ``GNU Free Documentation License''.
27 @end copying
29 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
31 @c                           GNAT_UGN Style Guide
33 @c  1. Always put a @noindent on the line before the first paragraph
34 @c     after any of these commands:
36 @c          @chapter
37 @c          @section
38 @c          @subsection
39 @c          @subsubsection
40 @c          @subsubsubsection
42 @c          @end smallexample
43 @c          @end itemize
44 @c          @end enumerate
46 @c  2. DO NOT use @example. Use @smallexample instead.
47 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
48 @c        context.  These can interfere with the readability of the texi
49 @c        source file.  Instead, use one of the following annotated
50 @c        @smallexample commands, and preprocess the texi file with the
51 @c        ada2texi tool (which generates appropriate highlighting):
52 @c        @smallexample @c ada
53 @c        @smallexample @c adanocomment
54 @c        @smallexample @c projectfile
55 @c     b) The "@c ada" markup will result in boldface for reserved words
56 @c        and italics for comments
57 @c     c) The "@c adanocomment" markup will result only in boldface for
58 @c        reserved words (comments are left alone)
59 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
60 @c        of reserved words include the new reserved words for project files
62 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
63 @c     command must be preceded by two empty lines
65 @c  4. The @item command should be on a line of its own if it is in an
66 @c     @itemize or @enumerate command.
68 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
69 @c     or "ali".
71 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
72 @c     cause the document build to fail.
74 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
75 @c     This command inhibits page breaks, so long examples in a @cartouche can
76 @c     lead to large, ugly patches of empty space on a page.
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
80 @set NOW January 2007
81 @c This flag is used where the text refers to conditions that exist when the
82 @c text was entered into the document but which may change over time.
83 @c Update the setting for the flag, and (if necessary) the text surrounding,
84 @c the references to the flag, on future doc revisions:
85 @c search for @value{NOW}.
87 @set FSFEDITION
88 @set EDITION GNAT
90 @set PLATFORM
92 @c @ovar(ARG)
93 @c ----------
94 @c The ARG is an optional argument.  To be used for macro arguments in
95 @c their documentation (@defmac).
96 @macro ovar{varname}
97 @r{[}@var{\varname\}@r{]}@c
98 @end macro
99 @c Status as of November 2009:
100 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
101 @c differently, and faulty output is produced by one or the other
102 @c depending on whether the "@c" is present or absent.
103 @c As a result, the @ovar macro is not used, and all invocations
104 @c of the @ovar macro have been expanded inline.
107 @settitle @value{EDITION} User's Guide
108 @dircategory GNU Ada tools
109 @direntry
110 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
111 @end direntry
113 @include gcc-common.texi
115 @setchapternewpage odd
116 @syncodeindex fn cp
117 @c %**end of header
119 @titlepage
120 @title @value{EDITION} User's Guide
122 @sp 2
124 @subtitle GNAT, The GNU Ada Development Environment
125 @versionsubtitle
126 @author AdaCore
128 @page
129 @vskip 0pt plus 1filll
131 @insertcopying
133 @end titlepage
135 @ifnottex
136 @node Top, About This Guide, (dir), (dir)
137 @top @value{EDITION} User's Guide
139 @noindent
140 @value{EDITION} User's Guide @value{PLATFORM}
142 @noindent
143 GNAT, The GNU Ada Development Environment@*
144 GCC version @value{version-GCC}@*
146 @noindent
147 AdaCore@*
149 @menu
150 * About This Guide::
151 * Getting Started with GNAT::
152 * The GNAT Compilation Model::
153 * Compiling with gcc::
154 * Binding with gnatbind::
155 * Linking with gnatlink::
156 * The GNAT Make Program gnatmake::
157 * Improving Performance::
158 * Renaming Files with gnatchop::
159 * Configuration Pragmas::
160 * Handling Arbitrary File Naming Conventions with gnatname::
161 * GNAT Project Manager::
162 * Tools Supporting Project Files::
163 * The Cross-Referencing Tools gnatxref and gnatfind::
164 @ifclear FSFEDITION
165 * The GNAT Pretty-Printer gnatpp::
166 * The Ada-to-XML converter gnat2xml::
167 * The GNAT Metrics Tool gnatmetric::
168 @end ifclear
169 * File Name Krunching with gnatkr::
170 * Preprocessing with gnatprep::
171 * The GNAT Library Browser gnatls::
172 * Cleaning Up with gnatclean::
173 * GNAT and Libraries::
174 * Using the GNU make Utility::
175 * Memory Management Issues::
176 * Stack Related Facilities::
177 @ifclear FSFEDITION
178 * Verifying Properties with gnatcheck::
179 * Creating Sample Bodies with gnatstub::
180 * Creating Unit Tests with gnattest::
181 @end ifclear
182 * Performing Dimensionality Analysis in GNAT::
183 * Generating Ada Bindings for C and C++ headers::
184 * Other Utility Programs::
185 * Code Coverage and Profiling::
186 * Running and Debugging Ada Programs::
187 * Platform-Specific Information for the Run-Time Libraries::
188 * Example of Binder Output File::
189 * Elaboration Order Handling in GNAT::
190 * Overflow Check Handling in GNAT::
191 * Conditional Compilation::
192 * Inline Assembler::
193 * Writing Portable Fixed-Point Declarations::
194 * Compatibility and Porting Guide::
195 * Microsoft Windows Topics::
196 * Mac OS Topics::
197 * GNU Free Documentation License::
198 * Index::
199 @end menu
200 @end ifnottex
202 @node About This Guide
203 @unnumbered About This Guide
205 @noindent
206 This guide describes the use of @value{EDITION},
207 a compiler and software development
208 toolset for the full Ada programming language.
209 It documents the features of the compiler and tools, and explains
210 how to use them to build Ada applications.
212 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
213 invoked in Ada 83 compatibility mode.
214 By default, @value{EDITION} assumes Ada 2012, but you can override with a
215 compiler switch (@pxref{Compiling Different Versions of Ada})
216 to explicitly specify the language version.
217 Throughout this manual, references to ``Ada'' without a year suffix
218 apply to all Ada 95/2005/2012 versions of the language.
220 @ifclear FSFEDITION
221 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
222 ``GNAT'' in the remainder of this document.
223 @end ifclear
226 @menu
227 * What This Guide Contains::
228 * What You Should Know before Reading This Guide::
229 * Related Information::
230 * Conventions::
231 @end menu
233 @node What This Guide Contains
234 @unnumberedsec What This Guide Contains
236 @noindent
237 This guide contains the following chapters:
238 @itemize @bullet
240 @item
241 @ref{Getting Started with GNAT}, describes how to get started compiling
242 and running Ada programs with the GNAT Ada programming environment.
243 @item
244 @ref{The GNAT Compilation Model}, describes the compilation model used
245 by GNAT.
247 @item
248 @ref{Compiling with gcc}, describes how to compile
249 Ada programs with @command{gcc}, the Ada compiler.
251 @item
252 @ref{Binding with gnatbind}, describes how to
253 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
254 utility.
256 @item
257 @ref{Linking with gnatlink},
258 describes @command{gnatlink}, a
259 program that provides for linking using the GNAT run-time library to
260 construct a program. @command{gnatlink} can also incorporate foreign language
261 object units into the executable.
263 @item
264 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
265 utility that automatically determines the set of sources
266 needed by an Ada compilation unit, and executes the necessary compilations
267 binding and link.
269 @item
270 @ref{Improving Performance}, shows various techniques for making your
271 Ada program run faster or take less space and describes the effect of
272 the compiler's optimization switch.
273 It also describes
274 @ifclear FSFEDITION
275 the @command{gnatelim} tool and
276 @end ifclear
277 unused subprogram/data elimination.
279 @item
280 @ref{Renaming Files with gnatchop}, describes
281 @code{gnatchop}, a utility that allows you to preprocess a file that
282 contains Ada source code, and split it into one or more new files, one
283 for each compilation unit.
285 @item
286 @ref{Configuration Pragmas}, describes the configuration pragmas
287 handled by GNAT.
289 @item
290 @ref{Handling Arbitrary File Naming Conventions with gnatname},
291 shows how to override the default GNAT file naming conventions,
292 either for an individual unit or globally.
294 @item
295 @ref{GNAT Project Manager}, describes how to use project files
296 to organize large projects.
298 @item
299 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
300 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
301 way to navigate through sources.
303 @ifclear FSFEDITION
304 @item
305 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
306 version of an Ada source file with control over casing, indentation,
307 comment placement, and other elements of program presentation style.
308 @end ifclear
310 @ifclear FSFEDITION
311 @item
312 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
313 source code into XML.
314 @end ifclear
316 @ifclear FSFEDITION
317 @item
318 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
319 metrics for an Ada source file, such as the number of types and subprograms,
320 and assorted complexity measures.
321 @end ifclear
323 @item
324 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
325 file name krunching utility, used to handle shortened
326 file names on operating systems with a limit on the length of names.
328 @item
329 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
330 preprocessor utility that allows a single source file to be used to
331 generate multiple or parameterized source files by means of macro
332 substitution.
334 @item
335 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
336 utility that displays information about compiled units, including dependences
337 on the corresponding sources files, and consistency of compilations.
339 @item
340 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
341 to delete files that are produced by the compiler, binder and linker.
343 @item
344 @ref{GNAT and Libraries}, describes the process of creating and using
345 Libraries with GNAT. It also describes how to recompile the GNAT run-time
346 library.
348 @item
349 @ref{Using the GNU make Utility}, describes some techniques for using
350 the GNAT toolset in Makefiles.
352 @item
353 @ref{Memory Management Issues}, describes some useful predefined storage pools
354 and in particular the GNAT Debug Pool facility, which helps detect incorrect
355 memory references.
356 @ifclear FSFEDITION
357 It also describes @command{gnatmem}, a utility that monitors dynamic
358 allocation and deallocation and helps detect ``memory leaks''.
359 @end ifclear
361 @item
362 @ref{Stack Related Facilities}, describes some useful tools associated with
363 stack checking and analysis.
365 @ifclear FSFEDITION
366 @item
367 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
368 a utility that checks Ada code against a set of rules.
370 @item
371 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
372 a utility that generates empty but compilable bodies for library units.
373 @end ifclear
375 @ifclear FSFEDITION
376 @item
377 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
378 a utility that generates unit testing templates for library units.
379 @end ifclear
381 @item
382 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
383 facilities used in GNAT to declare dimensioned objects, and to verify that
384 uses of these objects are consistent with their given physical dimensions
385 (so that meters cannot be assigned to kilograms, and so on).
387 @item
388 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
389 generate automatically Ada bindings from C and C++ headers.
391 @item
392 @ref{Other Utility Programs}, discusses several other GNAT utilities,
393 including @code{gnathtml}.
395 @item
396 @ref{Code Coverage and Profiling}, describes how to perform a structural
397 coverage and profile the execution of Ada programs.
399 @item
400 @ref{Running and Debugging Ada Programs}, describes how to run and debug
401 Ada programs.
404 @item
405 @ref{Platform-Specific Information for the Run-Time Libraries},
406 describes the various run-time
407 libraries supported by GNAT on various platforms and explains how to
408 choose a particular library.
410 @item
411 @ref{Example of Binder Output File}, shows the source code for the binder
412 output file for a sample program.
414 @item
415 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
416 you deal with elaboration order issues.
418 @item
419 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
420 you deal with arithmetic overflow issues.
422 @item
423 @ref{Conditional Compilation}, describes how to model conditional compilation,
424 both with Ada in general and with GNAT facilities in particular.
426 @item
427 @ref{Inline Assembler}, shows how to use the inline assembly facility
428 in an Ada program.
430 @item
431 @ref{Writing Portable Fixed-Point Declarations}, gives some guidance on
432 defining portable fixed-point types.
434 @item
435 @ref{Compatibility and Porting Guide}, contains sections on compatibility
436 of GNAT with other Ada development environments (including Ada 83 systems),
437 to assist in porting code from those environments.
439 @item
440 @ref{Microsoft Windows Topics}, presents information relevant to the
441 Microsoft Windows platform.
443 @item
444 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
445 platform.
446 @end itemize
448 @c *************************************************
449 @node What You Should Know before Reading This Guide
450 @c *************************************************
451 @unnumberedsec What You Should Know before Reading This Guide
453 @cindex Ada 95 Language Reference Manual
454 @cindex Ada 2005 Language Reference Manual
455 @noindent
456 This guide assumes a basic familiarity with the Ada 95 language, as
457 described in the International Standard ANSI/ISO/IEC-8652:1995, January
458 1995.
459 It does not require knowledge of the new features introduced by Ada 2005,
460 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
461 and Amendment 1).
462 Both reference manuals are included in the GNAT documentation
463 package.
465 @node Related Information
466 @unnumberedsec Related Information
468 @noindent
469 For further information about related tools, refer to the following
470 documents:
472 @itemize @bullet
473 @item
474 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
475 Reference Manual}, which contains all reference material for the GNAT
476 implementation of Ada.
478 @item
479 @cite{Using the GNAT Programming Studio}, which describes the GPS
480 Integrated Development Environment.
482 @item
483 @cite{GNAT Programming Studio Tutorial}, which introduces the
484 main GPS features through examples.
486 @item
487 @cite{Ada 95 Reference Manual}, which contains reference
488 material for the Ada 95 programming language.
490 @item
491 @cite{Ada 2005 Reference Manual}, which contains reference
492 material for the Ada 2005 programming language.
494 @item
495 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
496 for all details on the use of the GNU source-level debugger.
498 @item
499 @xref{Top,, The extensible self-documenting text editor, emacs,
500 GNU Emacs Manual},
501 for full information on the extensible editor and programming
502 environment Emacs.
504 @end itemize
506 @c **************
507 @node Conventions
508 @unnumberedsec Conventions
509 @cindex Conventions
510 @cindex Typographical conventions
512 @noindent
513 Following are examples of the typographical and graphic conventions used
514 in this guide:
516 @itemize @bullet
517 @item
518 @code{Functions}, @command{utility program names}, @code{standard names},
519 and @code{classes}.
521 @item
522 @option{Option flags}
524 @item
525 @file{File names}, @samp{button names}, and @samp{field names}.
527 @item
528 @code{Variables}, @env{environment variables}, and @var{metasyntactic
529 variables}.
531 @item
532 @emph{Emphasis}.
534 @item
535 @r{[}optional information or parameters@r{]}
537 @item
538 Examples are described by text
539 @smallexample
540 and then shown this way.
541 @end smallexample
542 @end itemize
544 @noindent
545 Commands that are entered by the user are preceded in this manual by the
546 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
547 uses this sequence as a prompt, then the commands will appear exactly as
548 you see them in the manual. If your system uses some other prompt, then
549 the command will appear with the @code{$} replaced by whatever prompt
550 character you are using.
552 Full file names are shown with the ``@code{/}'' character
553 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
554 If you are using GNAT on a Windows platform, please note that
555 the ``@code{\}'' character should be used instead.
557 @c ****************************
558 @node Getting Started with GNAT
559 @chapter Getting Started with GNAT
561 @noindent
562 This chapter describes some simple ways of using GNAT to build
563 executable Ada programs.
564 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
565 show how to use the command line environment.
566 @ref{Introduction to GPS}, provides a brief
567 introduction to the GNAT Programming Studio, a visually-oriented
568 Integrated Development Environment for GNAT.
569 GPS offers a graphical ``look and feel'', support for development in
570 other programming languages, comprehensive browsing features, and
571 many other capabilities.
572 For information on GPS please refer to
573 @cite{Using the GNAT Programming Studio}.
575 @menu
576 * Running GNAT::
577 * Running a Simple Ada Program::
578 * Running a Program with Multiple Units::
579 * Using the gnatmake Utility::
580 * Introduction to GPS::
581 @end menu
583 @node Running GNAT
584 @section Running GNAT
586 @noindent
587 Three steps are needed to create an executable file from an Ada source
588 file:
590 @enumerate
591 @item
592 The source file(s) must be compiled.
593 @item
594 The file(s) must be bound using the GNAT binder.
595 @item
596 All appropriate object files must be linked to produce an executable.
597 @end enumerate
599 @noindent
600 All three steps are most commonly handled by using the @command{gnatmake}
601 utility program that, given the name of the main program, automatically
602 performs the necessary compilation, binding and linking steps.
604 @node Running a Simple Ada Program
605 @section Running a Simple Ada Program
607 @noindent
608 Any text editor may be used to prepare an Ada program.
609 (If @code{Emacs} is
610 used, the optional Ada mode may be helpful in laying out the program.)
612 program text is a normal text file. We will assume in our initial
613 example that you have used your editor to prepare the following
614 standard format text file:
616 @smallexample @c ada
617 @cartouche
618 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
619 @b{procedure} Hello @b{is}
620 @b{begin}
621    Put_Line ("Hello WORLD!");
622 @b{end} Hello;
623 @end cartouche
624 @end smallexample
626 @noindent
627 This file should be named @file{hello.adb}.
628 With the normal default file naming conventions, GNAT requires
629 that each file
630 contain a single compilation unit whose file name is the
631 unit name,
632 with periods replaced by hyphens; the
633 extension is @file{ads} for a
634 spec and @file{adb} for a body.
635 You can override this default file naming convention by use of the
636 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
637 Alternatively, if you want to rename your files according to this default
638 convention, which is probably more convenient if you will be using GNAT
639 for all your compilations, then the @code{gnatchop} utility
640 can be used to generate correctly-named source files
641 (@pxref{Renaming Files with gnatchop}).
643 You can compile the program using the following command (@code{$} is used
644 as the command prompt in the examples in this document):
646 @smallexample
647 $ gcc -c hello.adb
648 @end smallexample
650 @noindent
651 @command{gcc} is the command used to run the compiler. This compiler is
652 capable of compiling programs in several languages, including Ada and
653 C. It assumes that you have given it an Ada program if the file extension is
654 either @file{.ads} or @file{.adb}, and it will then call
655 the GNAT compiler to compile the specified file.
657 The @option{-c} switch is required. It tells @command{gcc} to only do a
658 compilation. (For C programs, @command{gcc} can also do linking, but this
659 capability is not used directly for Ada programs, so the @option{-c}
660 switch must always be present.)
662 This compile command generates a file
663 @file{hello.o}, which is the object
664 file corresponding to your Ada program. It also generates
665 an ``Ada Library Information'' file @file{hello.ali},
666 which contains additional information used to check
667 that an Ada program is consistent.
668 To build an executable file,
669 use @code{gnatbind} to bind the program
670 and @command{gnatlink} to link it. The
671 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
672 @file{ALI} file, but the default extension of @file{.ali} can
673 be omitted. This means that in the most common case, the argument
674 is simply the name of the main program:
676 @smallexample
677 $ gnatbind hello
678 $ gnatlink hello
679 @end smallexample
681 @noindent
682 A simpler method of carrying out these steps is to use
683 @command{gnatmake},
684 a master program that invokes all the required
685 compilation, binding and linking tools in the correct order. In particular,
686 @command{gnatmake} automatically recompiles any sources that have been
687 modified since they were last compiled, or sources that depend
688 on such modified sources, so that ``version skew'' is avoided.
689 @cindex Version skew (avoided by @command{gnatmake})
691 @smallexample
692 $ gnatmake hello.adb
693 @end smallexample
695 @noindent
696 The result is an executable program called @file{hello}, which can be
697 run by entering:
699 @smallexample
700 $ hello
701 @end smallexample
703 @noindent
704 assuming that the current directory is on the search path
705 for executable programs.
707 @noindent
708 and, if all has gone well, you will see
710 @smallexample
711 Hello WORLD!
712 @end smallexample
714 @noindent
715 appear in response to this command.
717 @c ****************************************
718 @node Running a Program with Multiple Units
719 @section Running a Program with Multiple Units
721 @noindent
722 Consider a slightly more complicated example that has three files: a
723 main program, and the spec and body of a package:
725 @smallexample @c ada
726 @cartouche
727 @group
728 @b{package} Greetings @b{is}
729    @b{procedure} Hello;
730    @b{procedure} Goodbye;
731 @b{end} Greetings;
733 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
734 @b{package} @b{body} Greetings @b{is}
735    @b{procedure} Hello @b{is}
736    @b{begin}
737       Put_Line ("Hello WORLD!");
738    @b{end} Hello;
740    @b{procedure} Goodbye @b{is}
741    @b{begin}
742       Put_Line ("Goodbye WORLD!");
743    @b{end} Goodbye;
744 @b{end} Greetings;
745 @end group
747 @group
748 @b{with} Greetings;
749 @b{procedure} Gmain @b{is}
750 @b{begin}
751    Greetings.Hello;
752    Greetings.Goodbye;
753 @b{end} Gmain;
754 @end group
755 @end cartouche
756 @end smallexample
758 @noindent
759 Following the one-unit-per-file rule, place this program in the
760 following three separate files:
762 @table @file
763 @item greetings.ads
764 spec of package @code{Greetings}
766 @item greetings.adb
767 body of package @code{Greetings}
769 @item gmain.adb
770 body of main program
771 @end table
773 @noindent
774 To build an executable version of
775 this program, we could use four separate steps to compile, bind, and link
776 the program, as follows:
778 @smallexample
779 $ gcc -c gmain.adb
780 $ gcc -c greetings.adb
781 $ gnatbind gmain
782 $ gnatlink gmain
783 @end smallexample
785 @noindent
786 Note that there is no required order of compilation when using GNAT.
787 In particular it is perfectly fine to compile the main program first.
788 Also, it is not necessary to compile package specs in the case where
789 there is an accompanying body; you only need to compile the body. If you want
790 to submit these files to the compiler for semantic checking and not code
791 generation, then use the
792 @option{-gnatc} switch:
794 @smallexample
795 $ gcc -c greetings.ads -gnatc
796 @end smallexample
798 @noindent
799 Although the compilation can be done in separate steps as in the
800 above example, in practice it is almost always more convenient
801 to use the @command{gnatmake} tool. All you need to know in this case
802 is the name of the main program's source file. The effect of the above four
803 commands can be achieved with a single one:
805 @smallexample
806 $ gnatmake gmain.adb
807 @end smallexample
809 @noindent
810 In the next section we discuss the advantages of using @command{gnatmake} in
811 more detail.
813 @c *****************************
814 @node Using the gnatmake Utility
815 @section Using the @command{gnatmake} Utility
817 @noindent
818 If you work on a program by compiling single components at a time using
819 @command{gcc}, you typically keep track of the units you modify. In order to
820 build a consistent system, you compile not only these units, but also any
821 units that depend on the units you have modified.
822 For example, in the preceding case,
823 if you edit @file{gmain.adb}, you only need to recompile that file. But if
824 you edit @file{greetings.ads}, you must recompile both
825 @file{greetings.adb} and @file{gmain.adb}, because both files contain
826 units that depend on @file{greetings.ads}.
828 @code{gnatbind} will warn you if you forget one of these compilation
829 steps, so that it is impossible to generate an inconsistent program as a
830 result of forgetting to do a compilation. Nevertheless it is tedious and
831 error-prone to keep track of dependencies among units.
832 One approach to handle the dependency-bookkeeping is to use a
833 makefile. However, makefiles present maintenance problems of their own:
834 if the dependencies change as you change the program, you must make
835 sure that the makefile is kept up-to-date manually, which is also an
836 error-prone process.
838 The @command{gnatmake} utility takes care of these details automatically.
839 Invoke it using either one of the following forms:
841 @smallexample
842 $ gnatmake gmain.adb
843 $ gnatmake gmain
844 @end smallexample
846 @noindent
847 The argument is the name of the file containing the main program;
848 you may omit the extension. @command{gnatmake}
849 examines the environment, automatically recompiles any files that need
850 recompiling, and binds and links the resulting set of object files,
851 generating the executable file, @file{gmain}.
852 In a large program, it
853 can be extremely helpful to use @command{gnatmake}, because working out by hand
854 what needs to be recompiled can be difficult.
856 Note that @command{gnatmake}
857 takes into account all the Ada rules that
858 establish dependencies among units. These include dependencies that result
859 from inlining subprogram bodies, and from
860 generic instantiation. Unlike some other
861 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
862 found by the compiler on a previous compilation, which may possibly
863 be wrong when sources change. @command{gnatmake} determines the exact set of
864 dependencies from scratch each time it is run.
867 @node Introduction to GPS
868 @section Introduction to GPS
869 @cindex GPS (GNAT Programming Studio)
870 @cindex GNAT Programming Studio (GPS)
871 @noindent
872 Although the command line interface (@command{gnatmake}, etc.) alone
873 is sufficient, a graphical Interactive Development
874 Environment can make it easier for you to compose, navigate, and debug
875 programs.  This section describes the main features of GPS
876 (``GNAT Programming Studio''), the GNAT graphical IDE.
877 You will see how to use GPS to build and debug an executable, and
878 you will also learn some of the basics of the GNAT ``project'' facility.
880 GPS enables you to do much more than is presented here;
881 e.g., you can produce a call graph, interface to a third-party
882 Version Control System, and inspect the generated assembly language
883 for a program.
884 Indeed, GPS also supports languages other than Ada.
885 Such additional information, and an explanation of all of the GPS menu
886 items. may be found in the on-line help, which includes
887 a user's guide and a tutorial (these are also accessible from the GNAT
888 startup menu).
890 @menu
891 * Building a New Program with GPS::
892 * Simple Debugging with GPS::
893 @end menu
895 @node Building a New Program with GPS
896 @subsection Building a New Program with GPS
897 @noindent
898 GPS invokes the GNAT compilation tools using information
899 contained in a @emph{project} (also known as a @emph{project file}):
900 a collection of properties such
901 as source directories, identities of main subprograms, tool switches, etc.,
902 and their associated values.
903 See @ref{GNAT Project Manager} for details.
904 In order to run GPS, you will need to either create a new project
905 or else open an existing one.
907 This section will explain how you can use GPS to create a project,
908 to associate Ada source files with a project, and to build and run
909 programs.
911 @enumerate
912 @item @emph{Creating a project}
914 Invoke GPS, either from the command line or the platform's IDE.
915 After it starts, GPS will display a ``Welcome'' screen with three
916 radio buttons:
918 @itemize @bullet
919 @item
920 @code{Start with default project in directory}
922 @item
923 @code{Create new project with wizard}
925 @item
926 @code{Open existing project}
927 @end itemize
929 @noindent
930 Select @code{Create new project with wizard} and press @code{OK}.
931 A new window will appear.  In the text box labeled with
932 @code{Enter the name of the project to create}, type @file{sample}
933 as the project name.
934 In the next box, browse to choose the directory in which you
935 would like to create the project file.
936 After selecting an appropriate directory, press @code{Forward}.
938 A window will appear with the title
939 @code{Version Control System Configuration}.
940 Simply press @code{Forward}.
942 A window will appear with the title
943 @code{Please select the source directories for this project}.
944 The directory that you specified for the project file will be selected
945 by default as the one to use for sources; simply press @code{Forward}.
947 A window will appear with the title
948 @code{Please select the build directory for this project}.
949 The directory that you specified for the project file will be selected
950 by default for object files and executables;
951 simply press @code{Forward}.
953 A window will appear with the title
954 @code{Please select the main units for this project}.
955 You will supply this information later, after creating the source file.
956 Simply press @code{Forward} for now.
958 A window will appear with the title
959 @code{Please select the switches to build the project}.
960 Press @code{Apply}.  This will create a project file named
961 @file{sample.prj} in the directory that you had specified.
963 @item @emph{Creating and saving the source file}
965 After you create the new project, a GPS window will appear, which is
966 partitioned into two main sections:
968 @itemize @bullet
969 @item
970 A @emph{Workspace area}, initially greyed out, which you will use for
971 creating and editing source files
973 @item
974 Directly below, a @emph{Messages area}, which initially displays a
975 ``Welcome'' message.
976 (If the Messages area is not visible, drag its border upward to expand it.)
977 @end itemize
979 @noindent
980 Select @code{File} on the menu bar, and then the @code{New} command.
981 The Workspace area will become white, and you can now
982 enter the source program explicitly.
983 Type the following text
985 @smallexample @c ada
986 @group
987 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
988 @b{procedure} Hello @b{is}
989 @b{begin}
990   Put_Line("Hello from GPS!");
991 @b{end} Hello;
992 @end group
993 @end smallexample
995 @noindent
996 Select @code{File}, then @code{Save As}, and enter the source file name
997 @file{hello.adb}.
998 The file will be saved in the same directory you specified as the
999 location of the default project file.
1001 @item @emph{Updating the project file}
1003 You need to add the new source file to the project.
1004 To do this, select
1005 the @code{Project} menu and then @code{Edit project properties}.
1006 Click the @code{Main files} tab on the left, and then the
1007 @code{Add} button.
1008 Choose @file{hello.adb} from the list, and press @code{Open}.
1009 The project settings window will reflect this action.
1010 Click @code{OK}.
1012 @item @emph{Building and running the program}
1014 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1015 and select @file{hello.adb}.
1016 The Messages window will display the resulting invocations of @command{gcc},
1017 @command{gnatbind}, and @command{gnatlink}
1018 (reflecting the default switch settings from the
1019 project file that you created) and then a ``successful compilation/build''
1020 message.
1022 To run the program, choose the @code{Build} menu, then @code{Run}, and
1023 select @command{hello}.
1024 An @emph{Arguments Selection} window will appear.
1025 There are no command line arguments, so just click @code{OK}.
1027 The Messages window will now display the program's output (the string
1028 @code{Hello from GPS}), and at the bottom of the GPS window a status
1029 update is displayed (@code{Run: hello}).
1030 Close the GPS window (or select @code{File}, then @code{Exit}) to
1031 terminate this GPS session.
1032 @end enumerate
1034 @node Simple Debugging with GPS
1035 @subsection Simple Debugging with GPS
1036 @noindent
1037 This section illustrates basic debugging techniques (setting breakpoints,
1038 examining/modifying variables, single stepping).
1040 @enumerate
1041 @item @emph{Opening a project}
1043 Start GPS and select @code{Open existing project}; browse to
1044 specify the project file @file{sample.prj} that you had created in the
1045 earlier example.
1047 @item @emph{Creating a source file}
1049 Select @code{File}, then @code{New}, and type in the following program:
1051 @smallexample @c ada
1052 @group
1053 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
1054 @b{procedure} Example @b{is}
1055    Line : String (1..80);
1056    N    : Natural;
1057 @b{begin}
1058    Put_Line("Type a line of text at each prompt; an empty line to exit");
1059    @b{loop}
1060       Put(": ");
1061       Get_Line (Line, N);
1062       Put_Line (Line (1..N) );
1063       @b{exit} @b{when} N=0;
1064    @b{end} @b{loop};
1065 @b{end} Example;
1066 @end group
1067 @end smallexample
1069 @noindent
1070 Select @code{File}, then @code{Save as}, and enter the file name
1071 @file{example.adb}.
1073 @item @emph{Updating the project file}
1075 Add @code{Example} as a new main unit for the project:
1076 @enumerate a
1077 @item
1078 Select @code{Project}, then @code{Edit Project Properties}.
1080 @item
1081 Select the @code{Main files} tab, click @code{Add}, then
1082 select the file @file{example.adb} from the list, and
1083 click @code{Open}.
1084 You will see the file name appear in the list of main units
1086 @item
1087 Click @code{OK}
1088 @end enumerate
1090 @item @emph{Building/running the executable}
1092 To build the executable
1093 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1095 Run the program to see its effect (in the Messages area).
1096 Each line that you enter is displayed; an empty line will
1097 cause the loop to exit and the program to terminate.
1099 @item @emph{Debugging the program}
1101 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1102 which are required for debugging, are on by default when you create
1103 a new project.
1104 Thus unless you intentionally remove these settings, you will be able
1105 to debug any program that you develop using GPS.
1107 @enumerate a
1108 @item @emph{Initializing}
1110 Select @code{Debug}, then @code{Initialize}, then @file{example}
1112 @item @emph{Setting a breakpoint}
1114 After performing the initialization step, you will observe a small
1115 icon to the right of each line number.
1116 This serves as a toggle for breakpoints; clicking the icon will
1117 set a breakpoint at the corresponding line (the icon will change to
1118 a red circle with an ``x''), and clicking it again
1119 will remove the breakpoint / reset the icon.
1121 For purposes of this example, set a breakpoint at line 10 (the
1122 statement @code{Put_Line@ (Line@ (1..N));}
1124 @item @emph{Starting program execution}
1126 Select @code{Debug}, then @code{Run}.  When the
1127 @code{Program Arguments} window appears, click @code{OK}.
1128 A console window will appear; enter some line of text,
1129 e.g.@: @code{abcde}, at the prompt.
1130 The program will pause execution when it gets to the
1131 breakpoint, and the corresponding line is highlighted.
1133 @item @emph{Examining a variable}
1135 Move the mouse over one of the occurrences of the variable @code{N}.
1136 You will see the value (5) displayed, in ``tool tip'' fashion.
1137 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1138 You will see information about @code{N} appear in the @code{Debugger Data}
1139 pane, showing the value as 5.
1141 @item @emph{Assigning a new value to a variable}
1143 Right click on the @code{N} in the @code{Debugger Data} pane, and
1144 select @code{Set value of N}.
1145 When the input window appears, enter the value @code{4} and click
1146 @code{OK}.
1147 This value does not automatically appear in the @code{Debugger Data}
1148 pane; to see it, right click again on the @code{N} in the
1149 @code{Debugger Data} pane and select @code{Update value}.
1150 The new value, 4, will appear in red.
1152 @item @emph{Single stepping}
1154 Select @code{Debug}, then @code{Next}.
1155 This will cause the next statement to be executed, in this case the
1156 call of @code{Put_Line} with the string slice.
1157 Notice in the console window that the displayed string is simply
1158 @code{abcd} and not @code{abcde} which you had entered.
1159 This is because the upper bound of the slice is now 4 rather than 5.
1161 @item @emph{Removing a breakpoint}
1163 Toggle the breakpoint icon at line 10.
1165 @item @emph{Resuming execution from a breakpoint}
1167 Select @code{Debug}, then @code{Continue}.
1168 The program will reach the next iteration of the loop, and
1169 wait for input after displaying the prompt.
1170 This time, just hit the @kbd{Enter} key.
1171 The value of @code{N} will be 0, and the program will terminate.
1172 The console window will disappear.
1173 @end enumerate
1174 @end enumerate
1176 @node The GNAT Compilation Model
1177 @chapter The GNAT Compilation Model
1178 @cindex GNAT compilation model
1179 @cindex Compilation model
1181 @menu
1182 * Source Representation::
1183 * Foreign Language Representation::
1184 * File Naming Rules::
1185 * Using Other File Names::
1186 * Alternative File Naming Schemes::
1187 * Generating Object Files::
1188 * Source Dependencies::
1189 * The Ada Library Information Files::
1190 * Binding an Ada Program::
1191 * Mixed Language Programming::
1192 * Building Mixed Ada & C++ Programs::
1193 * Comparison between GNAT and C/C++ Compilation Models::
1194 * Comparison between GNAT and Conventional Ada Library Models::
1195 @end menu
1197 @noindent
1198 This chapter describes the compilation model used by GNAT. Although
1199 similar to that used by other languages, such as C and C++, this model
1200 is substantially different from the traditional Ada compilation models,
1201 which are based on a library. The model is initially described without
1202 reference to the library-based model. If you have not previously used an
1203 Ada compiler, you need only read the first part of this chapter. The
1204 last section describes and discusses the differences between the GNAT
1205 model and the traditional Ada compiler models. If you have used other
1206 Ada compilers, this section will help you to understand those
1207 differences, and the advantages of the GNAT model.
1209 @node Source Representation
1210 @section Source Representation
1211 @cindex Latin-1
1213 @noindent
1214 Ada source programs are represented in standard text files, using
1215 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1216 7-bit ASCII set, plus additional characters used for
1217 representing foreign languages (@pxref{Foreign Language Representation}
1218 for support of non-USA character sets). The format effector characters
1219 are represented using their standard ASCII encodings, as follows:
1221 @table @code
1222 @item VT
1223 @findex VT
1224 Vertical tab, @code{16#0B#}
1226 @item HT
1227 @findex HT
1228 Horizontal tab, @code{16#09#}
1230 @item CR
1231 @findex CR
1232 Carriage return, @code{16#0D#}
1234 @item LF
1235 @findex LF
1236 Line feed, @code{16#0A#}
1238 @item FF
1239 @findex FF
1240 Form feed, @code{16#0C#}
1241 @end table
1243 @noindent
1244 Source files are in standard text file format. In addition, GNAT will
1245 recognize a wide variety of stream formats, in which the end of
1246 physical lines is marked by any of the following sequences:
1247 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1248 in accommodating files that are imported from other operating systems.
1250 @cindex End of source file
1251 @cindex Source file, end
1252 @findex SUB
1253 The end of a source file is normally represented by the physical end of
1254 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1255 recognized as signalling the end of the source file. Again, this is
1256 provided for compatibility with other operating systems where this
1257 code is used to represent the end of file.
1259 Each file contains a single Ada compilation unit, including any pragmas
1260 associated with the unit. For example, this means you must place a
1261 package declaration (a package @dfn{spec}) and the corresponding body in
1262 separate files. An Ada @dfn{compilation} (which is a sequence of
1263 compilation units) is represented using a sequence of files. Similarly,
1264 you will place each subunit or child unit in a separate file.
1266 @node Foreign Language Representation
1267 @section Foreign Language Representation
1269 @noindent
1270 GNAT supports the standard character sets defined in Ada as well as
1271 several other non-standard character sets for use in localized versions
1272 of the compiler (@pxref{Character Set Control}).
1273 @menu
1274 * Latin-1::
1275 * Other 8-Bit Codes::
1276 * Wide_Character Encodings::
1277 * Wide_Wide_Character Encodings::
1278 @end menu
1280 @node Latin-1
1281 @subsection Latin-1
1282 @cindex Latin-1
1284 @noindent
1285 The basic character set is Latin-1. This character set is defined by ISO
1286 standard 8859, part 1. The lower half (character codes @code{16#00#}
1287 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1288 half is used to represent additional characters. These include extended letters
1289 used by European languages, such as French accents, the vowels with umlauts
1290 used in German, and the extra letter A-ring used in Swedish.
1292 @findex Ada.Characters.Latin_1
1293 For a complete list of Latin-1 codes and their encodings, see the source
1294 file of library unit @code{Ada.Characters.Latin_1} in file
1295 @file{a-chlat1.ads}.
1296 You may use any of these extended characters freely in character or
1297 string literals. In addition, the extended characters that represent
1298 letters can be used in identifiers.
1300 @node Other 8-Bit Codes
1301 @subsection Other 8-Bit Codes
1303 @noindent
1304 GNAT also supports several other 8-bit coding schemes:
1306 @table @asis
1307 @item ISO 8859-2 (Latin-2)
1308 @cindex Latin-2
1309 @cindex ISO 8859-2
1310 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1311 equivalence.
1313 @item ISO 8859-3 (Latin-3)
1314 @cindex Latin-3
1315 @cindex ISO 8859-3
1316 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1317 equivalence.
1319 @item ISO 8859-4 (Latin-4)
1320 @cindex Latin-4
1321 @cindex ISO 8859-4
1322 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1323 equivalence.
1325 @item ISO 8859-5 (Cyrillic)
1326 @cindex ISO 8859-5
1327 @cindex Cyrillic
1328 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1329 lowercase equivalence.
1331 @item ISO 8859-15 (Latin-9)
1332 @cindex ISO 8859-15
1333 @cindex Latin-9
1334 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1335 lowercase equivalence
1337 @item IBM PC (code page 437)
1338 @cindex code page 437
1339 This code page is the normal default for PCs in the U.S. It corresponds
1340 to the original IBM PC character set. This set has some, but not all, of
1341 the extended Latin-1 letters, but these letters do not have the same
1342 encoding as Latin-1. In this mode, these letters are allowed in
1343 identifiers with uppercase and lowercase equivalence.
1345 @item IBM PC (code page 850)
1346 @cindex code page 850
1347 This code page is a modification of 437 extended to include all the
1348 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1349 mode, all these letters are allowed in identifiers with uppercase and
1350 lowercase equivalence.
1352 @item Full Upper 8-bit
1353 Any character in the range 80-FF allowed in identifiers, and all are
1354 considered distinct. In other words, there are no uppercase and lowercase
1355 equivalences in this range. This is useful in conjunction with
1356 certain encoding schemes used for some foreign character sets (e.g.,
1357 the typical method of representing Chinese characters on the PC).
1359 @item No Upper-Half
1360 No upper-half characters in the range 80-FF are allowed in identifiers.
1361 This gives Ada 83 compatibility for identifier names.
1362 @end table
1364 @noindent
1365 For precise data on the encodings permitted, and the uppercase and lowercase
1366 equivalences that are recognized, see the file @file{csets.adb} in
1367 the GNAT compiler sources. You will need to obtain a full source release
1368 of GNAT to obtain this file.
1370 @node Wide_Character Encodings
1371 @subsection Wide_Character Encodings
1373 @noindent
1374 GNAT allows wide character codes to appear in character and string
1375 literals, and also optionally in identifiers, by means of the following
1376 possible encoding schemes:
1378 @table @asis
1380 @item Hex Coding
1381 In this encoding, a wide character is represented by the following five
1382 character sequence:
1384 @smallexample
1385 ESC a b c d
1386 @end smallexample
1388 @noindent
1389 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1390 characters (using uppercase letters) of the wide character code. For
1391 example, ESC A345 is used to represent the wide character with code
1392 @code{16#A345#}.
1393 This scheme is compatible with use of the full Wide_Character set.
1395 @item Upper-Half Coding
1396 @cindex Upper-Half Coding
1397 The wide character with encoding @code{16#abcd#} where the upper bit is on
1398 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1399 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1400 character, but is not required to be in the upper half. This method can
1401 be also used for shift-JIS or EUC, where the internal coding matches the
1402 external coding.
1404 @item Shift JIS Coding
1405 @cindex Shift JIS Coding
1406 A wide character is represented by a two-character sequence,
1407 @code{16#ab#} and
1408 @code{16#cd#}, with the restrictions described for upper-half encoding as
1409 described above. The internal character code is the corresponding JIS
1410 character according to the standard algorithm for Shift-JIS
1411 conversion. Only characters defined in the JIS code set table can be
1412 used with this encoding method.
1414 @item EUC Coding
1415 @cindex EUC Coding
1416 A wide character is represented by a two-character sequence
1417 @code{16#ab#} and
1418 @code{16#cd#}, with both characters being in the upper half. The internal
1419 character code is the corresponding JIS character according to the EUC
1420 encoding algorithm. Only characters defined in the JIS code set table
1421 can be used with this encoding method.
1423 @item UTF-8 Coding
1424 A wide character is represented using
1425 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1426 10646-1/Am.2. Depending on the character value, the representation
1427 is a one, two, or three byte sequence:
1428 @smallexample
1429 @iftex
1430 @leftskip=.7cm
1431 @end iftex
1432 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1433 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1434 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1436 @end smallexample
1438 @noindent
1439 where the @var{xxx} bits correspond to the left-padded bits of the
1440 16-bit character value. Note that all lower half ASCII characters
1441 are represented as ASCII bytes and all upper half characters and
1442 other wide characters are represented as sequences of upper-half
1443 (The full UTF-8 scheme allows for encoding 31-bit characters as
1444 6-byte sequences, and in the following section on wide wide
1445 characters, the use of these sequences is documented).
1447 @item Brackets Coding
1448 In this encoding, a wide character is represented by the following eight
1449 character sequence:
1451 @smallexample
1452 [ " a b c d " ]
1453 @end smallexample
1455 @noindent
1456 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1457 characters (using uppercase letters) of the wide character code. For
1458 example, [``A345''] is used to represent the wide character with code
1459 @code{16#A345#}. It is also possible (though not required) to use the
1460 Brackets coding for upper half characters. For example, the code
1461 @code{16#A3#} can be represented as @code{[``A3'']}.
1463 This scheme is compatible with use of the full Wide_Character set,
1464 and is also the method used for wide character encoding in some standard
1465 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1467 @end table
1469 @noindent
1470 Note: Some of these coding schemes do not permit the full use of the
1471 Ada character set. For example, neither Shift JIS, nor EUC allow the
1472 use of the upper half of the Latin-1 set.
1474 @node Wide_Wide_Character Encodings
1475 @subsection Wide_Wide_Character Encodings
1477 @noindent
1478 GNAT allows wide wide character codes to appear in character and string
1479 literals, and also optionally in identifiers, by means of the following
1480 possible encoding schemes:
1482 @table @asis
1484 @item UTF-8 Coding
1485 A wide character is represented using
1486 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1487 10646-1/Am.2. Depending on the character value, the representation
1488 of character codes with values greater than 16#FFFF# is a
1489 is a four, five, or six byte sequence:
1491 @smallexample
1492 @iftex
1493 @leftskip=.7cm
1494 @end iftex
1495 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1496                              10xxxxxx
1497 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1498                              10xxxxxx 10xxxxxx
1499 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1500                              10xxxxxx 10xxxxxx 10xxxxxx
1501 @end smallexample
1503 @noindent
1504 where the @var{xxx} bits correspond to the left-padded bits of the
1505 32-bit character value.
1507 @item Brackets Coding
1508 In this encoding, a wide wide character is represented by the following ten or
1509 twelve byte character sequence:
1511 @smallexample
1512 [ " a b c d e f " ]
1513 [ " a b c d e f g h " ]
1514 @end smallexample
1516 @noindent
1517 Where @code{a-h} are the six or eight hexadecimal
1518 characters (using uppercase letters) of the wide wide character code. For
1519 example, ["1F4567"] is used to represent the wide wide character with code
1520 @code{16#001F_4567#}.
1522 This scheme is compatible with use of the full Wide_Wide_Character set,
1523 and is also the method used for wide wide character encoding in some standard
1524 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1526 @end table
1528 @node File Naming Rules
1529 @section File Naming Rules
1531 @noindent
1532 The default file name is determined by the name of the unit that the
1533 file contains. The name is formed by taking the full expanded name of
1534 the unit and replacing the separating dots with hyphens and using
1535 lowercase for all letters.
1537 An exception arises if the file name generated by the above rules starts
1538 with one of the characters
1539 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1540 and the second character is a
1541 minus. In this case, the character tilde is used in place
1542 of the minus. The reason for this special rule is to avoid clashes with
1543 the standard names for child units of the packages System, Ada,
1544 Interfaces, and GNAT, which use the prefixes
1545 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1546 respectively.
1548 The file extension is @file{.ads} for a spec and
1549 @file{.adb} for a body. The following list shows some
1550 examples of these rules.
1552 @table @file
1553 @item main.ads
1554 Main (spec)
1555 @item main.adb
1556 Main (body)
1557 @item arith_functions.ads
1558 Arith_Functions (package spec)
1559 @item arith_functions.adb
1560 Arith_Functions (package body)
1561 @item func-spec.ads
1562 Func.Spec (child package spec)
1563 @item func-spec.adb
1564 Func.Spec (child package body)
1565 @item main-sub.adb
1566 Sub (subunit of Main)
1567 @item a~bad.adb
1568 A.Bad (child package body)
1569 @end table
1571 @noindent
1572 Following these rules can result in excessively long
1573 file names if corresponding
1574 unit names are long (for example, if child units or subunits are
1575 heavily nested). An option is available to shorten such long file names
1576 (called file name ``krunching''). This may be particularly useful when
1577 programs being developed with GNAT are to be used on operating systems
1578 with limited file name lengths. @xref{Using gnatkr}.
1580 Of course, no file shortening algorithm can guarantee uniqueness over
1581 all possible unit names; if file name krunching is used, it is your
1582 responsibility to ensure no name clashes occur. Alternatively you
1583 can specify the exact file names that you want used, as described
1584 in the next section. Finally, if your Ada programs are migrating from a
1585 compiler with a different naming convention, you can use the gnatchop
1586 utility to produce source files that follow the GNAT naming conventions.
1587 (For details @pxref{Renaming Files with gnatchop}.)
1589 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1590 systems, case is not significant. So for example on @code{Windows XP}
1591 if the canonical name is @code{main-sub.adb}, you can use the file name
1592 @code{Main-Sub.adb} instead. However, case is significant for other
1593 operating systems, so for example, if you want to use other than
1594 canonically cased file names on a Unix system, you need to follow
1595 the procedures described in the next section.
1597 @node Using Other File Names
1598 @section Using Other File Names
1599 @cindex File names
1601 @noindent
1602 In the previous section, we have described the default rules used by
1603 GNAT to determine the file name in which a given unit resides. It is
1604 often convenient to follow these default rules, and if you follow them,
1605 the compiler knows without being explicitly told where to find all
1606 the files it needs.
1608 However, in some cases, particularly when a program is imported from
1609 another Ada compiler environment, it may be more convenient for the
1610 programmer to specify which file names contain which units. GNAT allows
1611 arbitrary file names to be used by means of the Source_File_Name pragma.
1612 The form of this pragma is as shown in the following examples:
1613 @cindex Source_File_Name pragma
1615 @smallexample @c ada
1616 @cartouche
1617 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1618   Spec_File_Name => "myutilst_a.ada");
1619 @b{pragma} Source_File_name (My_Utilities.Stacks,
1620   Body_File_Name => "myutilst.ada");
1621 @end cartouche
1622 @end smallexample
1624 @noindent
1625 As shown in this example, the first argument for the pragma is the unit
1626 name (in this example a child unit). The second argument has the form
1627 of a named association. The identifier
1628 indicates whether the file name is for a spec or a body;
1629 the file name itself is given by a string literal.
1631 The source file name pragma is a configuration pragma, which means that
1632 normally it will be placed in the @file{gnat.adc}
1633 file used to hold configuration
1634 pragmas that apply to a complete compilation environment.
1635 For more details on how the @file{gnat.adc} file is created and used
1636 see @ref{Handling of Configuration Pragmas}.
1637 @cindex @file{gnat.adc}
1639 GNAT allows completely arbitrary file names to be specified using the
1640 source file name pragma. However, if the file name specified has an
1641 extension other than @file{.ads} or @file{.adb} it is necessary to use
1642 a special syntax when compiling the file. The name in this case must be
1643 preceded by the special sequence @option{-x} followed by a space and the name
1644 of the language, here @code{ada}, as in:
1646 @smallexample
1647 $ gcc -c -x ada peculiar_file_name.sim
1648 @end smallexample
1650 @noindent
1651 @command{gnatmake} handles non-standard file names in the usual manner (the
1652 non-standard file name for the main program is simply used as the
1653 argument to gnatmake). Note that if the extension is also non-standard,
1654 then it must be included in the @command{gnatmake} command, it may not
1655 be omitted.
1657 @node Alternative File Naming Schemes
1658 @section Alternative File Naming Schemes
1659 @cindex File naming schemes, alternative
1660 @cindex File names
1662 In the previous section, we described the use of the @code{Source_File_Name}
1663 pragma to allow arbitrary names to be assigned to individual source files.
1664 However, this approach requires one pragma for each file, and especially in
1665 large systems can result in very long @file{gnat.adc} files, and also create
1666 a maintenance problem.
1668 GNAT also provides a facility for specifying systematic file naming schemes
1669 other than the standard default naming scheme previously described. An
1670 alternative scheme for naming is specified by the use of
1671 @code{Source_File_Name} pragmas having the following format:
1672 @cindex Source_File_Name pragma
1674 @smallexample @c ada
1675 @b{pragma} Source_File_Name (
1676    Spec_File_Name  => FILE_NAME_PATTERN
1677  @r{[},Casing          => CASING_SPEC@r{]}
1678  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1680 @b{pragma} Source_File_Name (
1681    Body_File_Name  => FILE_NAME_PATTERN
1682  @r{[},Casing          => CASING_SPEC@r{]}
1683  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1685 @b{pragma} Source_File_Name (
1686    Subunit_File_Name  => FILE_NAME_PATTERN
1687  @r{[},Casing             => CASING_SPEC@r{]}
1688  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
1690 FILE_NAME_PATTERN ::= STRING_LITERAL
1691 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1692 @end smallexample
1694 @noindent
1695 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1696 It contains a single asterisk character, and the unit name is substituted
1697 systematically for this asterisk. The optional parameter
1698 @code{Casing} indicates
1699 whether the unit name is to be all upper-case letters, all lower-case letters,
1700 or mixed-case. If no
1701 @code{Casing} parameter is used, then the default is all
1702 lower-case.
1704 The optional @code{Dot_Replacement} string is used to replace any periods
1705 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1706 argument is used then separating dots appear unchanged in the resulting
1707 file name.
1708 Although the above syntax indicates that the
1709 @code{Casing} argument must appear
1710 before the @code{Dot_Replacement} argument, but it
1711 is also permissible to write these arguments in the opposite order.
1713 As indicated, it is possible to specify different naming schemes for
1714 bodies, specs, and subunits. Quite often the rule for subunits is the
1715 same as the rule for bodies, in which case, there is no need to give
1716 a separate @code{Subunit_File_Name} rule, and in this case the
1717 @code{Body_File_name} rule is used for subunits as well.
1719 The separate rule for subunits can also be used to implement the rather
1720 unusual case of a compilation environment (e.g.@: a single directory) which
1721 contains a subunit and a child unit with the same unit name. Although
1722 both units cannot appear in the same partition, the Ada Reference Manual
1723 allows (but does not require) the possibility of the two units coexisting
1724 in the same environment.
1726 The file name translation works in the following steps:
1728 @itemize @bullet
1730 @item
1731 If there is a specific @code{Source_File_Name} pragma for the given unit,
1732 then this is always used, and any general pattern rules are ignored.
1734 @item
1735 If there is a pattern type @code{Source_File_Name} pragma that applies to
1736 the unit, then the resulting file name will be used if the file exists. If
1737 more than one pattern matches, the latest one will be tried first, and the
1738 first attempt resulting in a reference to a file that exists will be used.
1740 @item
1741 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1742 for which the corresponding file exists, then the standard GNAT default
1743 naming rules are used.
1745 @end itemize
1747 @noindent
1748 As an example of the use of this mechanism, consider a commonly used scheme
1749 in which file names are all lower case, with separating periods copied
1750 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1751 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1752 two pragmas appear:
1754 @smallexample @c ada
1755 @b{pragma} Source_File_Name
1756   (Spec_File_Name => "*.1.ada");
1757 @b{pragma} Source_File_Name
1758   (Body_File_Name => "*.2.ada");
1759 @end smallexample
1761 @noindent
1762 The default GNAT scheme is actually implemented by providing the following
1763 default pragmas internally:
1765 @smallexample @c ada
1766 @b{pragma} Source_File_Name
1767   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1768 @b{pragma} Source_File_Name
1769   (Body_File_Name => "*.adb", Dot_Replacement => "-");
1770 @end smallexample
1772 @noindent
1773 Our final example implements a scheme typically used with one of the
1774 Ada 83 compilers, where the separator character for subunits was ``__''
1775 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1776 by adding @file{.ADA}, and subunits by
1777 adding @file{.SEP}. All file names were
1778 upper case. Child units were not present of course since this was an
1779 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1780 the same double underscore separator for child units.
1782 @smallexample @c ada
1783 @b{pragma} Source_File_Name
1784   (Spec_File_Name => "*_.ADA",
1785    Dot_Replacement => "__",
1786    Casing = Uppercase);
1787 @b{pragma} Source_File_Name
1788   (Body_File_Name => "*.ADA",
1789    Dot_Replacement => "__",
1790    Casing = Uppercase);
1791 @b{pragma} Source_File_Name
1792   (Subunit_File_Name => "*.SEP",
1793    Dot_Replacement => "__",
1794    Casing = Uppercase);
1795 @end smallexample
1797 @node Generating Object Files
1798 @section Generating Object Files
1800 @noindent
1801 An Ada program consists of a set of source files, and the first step in
1802 compiling the program is to generate the corresponding object files.
1803 These are generated by compiling a subset of these source files.
1804 The files you need to compile are the following:
1806 @itemize @bullet
1807 @item
1808 If a package spec has no body, compile the package spec to produce the
1809 object file for the package.
1811 @item
1812 If a package has both a spec and a body, compile the body to produce the
1813 object file for the package. The source file for the package spec need
1814 not be compiled in this case because there is only one object file, which
1815 contains the code for both the spec and body of the package.
1817 @item
1818 For a subprogram, compile the subprogram body to produce the object file
1819 for the subprogram. The spec, if one is present, is as usual in a
1820 separate file, and need not be compiled.
1822 @item
1823 @cindex Subunits
1824 In the case of subunits, only compile the parent unit. A single object
1825 file is generated for the entire subunit tree, which includes all the
1826 subunits.
1828 @item
1829 Compile child units independently of their parent units
1830 (though, of course, the spec of all the ancestor unit must be present in order
1831 to compile a child unit).
1833 @item
1834 @cindex Generics
1835 Compile generic units in the same manner as any other units. The object
1836 files in this case are small dummy files that contain at most the
1837 flag used for elaboration checking. This is because GNAT always handles generic
1838 instantiation by means of macro expansion. However, it is still necessary to
1839 compile generic units, for dependency checking and elaboration purposes.
1840 @end itemize
1842 @noindent
1843 The preceding rules describe the set of files that must be compiled to
1844 generate the object files for a program. Each object file has the same
1845 name as the corresponding source file, except that the extension is
1846 @file{.o} as usual.
1848 You may wish to compile other files for the purpose of checking their
1849 syntactic and semantic correctness. For example, in the case where a
1850 package has a separate spec and body, you would not normally compile the
1851 spec. However, it is convenient in practice to compile the spec to make
1852 sure it is error-free before compiling clients of this spec, because such
1853 compilations will fail if there is an error in the spec.
1855 GNAT provides an option for compiling such files purely for the
1856 purposes of checking correctness; such compilations are not required as
1857 part of the process of building a program. To compile a file in this
1858 checking mode, use the @option{-gnatc} switch.
1860 @node Source Dependencies
1861 @section Source Dependencies
1863 @noindent
1864 A given object file clearly depends on the source file which is compiled
1865 to produce it. Here we are using @dfn{depends} in the sense of a typical
1866 @code{make} utility; in other words, an object file depends on a source
1867 file if changes to the source file require the object file to be
1868 recompiled.
1869 In addition to this basic dependency, a given object may depend on
1870 additional source files as follows:
1872 @itemize @bullet
1873 @item
1874 If a file being compiled @code{with}'s a unit @var{X}, the object file
1875 depends on the file containing the spec of unit @var{X}. This includes
1876 files that are @code{with}'ed implicitly either because they are parents
1877 of @code{with}'ed child units or they are run-time units required by the
1878 language constructs used in a particular unit.
1880 @item
1881 If a file being compiled instantiates a library level generic unit, the
1882 object file depends on both the spec and body files for this generic
1883 unit.
1885 @item
1886 If a file being compiled instantiates a generic unit defined within a
1887 package, the object file depends on the body file for the package as
1888 well as the spec file.
1890 @item
1891 @findex Inline
1892 @cindex @option{-gnatn} switch
1893 If a file being compiled contains a call to a subprogram for which
1894 pragma @code{Inline} applies and inlining is activated with the
1895 @option{-gnatn} switch, the object file depends on the file containing the
1896 body of this subprogram as well as on the file containing the spec. Note
1897 that for inlining to actually occur as a result of the use of this switch,
1898 it is necessary to compile in optimizing mode.
1900 @cindex @option{-gnatN} switch
1901 The use of @option{-gnatN} activates  inlining optimization
1902 that is performed by the front end of the compiler. This inlining does
1903 not require that the code generation be optimized. Like @option{-gnatn},
1904 the use of this switch generates additional dependencies.
1906 When using a gcc-based back end (in practice this means using any version
1907 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1908 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1909 Historically front end inlining was more extensive than the gcc back end
1910 inlining, but that is no longer the case.
1912 @item
1913 If an object file @file{O} depends on the proper body of a subunit through
1914 inlining or instantiation, it depends on the parent unit of the subunit.
1915 This means that any modification of the parent unit or one of its subunits
1916 affects the compilation of @file{O}.
1918 @item
1919 The object file for a parent unit depends on all its subunit body files.
1921 @item
1922 The previous two rules meant that for purposes of computing dependencies and
1923 recompilation, a body and all its subunits are treated as an indivisible whole.
1925 @noindent
1926 These rules are applied transitively: if unit @code{A} @code{with}'s
1927 unit @code{B}, whose elaboration calls an inlined procedure in package
1928 @code{C}, the object file for unit @code{A} will depend on the body of
1929 @code{C}, in file @file{c.adb}.
1931 The set of dependent files described by these rules includes all the
1932 files on which the unit is semantically dependent, as dictated by the
1933 Ada language standard. However, it is a superset of what the
1934 standard describes, because it includes generic, inline, and subunit
1935 dependencies.
1937 An object file must be recreated by recompiling the corresponding source
1938 file if any of the source files on which it depends are modified. For
1939 example, if the @code{make} utility is used to control compilation,
1940 the rule for an Ada object file must mention all the source files on
1941 which the object file depends, according to the above definition.
1942 The determination of the necessary
1943 recompilations is done automatically when one uses @command{gnatmake}.
1944 @end itemize
1946 @node The Ada Library Information Files
1947 @section The Ada Library Information Files
1948 @cindex Ada Library Information files
1949 @cindex @file{ALI} files
1951 @noindent
1952 Each compilation actually generates two output files. The first of these
1953 is the normal object file that has a @file{.o} extension. The second is a
1954 text file containing full dependency information. It has the same
1955 name as the source file, but an @file{.ali} extension.
1956 This file is known as the Ada Library Information (@file{ALI}) file.
1957 The following information is contained in the @file{ALI} file.
1959 @itemize @bullet
1960 @item
1961 Version information (indicates which version of GNAT was used to compile
1962 the unit(s) in question)
1964 @item
1965 Main program information (including priority and time slice settings,
1966 as well as the wide character encoding used during compilation).
1968 @item
1969 List of arguments used in the @command{gcc} command for the compilation
1971 @item
1972 Attributes of the unit, including configuration pragmas used, an indication
1973 of whether the compilation was successful, exception model used etc.
1975 @item
1976 A list of relevant restrictions applying to the unit (used for consistency)
1977 checking.
1979 @item
1980 Categorization information (e.g.@: use of pragma @code{Pure}).
1982 @item
1983 Information on all @code{with}'ed units, including presence of
1984 @code{Elaborate} or @code{Elaborate_All} pragmas.
1986 @item
1987 Information from any @code{Linker_Options} pragmas used in the unit
1989 @item
1990 Information on the use of @code{Body_Version} or @code{Version}
1991 attributes in the unit.
1993 @item
1994 Dependency information. This is a list of files, together with
1995 time stamp and checksum information. These are files on which
1996 the unit depends in the sense that recompilation is required
1997 if any of these units are modified.
1999 @item
2000 Cross-reference data. Contains information on all entities referenced
2001 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2002 provide cross-reference information.
2004 @end itemize
2006 @noindent
2007 For a full detailed description of the format of the @file{ALI} file,
2008 see the source of the body of unit @code{Lib.Writ}, contained in file
2009 @file{lib-writ.adb} in the GNAT compiler sources.
2011 @node Binding an Ada Program
2012 @section Binding an Ada Program
2014 @noindent
2015 When using languages such as C and C++, once the source files have been
2016 compiled the only remaining step in building an executable program
2017 is linking the object modules together. This means that it is possible to
2018 link an inconsistent version of a program, in which two units have
2019 included different versions of the same header.
2021 The rules of Ada do not permit such an inconsistent program to be built.
2022 For example, if two clients have different versions of the same package,
2023 it is illegal to build a program containing these two clients.
2024 These rules are enforced by the GNAT binder, which also determines an
2025 elaboration order consistent with the Ada rules.
2027 The GNAT binder is run after all the object files for a program have
2028 been created. It is given the name of the main program unit, and from
2029 this it determines the set of units required by the program, by reading the
2030 corresponding ALI files. It generates error messages if the program is
2031 inconsistent or if no valid order of elaboration exists.
2033 If no errors are detected, the binder produces a main program, in Ada by
2034 default, that contains calls to the elaboration procedures of those
2035 compilation unit that require them, followed by
2036 a call to the main program. This Ada program is compiled to generate the
2037 object file for the main program. The name of
2038 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2039 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2040 main program unit.
2042 Finally, the linker is used to build the resulting executable program,
2043 using the object from the main program from the bind step as well as the
2044 object files for the Ada units of the program.
2046 @node Mixed Language Programming
2047 @section Mixed Language Programming
2048 @cindex Mixed Language Programming
2050 @noindent
2051 This section describes how to develop a mixed-language program,
2052 specifically one that comprises units in both Ada and C.
2054 @menu
2055 * Interfacing to C::
2056 * Calling Conventions::
2057 @end menu
2059 @node Interfacing to C
2060 @subsection Interfacing to C
2061 @noindent
2062 Interfacing Ada with a foreign language such as C involves using
2063 compiler directives to import and/or export entity definitions in each
2064 language---using @code{extern} statements in C, for instance, and the
2065 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2066 A full treatment of these topics is provided in Appendix B, section 1
2067 of the Ada Reference Manual.
2069 There are two ways to build a program using GNAT that contains some Ada
2070 sources and some foreign language sources, depending on whether or not
2071 the main subprogram is written in Ada.  Here is a source example with
2072 the main subprogram in Ada:
2074 @smallexample
2075 /* file1.c */
2076 #include <stdio.h>
2078 void print_num (int num)
2080   printf ("num is %d.\n", num);
2081   return;
2084 /* file2.c */
2086 /* num_from_Ada is declared in my_main.adb */
2087 extern int num_from_Ada;
2089 int get_num (void)
2091   return num_from_Ada;
2093 @end smallexample
2095 @smallexample @c ada
2096 --  my_main.adb
2097 procedure My_Main is
2099    --  Declare then export an Integer entity called num_from_Ada
2100    My_Num : Integer := 10;
2101    pragma Export (C, My_Num, "num_from_Ada");
2103    --  Declare an Ada function spec for Get_Num, then use
2104    --  C function get_num for the implementation.
2105    function Get_Num return Integer;
2106    pragma Import (C, Get_Num, "get_num");
2108    --  Declare an Ada procedure spec for Print_Num, then use
2109    --  C function print_num for the implementation.
2110    procedure Print_Num (Num : Integer);
2111    pragma Import (C, Print_Num, "print_num";
2113 begin
2114    Print_Num (Get_Num);
2115 end My_Main;
2116 @end smallexample
2118 @enumerate
2119 @item
2120 To build this example, first compile the foreign language files to
2121 generate object files:
2122 @smallexample
2123 gcc -c file1.c
2124 gcc -c file2.c
2125 @end smallexample
2127 @item
2128 Then, compile the Ada units to produce a set of object files and ALI
2129 files:
2130 @smallexample
2131 gnatmake -c my_main.adb
2132 @end smallexample
2134 @item
2135 Run the Ada binder on the Ada main program:
2136 @smallexample
2137 gnatbind my_main.ali
2138 @end smallexample
2140 @item
2141 Link the Ada main program, the Ada objects and the other language
2142 objects:
2143 @smallexample
2144 gnatlink my_main.ali file1.o file2.o
2145 @end smallexample
2146 @end enumerate
2148 The last three steps can be grouped in a single command:
2149 @smallexample
2150 gnatmake my_main.adb -largs file1.o file2.o
2151 @end smallexample
2153 @cindex Binder output file
2154 @noindent
2155 If the main program is in a language other than Ada, then you may have
2156 more than one entry point into the Ada subsystem. You must use a special
2157 binder option to generate callable routines that initialize and
2158 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2159 Calls to the initialization and finalization routines must be inserted
2160 in the main program, or some other appropriate point in the code. The
2161 call to initialize the Ada units must occur before the first Ada
2162 subprogram is called, and the call to finalize the Ada units must occur
2163 after the last Ada subprogram returns. The binder will place the
2164 initialization and finalization subprograms into the
2165 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2166 sources.  To illustrate, we have the following example:
2168 @smallexample
2169 /* main.c */
2170 extern void adainit (void);
2171 extern void adafinal (void);
2172 extern int add (int, int);
2173 extern int sub (int, int);
2175 int main (int argc, char *argv[])
2177   int a = 21, b = 7;
2179   adainit();
2181   /* Should print "21 + 7 = 28" */
2182   printf ("%d + %d = %d\n", a, b, add (a, b));
2183   /* Should print "21 - 7 = 14" */
2184   printf ("%d - %d = %d\n", a, b, sub (a, b));
2186   adafinal();
2188 @end smallexample
2190 @smallexample @c ada
2191 --  unit1.ads
2192 package Unit1 is
2193    function Add (A, B : Integer) return Integer;
2194    pragma Export (C, Add, "add");
2195 end Unit1;
2197 --  unit1.adb
2198 package body Unit1 is
2199    function Add (A, B : Integer) return Integer is
2200    begin
2201       return A + B;
2202    end Add;
2203 end Unit1;
2205 --  unit2.ads
2206 package Unit2 is
2207    function Sub (A, B : Integer) return Integer;
2208    pragma Export (C, Sub, "sub");
2209 end Unit2;
2211 --  unit2.adb
2212 package body Unit2 is
2213    function Sub (A, B : Integer) return Integer is
2214    begin
2215       return A - B;
2216    end Sub;
2217 end Unit2;
2218 @end smallexample
2220 @enumerate
2221 @item
2222 The build procedure for this application is similar to the last
2223 example's.  First, compile the foreign language files to generate object
2224 files:
2225 @smallexample
2226 gcc -c main.c
2227 @end smallexample
2229 @item
2230 Next, compile the Ada units to produce a set of object files and ALI
2231 files:
2232 @smallexample
2233 gnatmake -c unit1.adb
2234 gnatmake -c unit2.adb
2235 @end smallexample
2237 @item
2238 Run the Ada binder on every generated ALI file.  Make sure to use the
2239 @option{-n} option to specify a foreign main program:
2240 @smallexample
2241 gnatbind -n unit1.ali unit2.ali
2242 @end smallexample
2244 @item
2245 Link the Ada main program, the Ada objects and the foreign language
2246 objects. You need only list the last ALI file here:
2247 @smallexample
2248 gnatlink unit2.ali main.o -o exec_file
2249 @end smallexample
2251 This procedure yields a binary executable called @file{exec_file}.
2252 @end enumerate
2254 @noindent
2255 Depending on the circumstances (for example when your non-Ada main object
2256 does not provide symbol @code{main}), you may also need to instruct the
2257 GNAT linker not to include the standard startup objects by passing the
2258 @option{-nostartfiles} switch to @command{gnatlink}.
2260 @node Calling Conventions
2261 @subsection Calling Conventions
2262 @cindex Foreign Languages
2263 @cindex Calling Conventions
2264 GNAT follows standard calling sequence conventions and will thus interface
2265 to any other language that also follows these conventions. The following
2266 Convention identifiers are recognized by GNAT:
2268 @table @code
2269 @cindex Interfacing to Ada
2270 @cindex Other Ada compilers
2271 @cindex Convention Ada
2272 @item Ada
2273 This indicates that the standard Ada calling sequence will be
2274 used and all Ada data items may be passed without any limitations in the
2275 case where GNAT is used to generate both the caller and callee. It is also
2276 possible to mix GNAT generated code and code generated by another Ada
2277 compiler. In this case, the data types should be restricted to simple
2278 cases, including primitive types. Whether complex data types can be passed
2279 depends on the situation. Probably it is safe to pass simple arrays, such
2280 as arrays of integers or floats. Records may or may not work, depending
2281 on whether both compilers lay them out identically. Complex structures
2282 involving variant records, access parameters, tasks, or protected types,
2283 are unlikely to be able to be passed.
2285 Note that in the case of GNAT running
2286 on a platform that supports HP Ada 83, a higher degree of compatibility
2287 can be guaranteed, and in particular records are laid out in an identical
2288 manner in the two compilers. Note also that if output from two different
2289 compilers is mixed, the program is responsible for dealing with elaboration
2290 issues. Probably the safest approach is to write the main program in the
2291 version of Ada other than GNAT, so that it takes care of its own elaboration
2292 requirements, and then call the GNAT-generated adainit procedure to ensure
2293 elaboration of the GNAT components. Consult the documentation of the other
2294 Ada compiler for further details on elaboration.
2296 However, it is not possible to mix the tasking run time of GNAT and
2297 HP Ada 83, All the tasking operations must either be entirely within
2298 GNAT compiled sections of the program, or entirely within HP Ada 83
2299 compiled sections of the program.
2301 @cindex Interfacing to Assembly
2302 @cindex Convention Assembler
2303 @item Assembler
2304 Specifies assembler as the convention. In practice this has the
2305 same effect as convention Ada (but is not equivalent in the sense of being
2306 considered the same convention).
2308 @cindex Convention Asm
2309 @findex Asm
2310 @item Asm
2311 Equivalent to Assembler.
2313 @cindex Interfacing to COBOL
2314 @cindex Convention COBOL
2315 @findex COBOL
2316 @item COBOL
2317 Data will be passed according to the conventions described
2318 in section B.4 of the Ada Reference Manual.
2320 @findex C
2321 @cindex Interfacing to C
2322 @cindex Convention C
2323 @item C
2324 Data will be passed according to the conventions described
2325 in section B.3 of the Ada Reference Manual.
2327 A note on interfacing to a C ``varargs'' function:
2328 @findex C varargs function
2329 @cindex Interfacing to C varargs function
2330 @cindex varargs function interfaces
2332 @itemize @bullet
2333 @item
2334 In C, @code{varargs} allows a function to take a variable number of
2335 arguments. There is no direct equivalent in this to Ada. One
2336 approach that can be used is to create a C wrapper for each
2337 different profile and then interface to this C wrapper. For
2338 example, to print an @code{int} value using @code{printf},
2339 create a C function @code{printfi} that takes two arguments, a
2340 pointer to a string and an int, and calls @code{printf}.
2341 Then in the Ada program, use pragma @code{Import} to
2342 interface to @code{printfi}.
2344 @item
2345 It may work on some platforms to directly interface to
2346 a @code{varargs} function by providing a specific Ada profile
2347 for a particular call. However, this does not work on
2348 all platforms, since there is no guarantee that the
2349 calling sequence for a two argument normal C function
2350 is the same as for calling a @code{varargs} C function with
2351 the same two arguments.
2352 @end itemize
2354 @cindex Convention Default
2355 @findex Default
2356 @item Default
2357 Equivalent to C.
2359 @cindex Convention External
2360 @findex External
2361 @item External
2362 Equivalent to C.
2364 @findex C++
2365 @cindex Interfacing to C++
2366 @cindex Convention C++
2367 @item C_Plus_Plus (or CPP)
2368 This stands for C++. For most purposes this is identical to C.
2369 See the separate description of the specialized GNAT pragmas relating to
2370 C++ interfacing for further details.
2372 @findex Fortran
2373 @cindex Interfacing to Fortran
2374 @cindex Convention Fortran
2375 @item Fortran
2376 Data will be passed according to the conventions described
2377 in section B.5 of the Ada Reference Manual.
2379 @item Intrinsic
2380 This applies to an intrinsic operation, as defined in the Ada
2381 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2382 this means that the body of the subprogram is provided by the compiler itself,
2383 usually by means of an efficient code sequence, and that the user does not
2384 supply an explicit body for it. In an application program, the pragma may
2385 be applied to the following sets of names:
2387 @itemize @bullet
2388 @item
2389 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2390 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2391 two formal parameters. The
2392 first one must be a signed integer type or a modular type with a binary
2393 modulus, and the second parameter must be of type Natural.
2394 The return type must be the same as the type of the first argument. The size
2395 of this type can only be 8, 16, 32, or 64.
2397 @item
2398 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2399 The corresponding operator declaration must have parameters and result type
2400 that have the same root numeric type (for example, all three are long_float
2401 types). This simplifies the definition of operations that use type checking
2402 to perform dimensional checks:
2404 @smallexample @c ada
2405 @b{type} Distance @b{is} @b{new} Long_Float;
2406 @b{type} Time     @b{is} @b{new} Long_Float;
2407 @b{type} Velocity @b{is} @b{new} Long_Float;
2408 @b{function} "/" (D : Distance; T : Time)
2409   @b{return} Velocity;
2410 @b{pragma} Import (Intrinsic, "/");
2411 @end smallexample
2413 @noindent
2414 This common idiom is often programmed with a generic definition and an
2415 explicit body. The pragma makes it simpler to introduce such declarations.
2416 It incurs no overhead in compilation time or code size, because it is
2417 implemented as a single machine instruction.
2419 @item
2420 General subprogram entities, to bind an Ada subprogram declaration to
2421 a compiler builtin by name with back-ends where such interfaces are
2422 available. A typical example is the set of ``__builtin'' functions
2423 exposed by the GCC back-end, as in the following example:
2425 @smallexample @c ada
2426    @b{function} builtin_sqrt (F : Float) @b{return} Float;
2427    @b{pragma} Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2428 @end smallexample
2430 Most of the GCC builtins are accessible this way, and as for other
2431 import conventions (e.g. C), it is the user's responsibility to ensure
2432 that the Ada subprogram profile matches the underlying builtin
2433 expectations.
2434 @end itemize
2436 @noindent
2438 @findex Stdcall
2439 @cindex Convention Stdcall
2440 @item Stdcall
2441 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2442 and specifies that the @code{Stdcall} calling sequence will be used,
2443 as defined by the NT API. Nevertheless, to ease building
2444 cross-platform bindings this convention will be handled as a @code{C} calling
2445 convention on non-Windows platforms.
2447 @findex DLL
2448 @cindex Convention DLL
2449 @item DLL
2450 This is equivalent to @code{Stdcall}.
2452 @findex Win32
2453 @cindex Convention Win32
2454 @item Win32
2455 This is equivalent to @code{Stdcall}.
2457 @findex Stubbed
2458 @cindex Convention Stubbed
2459 @item Stubbed
2460 This is a special convention that indicates that the compiler
2461 should provide a stub body that raises @code{Program_Error}.
2462 @end table
2464 @noindent
2465 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2466 that can be used to parameterize conventions and allow additional synonyms
2467 to be specified. For example if you have legacy code in which the convention
2468 identifier Fortran77 was used for Fortran, you can use the configuration
2469 pragma:
2471 @smallexample @c ada
2472 @b{pragma} Convention_Identifier (Fortran77, Fortran);
2473 @end smallexample
2475 @noindent
2476 And from now on the identifier Fortran77 may be used as a convention
2477 identifier (for example in an @code{Import} pragma) with the same
2478 meaning as Fortran.
2480 @node Building Mixed Ada & C++ Programs
2481 @section Building Mixed Ada and C++ Programs
2483 @noindent
2484 A programmer inexperienced with mixed-language development may find that
2485 building an application containing both Ada and C++ code can be a
2486 challenge.  This section gives a few
2487 hints that should make this task easier. The first section addresses
2488 the differences between interfacing with C and interfacing with C++.
2489 The second section
2490 looks into the delicate problem of linking the complete application from
2491 its Ada and C++ parts. The last section gives some hints on how the GNAT
2492 run-time library can be adapted in order to allow inter-language dispatching
2493 with a new C++ compiler.
2495 @menu
2496 * Interfacing to C++::
2497 * Linking a Mixed C++ & Ada Program::
2498 * A Simple Example::
2499 * Interfacing with C++ constructors::
2500 * Interfacing with C++ at the Class Level::
2501 @end menu
2503 @node Interfacing to C++
2504 @subsection Interfacing to C++
2506 @noindent
2507 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2508 generating code that is compatible with the G++ Application Binary
2509 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2511 @noindent
2512 Interfacing can be done at 3 levels: simple data, subprograms, and
2513 classes. In the first two cases, GNAT offers a specific @code{Convention
2514 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2515 Usually, C++ mangles the names of subprograms. To generate proper mangled
2516 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2517 This problem can also be addressed manually in two ways:
2519 @itemize @bullet
2520 @item
2521 by modifying the C++ code in order to force a C convention using
2522 the @code{extern "C"} syntax.
2524 @item
2525 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2526 Link_Name argument of the pragma import.
2527 @end itemize
2529 @noindent
2530 Interfacing at the class level can be achieved by using the GNAT specific
2531 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
2532 gnat_rm, GNAT Reference Manual}, for additional information.
2534 @node Linking a Mixed C++ & Ada Program
2535 @subsection Linking a Mixed C++ & Ada Program
2537 @noindent
2538 Usually the linker of the C++ development system must be used to link
2539 mixed applications because most C++ systems will resolve elaboration
2540 issues (such as calling constructors on global class instances)
2541 transparently during the link phase. GNAT has been adapted to ease the
2542 use of a foreign linker for the last phase. Three cases can be
2543 considered:
2544 @enumerate
2546 @item
2547 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2548 The C++ linker can simply be called by using the C++ specific driver
2549 called @code{g++}.
2551 Note that if the C++ code uses inline functions, you will need to
2552 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2553 order to provide an existing function implementation that the Ada code can
2554 link with.
2556 @smallexample
2557 $ g++ -c -fkeep-inline-functions file1.C
2558 $ g++ -c -fkeep-inline-functions file2.C
2559 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2560 @end smallexample
2562 @item
2563 Using GNAT and G++ from two different GCC installations: If both
2564 compilers are on the @env{PATH}, the previous method may be used. It is
2565 important to note that environment variables such as
2566 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2567 @env{GCC_ROOT} will affect both compilers
2568 at the same time and may make one of the two compilers operate
2569 improperly if set during invocation of the wrong compiler.  It is also
2570 very important that the linker uses the proper @file{libgcc.a} GCC
2571 library -- that is, the one from the C++ compiler installation. The
2572 implicit link command as suggested in the @command{gnatmake} command
2573 from the former example can be replaced by an explicit link command with
2574 the full-verbosity option in order to verify which library is used:
2575 @smallexample
2576 $ gnatbind ada_unit
2577 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2578 @end smallexample
2579 If there is a problem due to interfering environment variables, it can
2580 be worked around by using an intermediate script. The following example
2581 shows the proper script to use when GNAT has not been installed at its
2582 default location and g++ has been installed at its default location:
2584 @smallexample
2585 $ cat ./my_script
2586 #!/bin/sh
2587 unset BINUTILS_ROOT
2588 unset GCC_ROOT
2589 c++ $*
2590 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2591 @end smallexample
2593 @item
2594 Using a non-GNU C++ compiler: The commands previously described can be
2595 used to insure that the C++ linker is used. Nonetheless, you need to add
2596 a few more parameters to the link command line, depending on the exception
2597 mechanism used.
2599 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2600 to the libgcc libraries are required:
2602 @smallexample
2603 $ cat ./my_script
2604 #!/bin/sh
2605 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2606 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2607 @end smallexample
2609 Where CC is the name of the non-GNU C++ compiler.
2611 If the @code{zero cost} exception mechanism is used, and the platform
2612 supports automatic registration of exception tables (e.g.@: Solaris),
2613 paths to more objects are required:
2615 @smallexample
2616 $ cat ./my_script
2617 #!/bin/sh
2618 CC `gcc -print-file-name=crtbegin.o` $* \
2619 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2620 `gcc -print-file-name=crtend.o`
2621 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2622 @end smallexample
2624 If the @code{zero cost} exception mechanism is used, and the platform
2625 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2626 or AIX), the simple approach described above will not work and
2627 a pre-linking phase using GNAT will be necessary.
2629 @end enumerate
2631 Another alternative is to use the @command{gprbuild} multi-language builder
2632 which has a large knowledge base and knows how to link Ada and C++ code
2633 together automatically in most cases.
2635 @node A Simple Example
2636 @subsection  A Simple Example
2637 @noindent
2638 The following example, provided as part of the GNAT examples, shows how
2639 to achieve procedural interfacing between Ada and C++ in both
2640 directions. The C++ class A has two methods. The first method is exported
2641 to Ada by the means of an extern C wrapper function. The second method
2642 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2643 a limited record with a layout comparable to the C++ class. The Ada
2644 subprogram, in turn, calls the C++ method. So, starting from the C++
2645 main program, the process passes back and forth between the two
2646 languages.
2648 @noindent
2649 Here are the compilation commands:
2650 @smallexample
2651 $ gnatmake -c simple_cpp_interface
2652 $ g++ -c cpp_main.C
2653 $ g++ -c ex7.C
2654 $ gnatbind -n simple_cpp_interface
2655 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2656       -lstdc++ ex7.o cpp_main.o
2657 @end smallexample
2659 @noindent
2660 Here are the corresponding sources:
2661 @smallexample
2663 //cpp_main.C
2665 #include "ex7.h"
2667 extern "C" @{
2668   void adainit (void);
2669   void adafinal (void);
2670   void method1 (A *t);
2673 void method1 (A *t)
2675   t->method1 ();
2678 int main ()
2680   A obj;
2681   adainit ();
2682   obj.method2 (3030);
2683   adafinal ();
2686 //ex7.h
2688 class Origin @{
2689  public:
2690   int o_value;
2692 class A : public Origin @{
2693  public:
2694   void method1 (void);
2695   void method2 (int v);
2696   A();
2697   int   a_value;
2700 //ex7.C
2702 #include "ex7.h"
2703 #include <stdio.h>
2705 extern "C" @{ void ada_method2 (A *t, int v);@}
2707 void A::method1 (void)
2709   a_value = 2020;
2710   printf ("in A::method1, a_value = %d \n",a_value);
2714 void A::method2 (int v)
2716    ada_method2 (this, v);
2717    printf ("in A::method2, a_value = %d \n",a_value);
2721 A::A(void)
2723    a_value = 1010;
2724   printf ("in A::A, a_value = %d \n",a_value);
2726 @end smallexample
2728 @smallexample @c ada
2729 --@i{ Ada sources}
2730 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2732    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2733    @b{begin}
2734       Method1 (This);
2735       This.A_Value := V;
2736    @b{end} Ada_Method2;
2738 @b{end} Simple_Cpp_Interface;
2740 @b{with} System;
2741 @b{package} Simple_Cpp_Interface @b{is}
2742    @b{type} A @b{is} @b{limited}
2743       @b{record}
2744          Vptr    : System.Address;
2745          O_Value : Integer;
2746          A_Value : Integer;
2747       @b{end} @b{record};
2748    @b{pragma} Convention (C, A);
2750    @b{procedure} Method1 (This : @b{in} @b{out} A);
2751    @b{pragma} Import (C, Method1);
2753    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2754    @b{pragma} Export (C, Ada_Method2);
2756 @b{end} Simple_Cpp_Interface;
2757 @end smallexample
2759 @node Interfacing with C++ constructors
2760 @subsection Interfacing with C++ constructors
2761 @noindent
2763 In order to interface with C++ constructors GNAT provides the
2764 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2765 gnat_rm, GNAT Reference Manual}, for additional information).
2766 In this section we present some common uses of C++ constructors
2767 in mixed-languages programs in GNAT.
2769 Let us assume that we need to interface with the following
2770 C++ class:
2772 @smallexample
2773 @b{class} Root @{
2774 @b{public}:
2775   int  a_value;
2776   int  b_value;
2777   @b{virtual} int Get_Value ();
2778   Root();              // Default constructor
2779   Root(int v);         // 1st non-default constructor
2780   Root(int v, int w);  // 2nd non-default constructor
2782 @end smallexample
2784 For this purpose we can write the following package spec (further
2785 information on how to build this spec is available in
2786 @ref{Interfacing with C++ at the Class Level} and
2787 @ref{Generating Ada Bindings for C and C++ headers}).
2789 @smallexample @c ada
2790 @b{with} Interfaces.C; @b{use} Interfaces.C;
2791 @b{package} Pkg_Root @b{is}
2792   @b{type} Root @b{is} @b{tagged} @b{limited} @b{record}
2793      A_Value : int;
2794      B_Value : int;
2795   @b{end} @b{record};
2796   @b{pragma} Import (CPP, Root);
2798   @b{function} Get_Value (Obj : Root) @b{return} int;
2799   @b{pragma} Import (CPP, Get_Value);
2801   @b{function} Constructor @b{return} Root;
2802   @b{pragma} Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2804   @b{function} Constructor (v : Integer) @b{return} Root;
2805   @b{pragma} Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2807   @b{function} Constructor (v, w : Integer) @b{return} Root;
2808   @b{pragma} Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2809 @b{end} Pkg_Root;
2810 @end smallexample
2812 On the Ada side the constructor is represented by a function (whose
2813 name is arbitrary) that returns the classwide type corresponding to
2814 the imported C++ class. Although the constructor is described as a
2815 function, it is typically a procedure with an extra implicit argument
2816 (the object being initialized) at the implementation level. GNAT
2817 issues the appropriate call, whatever it is, to get the object
2818 properly initialized.
2820 Constructors can only appear in the following contexts:
2822 @itemize @bullet
2823 @item
2824 On the right side of an initialization of an object of type @var{T}.
2825 @item
2826 On the right side of an initialization of a record component of type @var{T}.
2827 @item
2828 In an Ada 2005 limited aggregate.
2829 @item
2830 In an Ada 2005 nested limited aggregate.
2831 @item
2832 In an Ada 2005 limited aggregate that initializes an object built in
2833 place by an extended return statement.
2834 @end itemize
2836 @noindent
2837 In a declaration of an object whose type is a class imported from C++,
2838 either the default C++ constructor is implicitly called by GNAT, or
2839 else the required C++ constructor must be explicitly called in the
2840 expression that initializes the object. For example:
2842 @smallexample @c ada
2843   Obj1 : Root;
2844   Obj2 : Root := Constructor;
2845   Obj3 : Root := Constructor (v => 10);
2846   Obj4 : Root := Constructor (30, 40);
2847 @end smallexample
2849 The first two declarations are equivalent: in both cases the default C++
2850 constructor is invoked (in the former case the call to the constructor is
2851 implicit, and in the latter case the call is explicit in the object
2852 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2853 that takes an integer argument, and @code{Obj4} is initialized by the
2854 non-default C++ constructor that takes two integers.
2856 Let us derive the imported C++ class in the Ada side. For example:
2858 @smallexample @c ada
2859   @b{type} DT @b{is} @b{new} Root @b{with} @b{record}
2860      C_Value : Natural := 2009;
2861   @b{end} @b{record};
2862 @end smallexample
2864 In this case the components DT inherited from the C++ side must be
2865 initialized by a C++ constructor, and the additional Ada components
2866 of type DT are initialized by GNAT. The initialization of such an
2867 object is done either by default, or by means of a function returning
2868 an aggregate of type DT, or by means of an extension aggregate.
2870 @smallexample @c ada
2871   Obj5 : DT;
2872   Obj6 : DT := Function_Returning_DT (50);
2873   Obj7 : DT := (Constructor (30,40) @b{with} C_Value => 50);
2874 @end smallexample
2876 The declaration of @code{Obj5} invokes the default constructors: the
2877 C++ default constructor of the parent type takes care of the initialization
2878 of the components inherited from Root, and GNAT takes care of the default
2879 initialization of the additional Ada components of type DT (that is,
2880 @code{C_Value} is initialized to value 2009). The order of invocation of
2881 the constructors is consistent with the order of elaboration required by
2882 Ada and C++. That is, the constructor of the parent type is always called
2883 before the constructor of the derived type.
2885 Let us now consider a record that has components whose type is imported
2886 from C++. For example:
2888 @smallexample @c ada
2889   @b{type} Rec1 @b{is} @b{limited} @b{record}
2890      Data1 : Root := Constructor (10);
2891      Value : Natural := 1000;
2892   @b{end} @b{record};
2894   @b{type} Rec2 (D : Integer := 20) @b{is} @b{limited} @b{record}
2895      Rec   : Rec1;
2896      Data2 : Root := Constructor (D, 30);
2897   @b{end} @b{record};
2898 @end smallexample
2900 The initialization of an object of type @code{Rec2} will call the
2901 non-default C++ constructors specified for the imported components.
2902 For example:
2904 @smallexample @c ada
2905   Obj8 : Rec2 (40);
2906 @end smallexample
2908 Using Ada 2005 we can use limited aggregates to initialize an object
2909 invoking C++ constructors that differ from those specified in the type
2910 declarations. For example:
2912 @smallexample @c ada
2913   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2914                           @b{others} => <>),
2915                   @b{others} => <>);
2916 @end smallexample
2918 The above declaration uses an Ada 2005 limited aggregate to
2919 initialize @code{Obj9}, and the C++ constructor that has two integer
2920 arguments is invoked to initialize the @code{Data1} component instead
2921 of the constructor specified in the declaration of type @code{Rec1}. In
2922 Ada 2005 the box in the aggregate indicates that unspecified components
2923 are initialized using the expression (if any) available in the component
2924 declaration. That is, in this case discriminant @code{D} is initialized
2925 to value @code{20}, @code{Value} is initialized to value 1000, and the
2926 non-default C++ constructor that handles two integers takes care of
2927 initializing component @code{Data2} with values @code{20,30}.
2929 In Ada 2005 we can use the extended return statement to build the Ada
2930 equivalent to C++ non-default constructors. For example:
2932 @smallexample @c ada
2933   @b{function} Constructor (V : Integer) @b{return} Rec2 @b{is}
2934   @b{begin}
2935      @b{return} Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
2936                                    @b{others} => <>),
2937                            @b{others} => <>) @b{do}
2938         --@i{  Further actions required for construction of}
2939         --@i{  objects of type Rec2}
2940         ...
2941      @b{end} @b{record};
2942   @b{end} Constructor;
2943 @end smallexample
2945 In this example the extended return statement construct is used to
2946 build in place the returned object whose components are initialized
2947 by means of a limited aggregate. Any further action associated with
2948 the constructor can be placed inside the construct.
2950 @node Interfacing with C++ at the Class Level
2951 @subsection Interfacing with C++ at the Class Level
2952 @noindent
2953 In this section we demonstrate the GNAT features for interfacing with
2954 C++ by means of an example making use of Ada 2005 abstract interface
2955 types. This example consists of a classification of animals; classes
2956 have been used to model our main classification of animals, and
2957 interfaces provide support for the management of secondary
2958 classifications. We first demonstrate a case in which the types and
2959 constructors are defined on the C++ side and imported from the Ada
2960 side, and latter the reverse case.
2962 The root of our derivation will be the @code{Animal} class, with a
2963 single private attribute (the @code{Age} of the animal), a constructor,
2964 and two public primitives to set and get the value of this attribute.
2966 @smallexample
2967 @b{class} Animal @{
2968  @b{public}:
2969    @b{virtual} void Set_Age (int New_Age);
2970    @b{virtual} int Age ();
2971    Animal() @{Age_Count = 0;@};
2972  @b{private}:
2973    int Age_Count;
2975 @end smallexample
2977 Abstract interface types are defined in C++ by means of classes with pure
2978 virtual functions and no data members. In our example we will use two
2979 interfaces that provide support for the common management of @code{Carnivore}
2980 and @code{Domestic} animals:
2982 @smallexample
2983 @b{class} Carnivore @{
2984 @b{public}:
2985    @b{virtual} int Number_Of_Teeth () = 0;
2988 @b{class} Domestic @{
2989 @b{public}:
2990    @b{virtual void} Set_Owner (char* Name) = 0;
2992 @end smallexample
2994 Using these declarations, we can now say that a @code{Dog} is an animal that is
2995 both Carnivore and Domestic, that is:
2997 @smallexample
2998 @b{class} Dog : Animal, Carnivore, Domestic @{
2999  @b{public}:
3000    @b{virtual} int  Number_Of_Teeth ();
3001    @b{virtual} void Set_Owner (char* Name);
3003    Dog(); // Constructor
3004  @b{private}:
3005    int  Tooth_Count;
3006    char *Owner;
3008 @end smallexample
3010 In the following examples we will assume that the previous declarations are
3011 located in a file named @code{animals.h}. The following package demonstrates
3012 how to import these C++ declarations from the Ada side:
3014 @smallexample @c ada
3015 @b{with} Interfaces.C.Strings; @b{use} Interfaces.C.Strings;
3016 @b{package} Animals @b{is}
3017   @b{type} Carnivore @b{is} @b{limited} interface;
3018   @b{pragma} Convention (C_Plus_Plus, Carnivore);
3019   @b{function} Number_Of_Teeth (X : Carnivore)
3020      @b{return} Natural @b{is} @b{abstract};
3022   @b{type} Domestic @b{is} @b{limited} interface;
3023   @b{pragma} Convention (C_Plus_Plus, Domestic);
3024   @b{procedure} Set_Owner
3025     (X    : @b{in} @b{out} Domestic;
3026      Name : Chars_Ptr) @b{is} @b{abstract};
3028   @b{type} Animal @b{is} @b{tagged} @b{limited} @b{record}
3029     Age : Natural;
3030   @b{end} @b{record};
3031   @b{pragma} Import (C_Plus_Plus, Animal);
3033   @b{procedure} Set_Age (X : @b{in} @b{out} Animal; Age : Integer);
3034   @b{pragma} Import (C_Plus_Plus, Set_Age);
3036   @b{function} Age (X : Animal) @b{return} Integer;
3037   @b{pragma} Import (C_Plus_Plus, Age);
3039   @b{function} New_Animal @b{return} Animal;
3040   @b{pragma} CPP_Constructor (New_Animal);
3041   @b{pragma} Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
3043   @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
3044     Tooth_Count : Natural;
3045     Owner       : String (1 .. 30);
3046   @b{end} @b{record};
3047   @b{pragma} Import (C_Plus_Plus, Dog);
3049   @b{function} Number_Of_Teeth (A : Dog) @b{return} Natural;
3050   @b{pragma} Import (C_Plus_Plus, Number_Of_Teeth);
3052   @b{procedure} Set_Owner (A : @b{in} @b{out} Dog; Name : Chars_Ptr);
3053   @b{pragma} Import (C_Plus_Plus, Set_Owner);
3055   @b{function} New_Dog @b{return} Dog;
3056   @b{pragma} CPP_Constructor (New_Dog);
3057   @b{pragma} Import (CPP, New_Dog, "_ZN3DogC2Ev");
3058 @b{end} Animals;
3059 @end smallexample
3061 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3062 interfacing with these C++ classes is easy. The only requirement is that all
3063 the primitives and components must be declared exactly in the same order in
3064 the two languages.
3066 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3067 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3068 the arguments to the called primitives will be the same as for C++. For the
3069 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3070 to indicate that they have been defined on the C++ side; this is required
3071 because the dispatch table associated with these tagged types will be built
3072 in the C++ side and therefore will not contain the predefined Ada primitives
3073 which Ada would otherwise expect.
3075 As the reader can see there is no need to indicate the C++ mangled names
3076 associated with each subprogram because it is assumed that all the calls to
3077 these primitives will be dispatching calls. The only exception is the
3078 constructor, which must be registered with the compiler by means of
3079 @code{pragma CPP_Constructor} and needs to provide its associated C++
3080 mangled name because the Ada compiler generates direct calls to it.
3082 With the above packages we can now declare objects of type Dog on the Ada side
3083 and dispatch calls to the corresponding subprograms on the C++ side. We can
3084 also extend the tagged type Dog with further fields and primitives, and
3085 override some of its C++ primitives on the Ada side. For example, here we have
3086 a type derivation defined on the Ada side that inherits all the dispatching
3087 primitives of the ancestor from the C++ side.
3089 @smallexample
3090 @b{with} Animals; @b{use} Animals;
3091 @b{package} Vaccinated_Animals @b{is}
3092   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3093   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3094 @b{end} Vaccinated_Animals;
3095 @end smallexample
3097 It is important to note that, because of the ABI compatibility, the programmer
3098 does not need to add any further information to indicate either the object
3099 layout or the dispatch table entry associated with each dispatching operation.
3101 Now let us define all the types and constructors on the Ada side and export
3102 them to C++, using the same hierarchy of our previous example:
3104 @smallexample @c ada
3105 @b{with} Interfaces.C.Strings;
3106 @b{use} Interfaces.C.Strings;
3107 @b{package} Animals @b{is}
3108   @b{type} Carnivore @b{is} @b{limited} interface;
3109   @b{pragma} Convention (C_Plus_Plus, Carnivore);
3110   @b{function} Number_Of_Teeth (X : Carnivore)
3111      @b{return} Natural @b{is} @b{abstract};
3113   @b{type} Domestic @b{is} @b{limited} interface;
3114   @b{pragma} Convention (C_Plus_Plus, Domestic);
3115   @b{procedure} Set_Owner
3116     (X    : @b{in} @b{out} Domestic;
3117      Name : Chars_Ptr) @b{is} @b{abstract};
3119   @b{type} Animal @b{is} @b{tagged} @b{record}
3120     Age : Natural;
3121   @b{end} @b{record};
3122   @b{pragma} Convention (C_Plus_Plus, Animal);
3124   @b{procedure} Set_Age (X : @b{in} @b{out} Animal; Age : Integer);
3125   @b{pragma} Export (C_Plus_Plus, Set_Age);
3127   @b{function} Age (X : Animal) @b{return} Integer;
3128   @b{pragma} Export (C_Plus_Plus, Age);
3130   @b{function} New_Animal @b{return} Animal'Class;
3131   @b{pragma} Export (C_Plus_Plus, New_Animal);
3133   @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
3134     Tooth_Count : Natural;
3135     Owner       : String (1 .. 30);
3136   @b{end} @b{record};
3137   @b{pragma} Convention (C_Plus_Plus, Dog);
3139   @b{function} Number_Of_Teeth (A : Dog) @b{return} Natural;
3140   @b{pragma} Export (C_Plus_Plus, Number_Of_Teeth);
3142   @b{procedure} Set_Owner (A : @b{in} @b{out} Dog; Name : Chars_Ptr);
3143   @b{pragma} Export (C_Plus_Plus, Set_Owner);
3145   @b{function} New_Dog @b{return} Dog'Class;
3146   @b{pragma} Export (C_Plus_Plus, New_Dog);
3147 @b{end} Animals;
3148 @end smallexample
3150 Compared with our previous example the only differences are the use of
3151 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
3152 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3153 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3154 nothing else to be done; as explained above, the only requirement is that all
3155 the primitives and components are declared in exactly the same order.
3157 For completeness, let us see a brief C++ main program that uses the
3158 declarations available in @code{animals.h} (presented in our first example) to
3159 import and use the declarations from the Ada side, properly initializing and
3160 finalizing the Ada run-time system along the way:
3162 @smallexample
3163 @b{#include} "animals.h"
3164 @b{#include} <iostream>
3165 @b{using namespace} std;
3167 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3168 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3169 void Check_Animal (Animal *obj)       @{@dots{}@}
3170 void Check_Dog (Dog *obj)             @{@dots{}@}
3172 @b{extern} "C" @{
3173   void adainit (void);
3174   void adafinal (void);
3175   Dog* new_dog ();
3178 void test ()
3180   Dog *obj = new_dog();  // Ada constructor
3181   Check_Carnivore (obj); // Check secondary DT
3182   Check_Domestic (obj);  // Check secondary DT
3183   Check_Animal (obj);    // Check primary DT
3184   Check_Dog (obj);       // Check primary DT
3187 int main ()
3189   adainit ();  test();  adafinal ();
3190   return 0;
3192 @end smallexample
3194 @node Comparison between GNAT and C/C++ Compilation Models
3195 @section Comparison between GNAT and C/C++ Compilation Models
3197 @noindent
3198 The GNAT model of compilation is close to the C and C++ models. You can
3199 think of Ada specs as corresponding to header files in C. As in C, you
3200 don't need to compile specs; they are compiled when they are used. The
3201 Ada @code{with} is similar in effect to the @code{#include} of a C
3202 header.
3204 One notable difference is that, in Ada, you may compile specs separately
3205 to check them for semantic and syntactic accuracy. This is not always
3206 possible with C headers because they are fragments of programs that have
3207 less specific syntactic or semantic rules.
3209 The other major difference is the requirement for running the binder,
3210 which performs two important functions. First, it checks for
3211 consistency. In C or C++, the only defense against assembling
3212 inconsistent programs lies outside the compiler, in a makefile, for
3213 example. The binder satisfies the Ada requirement that it be impossible
3214 to construct an inconsistent program when the compiler is used in normal
3215 mode.
3217 @cindex Elaboration order control
3218 The other important function of the binder is to deal with elaboration
3219 issues. There are also elaboration issues in C++ that are handled
3220 automatically. This automatic handling has the advantage of being
3221 simpler to use, but the C++ programmer has no control over elaboration.
3222 Where @code{gnatbind} might complain there was no valid order of
3223 elaboration, a C++ compiler would simply construct a program that
3224 malfunctioned at run time.
3226 @node Comparison between GNAT and Conventional Ada Library Models
3227 @section Comparison between GNAT and Conventional Ada Library Models
3229 @noindent
3230 This section is intended for Ada programmers who have
3231 used an Ada compiler implementing the traditional Ada library
3232 model, as described in the Ada Reference Manual.
3234 @cindex GNAT library
3235 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3236 source files themselves acts as the library. Compiling Ada programs does
3237 not generate any centralized information, but rather an object file and
3238 a ALI file, which are of interest only to the binder and linker.
3239 In a traditional system, the compiler reads information not only from
3240 the source file being compiled, but also from the centralized library.
3241 This means that the effect of a compilation depends on what has been
3242 previously compiled. In particular:
3244 @itemize @bullet
3245 @item
3246 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3247 to the version of the unit most recently compiled into the library.
3249 @item
3250 Inlining is effective only if the necessary body has already been
3251 compiled into the library.
3253 @item
3254 Compiling a unit may obsolete other units in the library.
3255 @end itemize
3257 @noindent
3258 In GNAT, compiling one unit never affects the compilation of any other
3259 units because the compiler reads only source files. Only changes to source
3260 files can affect the results of a compilation. In particular:
3262 @itemize @bullet
3263 @item
3264 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3265 to the source version of the unit that is currently accessible to the
3266 compiler.
3268 @item
3269 @cindex Inlining
3270 Inlining requires the appropriate source files for the package or
3271 subprogram bodies to be available to the compiler. Inlining is always
3272 effective, independent of the order in which units are complied.
3274 @item
3275 Compiling a unit never affects any other compilations. The editing of
3276 sources may cause previous compilations to be out of date if they
3277 depended on the source file being modified.
3278 @end itemize
3280 @noindent
3281 The most important result of these differences is that order of compilation
3282 is never significant in GNAT. There is no situation in which one is
3283 required to do one compilation before another. What shows up as order of
3284 compilation requirements in the traditional Ada library becomes, in
3285 GNAT, simple source dependencies; in other words, there is only a set
3286 of rules saying what source files must be present when a file is
3287 compiled.
3290 @c *************************
3291 @node Compiling with gcc
3292 @chapter Compiling with @command{gcc}
3294 @noindent
3295 This chapter discusses how to compile Ada programs using the @command{gcc}
3296 command. It also describes the set of switches
3297 that can be used to control the behavior of the compiler.
3298 @menu
3299 * Compiling Programs::
3300 * Switches for gcc::
3301 * Search Paths and the Run-Time Library (RTL)::
3302 * Order of Compilation Issues::
3303 * Examples::
3304 @end menu
3306 @node Compiling Programs
3307 @section Compiling Programs
3309 @noindent
3310 The first step in creating an executable program is to compile the units
3311 of the program using the @command{gcc} command. You must compile the
3312 following files:
3314 @itemize @bullet
3315 @item
3316 the body file (@file{.adb}) for a library level subprogram or generic
3317 subprogram
3319 @item
3320 the spec file (@file{.ads}) for a library level package or generic
3321 package that has no body
3323 @item
3324 the body file (@file{.adb}) for a library level package
3325 or generic package that has a body
3327 @end itemize
3329 @noindent
3330 You need @emph{not} compile the following files
3332 @itemize @bullet
3334 @item
3335 the spec of a library unit which has a body
3337 @item
3338 subunits
3339 @end itemize
3341 @noindent
3342 because they are compiled as part of compiling related units. GNAT
3343 package specs
3344 when the corresponding body is compiled, and subunits when the parent is
3345 compiled.
3347 @cindex cannot generate code
3348 If you attempt to compile any of these files, you will get one of the
3349 following error messages (where @var{fff} is the name of the file you
3350 compiled):
3352 @smallexample
3353 cannot generate code for file @var{fff} (package spec)
3354 to check package spec, use -gnatc
3356 cannot generate code for file @var{fff} (missing subunits)
3357 to check parent unit, use -gnatc
3359 cannot generate code for file @var{fff} (subprogram spec)
3360 to check subprogram spec, use -gnatc
3362 cannot generate code for file @var{fff} (subunit)
3363 to check subunit, use -gnatc
3364 @end smallexample
3366 @noindent
3367 As indicated by the above error messages, if you want to submit
3368 one of these files to the compiler to check for correct semantics
3369 without generating code, then use the @option{-gnatc} switch.
3371 The basic command for compiling a file containing an Ada unit is
3373 @smallexample
3374 @c $ gcc -c @ovar{switches} @file{file name}
3375 @c Expanding @ovar macro inline (explanation in macro def comments)
3376 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3377 @end smallexample
3379 @noindent
3380 where @var{file name} is the name of the Ada file (usually
3381 having an extension
3382 @file{.ads} for a spec or @file{.adb} for a body).
3383 You specify the
3384 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3385 The result of a successful compilation is an object file, which has the
3386 same name as the source file but an extension of @file{.o} and an Ada
3387 Library Information (ALI) file, which also has the same name as the
3388 source file, but with @file{.ali} as the extension. GNAT creates these
3389 two output files in the current directory, but you may specify a source
3390 file in any directory using an absolute or relative path specification
3391 containing the directory information.
3393 @findex gnat1
3394 @command{gcc} is actually a driver program that looks at the extensions of
3395 the file arguments and loads the appropriate compiler. For example, the
3396 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3397 These programs are in directories known to the driver program (in some
3398 configurations via environment variables you set), but need not be in
3399 your path. The @command{gcc} driver also calls the assembler and any other
3400 utilities needed to complete the generation of the required object
3401 files.
3403 It is possible to supply several file names on the same @command{gcc}
3404 command. This causes @command{gcc} to call the appropriate compiler for
3405 each file. For example, the following command lists two separate
3406 files to be compiled:
3408 @smallexample
3409 $ gcc -c x.adb y.adb
3410 @end smallexample
3412 @noindent
3413 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3414 @file{y.adb}.
3415 The compiler generates two object files @file{x.o} and @file{y.o}
3416 and the two ALI files @file{x.ali} and @file{y.ali}.
3417 Any switches apply to all the files listed,
3419 @node Switches for gcc
3420 @section Switches for @command{gcc}
3422 @noindent
3423 The @command{gcc} command accepts switches that control the
3424 compilation process. These switches are fully described in this section.
3425 First we briefly list all the switches, in alphabetical order, then we
3426 describe the switches in more detail in functionally grouped sections.
3428 More switches exist for GCC than those documented here, especially
3429 for specific targets. However, their use is not recommended as
3430 they may change code generation in ways that are incompatible with
3431 the Ada run-time library, or can cause inconsistencies between
3432 compilation units.
3434 @menu
3435 * Output and Error Message Control::
3436 * Warning Message Control::
3437 * Debugging and Assertion Control::
3438 * Validity Checking::
3439 * Style Checking::
3440 * Run-Time Checks::
3441 * Using gcc for Syntax Checking::
3442 * Using gcc for Semantic Checking::
3443 * Compiling Different Versions of Ada::
3444 * Character Set Control::
3445 * File Naming Control::
3446 * Subprogram Inlining Control::
3447 * Auxiliary Output Control::
3448 * Debugging Control::
3449 * Exception Handling Control::
3450 * Units to Sources Mapping Files::
3451 * Integrated Preprocessing::
3452 * Code Generation Control::
3453 @end menu
3455 @table @option
3456 @c !sort!
3457 @cindex @option{-b} (@command{gcc})
3458 @item -b @var{target}
3459 Compile your program to run on @var{target}, which is the name of a
3460 system configuration. You must have a GNAT cross-compiler built if
3461 @var{target} is not the same as your host system.
3463 @item -B@var{dir}
3464 @cindex @option{-B} (@command{gcc})
3465 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3466 from @var{dir} instead of the default location. Only use this switch
3467 when multiple versions of the GNAT compiler are available.
3468 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3469 GNU Compiler Collection (GCC)}, for further details. You would normally
3470 use the @option{-b} or @option{-V} switch instead.
3472 @item -c
3473 @cindex @option{-c} (@command{gcc})
3474 Compile. Always use this switch when compiling Ada programs.
3476 Note: for some other languages when using @command{gcc}, notably in
3477 the case of C and C++, it is possible to use
3478 use @command{gcc} without a @option{-c} switch to
3479 compile and link in one step. In the case of GNAT, you
3480 cannot use this approach, because the binder must be run
3481 and @command{gcc} cannot be used to run the GNAT binder.
3483 @item -fcallgraph-info@r{[}=su,da@r{]}
3484 @cindex @option{-fcallgraph-info} (@command{gcc})
3485 Makes the compiler output callgraph information for the program, on a
3486 per-file basis. The information is generated in the VCG format.  It can
3487 be decorated with additional, per-node and/or per-edge information, if a
3488 list of comma-separated markers is additionally specified. When the
3489 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3490 marker is specified, the callgraph is decorated with information about
3491 dynamically allocated objects.
3493 @item -fdump-scos
3494 @cindex @option{-fdump-scos} (@command{gcc})
3495 Generates SCO (Source Coverage Obligation) information in the ALI file.
3496 This information is used by advanced coverage tools. See unit @file{SCOs}
3497 in the compiler sources for details in files @file{scos.ads} and
3498 @file{scos.adb}.
3500 @item -fdump-xref
3501 @cindex @option{-fdump-xref} (@command{gcc})
3502 Generates cross reference information in GLI files for C and C++ sources.
3503 The GLI files have the same syntax as the ALI files for Ada, and can be used
3504 for source navigation in IDEs and on the command line using e.g. gnatxref
3505 and the @option{--ext=gli} switch.
3507 @item -flto@r{[}=n@r{]}
3508 @cindex @option{-flto} (@command{gcc})
3509 Enables Link Time Optimization. This switch must be used in conjunction
3510 with the traditional @option{-Ox} switches and instructs the compiler to
3511 defer most optimizations until the link stage. The advantage of this
3512 approach is that the compiler can do a whole-program analysis and choose
3513 the best interprocedural optimization strategy based on a complete view
3514 of the program, instead of a fragmentary view with the usual approach.
3515 This can also speed up the compilation of big programs and reduce the
3516 size of the executable, compared with a traditional per-unit compilation
3517 with inlining across modules enabled by the @option{-gnatn} switch.
3518 The drawback of this approach is that it may require more memory and that
3519 the debugging information generated by -g with it might be hardly usable.
3520 The switch, as well as the accompanying @option{-Ox} switches, must be
3521 specified both for the compilation and the link phases.
3522 If the @var{n} parameter is specified, the optimization and final code
3523 generation at link time are executed using @var{n} parallel jobs by
3524 means of an installed @command{make} program.
3526 @item -fno-inline
3527 @cindex @option{-fno-inline} (@command{gcc})
3528 Suppresses all inlining, even if other optimization or inlining
3529 switches are set.  This includes suppression of inlining that
3530 results from the use of the pragma @code{Inline_Always}.
3531 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3532 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3533 effects if this switch is present.  Note that inlining can also
3534 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3536 @item -fno-inline-functions
3537 @cindex @option{-fno-inline-functions} (@command{gcc})
3538 Suppresses automatic inlining of subprograms, which is enabled
3539 if @option{-O3} is used.
3541 @item -fno-inline-small-functions
3542 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3543 Suppresses automatic inlining of small subprograms, which is enabled
3544 if @option{-O2} is used.
3546 @item -fno-inline-functions-called-once
3547 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3548 Suppresses inlining of subprograms local to the unit and called once
3549 from within it, which is enabled if @option{-O1} is used.
3551 @item -fno-ivopts
3552 @cindex @option{-fno-ivopts} (@command{gcc})
3553 Suppresses high-level loop induction variable optimizations, which are
3554 enabled if @option{-O1} is used. These optimizations are generally
3555 profitable but, for some specific cases of loops with numerous uses
3556 of the iteration variable that follow a common pattern, they may end
3557 up destroying the regularity that could be exploited at a lower level
3558 and thus producing inferior code.
3560 @item -fno-strict-aliasing
3561 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3562 Causes the compiler to avoid assumptions regarding non-aliasing
3563 of objects of different types. See
3564 @ref{Optimization and Strict Aliasing} for details.
3566 @item -fstack-check
3567 @cindex @option{-fstack-check} (@command{gcc})
3568 Activates stack checking.
3569 See @ref{Stack Overflow Checking} for details.
3571 @item -fstack-usage
3572 @cindex @option{-fstack-usage} (@command{gcc})
3573 Makes the compiler output stack usage information for the program, on a
3574 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3576 @item -g
3577 @cindex @option{-g} (@command{gcc})
3578 Generate debugging information. This information is stored in the object
3579 file and copied from there to the final executable file by the linker,
3580 where it can be read by the debugger. You must use the
3581 @option{-g} switch if you plan on using the debugger.
3583 @item -gnat83
3584 @cindex @option{-gnat83} (@command{gcc})
3585 Enforce Ada 83 restrictions.
3587 @item -gnat95
3588 @cindex @option{-gnat95} (@command{gcc})
3589 Enforce Ada 95 restrictions.
3591 Note: for compatibility with some Ada 95 compilers which support only
3592 the @code{overriding} keyword of Ada 2005, the @option{-gnatd.D} switch can
3593 be used along with @option{-gnat95} to achieve a similar effect with GNAT.
3595 @option{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
3596 and handle its associated semantic checks, even in Ada 95 mode.
3598 @item -gnat05
3599 @cindex @option{-gnat05} (@command{gcc})
3600 Allow full Ada 2005 features.
3602 @item -gnat2005
3603 @cindex @option{-gnat2005} (@command{gcc})
3604 Allow full Ada 2005 features (same as @option{-gnat05})
3606 @item -gnat12
3607 @cindex @option{-gnat12} (@command{gcc})
3609 @item -gnat2012
3610 @cindex @option{-gnat2012} (@command{gcc})
3611 Allow full Ada 2012 features (same as @option{-gnat12})
3613 @item -gnata
3614 @cindex @option{-gnata} (@command{gcc})
3615 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3616 activated. Note that these pragmas can also be controlled using the
3617 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3618 It also activates pragmas @code{Check}, @code{Precondition}, and
3619 @code{Postcondition}. Note that these pragmas can also be controlled
3620 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3621 also activates all assertions defined in the RM as aspects: preconditions,
3622 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3623 corresponding pragmas for type invariants and (sub)type predicates are
3624 also activated. The default is that all these assertions are disabled,
3625 and have no effect, other than being checked for syntactic validity, and
3626 in the case of subtype predicates, constructions such as membership tests
3627 still test predicates even if assertions are turned off.
3629 @item -gnatA
3630 @cindex @option{-gnatA} (@command{gcc})
3631 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3632 it will be ignored.
3634 @item -gnatb
3635 @cindex @option{-gnatb} (@command{gcc})
3636 Generate brief messages to @file{stderr} even if verbose mode set.
3638 @item -gnatB
3639 @cindex @option{-gnatB} (@command{gcc})
3640 Assume no invalid (bad) values except for 'Valid attribute use
3641 (@pxref{Validity Checking}).
3643 @item -gnatc
3644 @cindex @option{-gnatc} (@command{gcc})
3645 Check syntax and semantics only (no code generation attempted). When the
3646 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3647 only given to the compiler (after @option{-cargs} or in package Compiler of
3648 the project file, @command{gnatmake} will fail because it will not find the
3649 object file after compilation. If @command{gnatmake} is called with
3650 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3651 Builder of the project file) then @command{gnatmake} will not fail because
3652 it will not look for the object files after compilation, and it will not try
3653 to build and link. This switch may not be given if a previous @code{-gnatR}
3654 switch has been given, since @code{-gnatR} requires that the code generator
3655 be called to complete determination of representation information.
3657 @item -gnatC
3658 @cindex @option{-gnatC} (@command{gcc})
3659 Generate CodePeer intermediate format (no code generation attempted).
3660 This switch will generate an intermediate representation suitable for
3661 use by CodePeer (@file{.scil} files). This switch is not compatible with
3662 code generation (it will, among other things, disable some switches such
3663 as -gnatn, and enable others such as -gnata).
3665 @item -gnatd
3666 @cindex @option{-gnatd} (@command{gcc})
3667 Specify debug options for the compiler. The string of characters after
3668 the @option{-gnatd} specify the specific debug options. The possible
3669 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3670 compiler source file @file{debug.adb} for details of the implemented
3671 debug options. Certain debug options are relevant to applications
3672 programmers, and these are documented at appropriate points in this
3673 users guide.
3675 @item -gnatD
3676 @cindex @option{-gnatD[nn]} (@command{gcc})
3677 Create expanded source files for source level debugging. This switch
3678 also suppress generation of cross-reference information
3679 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3680 -gnatR switch has been given, since these two switches are not compatible.
3682 @item -gnateA
3683 @cindex @option{-gnateA} (@command{gcc})
3684 Check that the actual parameters of a subprogram call are not aliases of one
3685 another. To qualify as aliasing, the actuals must denote objects of a composite
3686 type, their memory locations must be identical or overlapping, and at least one
3687 of the corresponding formal parameters must be of mode OUT or IN OUT.
3689 @smallexample
3690 type Rec_Typ is record
3691    Data : Integer := 0;
3692 end record;
3694 function Self (Val : Rec_Typ) return Rec_Typ is
3695 begin
3696    return Val;
3697 end Self;
3699 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
3700 begin
3701    null;
3702 end Detect_Aliasing;
3704 Obj : Rec_Typ;
3706 Detect_Aliasing (Obj, Obj);
3707 Detect_Aliasing (Obj, Self (Obj));
3708 @end smallexample
3710 In the example above, the first call to @code{Detect_Aliasing} fails with a
3711 @code{Program_Error} at runtime because the actuals for @code{Val_1} and
3712 @code{Val_2} denote the same object. The second call executes without raising
3713 an exception because @code{Self(Obj)} produces an anonymous object which does
3714 not share the memory location of @code{Obj}.
3716 @item -gnatec=@var{path}
3717 @cindex @option{-gnatec} (@command{gcc})
3718 Specify a configuration pragma file
3719 (the equal sign is optional)
3720 (@pxref{The Configuration Pragmas Files}).
3722 @item -gnateC
3723 @cindex @option{-gnateC} (@command{gcc})
3724 Generate CodePeer messages in a compiler-like format. This switch is only
3725 effective if @option{-gnatcC} is also specified and requires an installation
3726 of CodePeer.
3728 @item -gnated
3729 @cindex @option{-gnated} (@command{gcc})
3730 Disable atomic synchronization
3732 @item -gnateDsymbol@r{[}=@var{value}@r{]}
3733 @cindex @option{-gnateD} (@command{gcc})
3734 Defines a symbol, associated with @var{value}, for preprocessing.
3735 (@pxref{Integrated Preprocessing}).
3737 @item -gnateE
3738 @cindex @option{-gnateE} (@command{gcc})
3739 Generate extra information in exception messages. In particular, display
3740 extra column information and the value and range associated with index and
3741 range check failures, and extra column information for access checks.
3742 In cases where the compiler is able to determine at compile time that
3743 a check will fail, it gives a warning, and the extra information is not
3744 produced at run time.
3746 @item -gnatef
3747 @cindex @option{-gnatef} (@command{gcc})
3748 Display full source path name in brief error messages.
3750 @item -gnateF
3751 @cindex @option{-gnateF} (@command{gcc})
3752 Check for overflow on all floating-point operations, including those
3753 for unconstrained predefined types. See description of pragma
3754 @code{Check_Float_Overflow} in GNAT RM.
3756 @item -gnateG
3757 @cindex @option{-gnateG} (@command{gcc})
3758 Save result of preprocessing in a text file.
3760 @item -gnatei@var{nnn}
3761 @cindex @option{-gnatei} (@command{gcc})
3762 Set maximum number of instantiations during compilation of a single unit to
3763 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3764 the rare case when a single unit legitimately exceeds this limit.
3766 @item -gnateI@var{nnn}
3767 @cindex @option{-gnateI} (@command{gcc})
3768 Indicates that the source is a multi-unit source and that the index of the
3769 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3770 to be a valid index in the multi-unit source.
3772 @item -gnatel
3773 @cindex @option{-gnatel} (@command{gcc})
3774 This switch can be used with the static elaboration model to issue info
3775 messages showing
3776 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
3777 are generated. This is useful in diagnosing elaboration circularities
3778 caused by these implicit pragmas when using the static elaboration
3779 model. See See the section in this guide on elaboration checking for
3780 further details. These messages are not generated by default, and are
3781 intended only for temporary use when debugging circularity problems.
3783 @item -gnateL
3784 @cindex @option{-gnatel} (@command{gcc})
3785 This switch turns off the info messages about implicit elaboration pragmas.
3787 @item -gnatem=@var{path}
3788 @cindex @option{-gnatem} (@command{gcc})
3789 Specify a mapping file
3790 (the equal sign is optional)
3791 (@pxref{Units to Sources Mapping Files}).
3793 @item -gnatep=@var{file}
3794 @cindex @option{-gnatep} (@command{gcc})
3795 Specify a preprocessing data file
3796 (the equal sign is optional)
3797 (@pxref{Integrated Preprocessing}).
3799 @item -gnateP
3800 @cindex @option{-gnateP} (@command{gcc})
3801 Turn categorization dependency errors into warnings.
3802 Ada requires that units that WITH one another have compatible categories, for
3803 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3804 these errors become warnings (which can be ignored, or suppressed in the usual
3805 manner). This can be useful in some specialized circumstances such as the
3806 temporary use of special test software.
3808 @item -gnateS
3809 @cindex @option{-gnateS} (@command{gcc})
3810 Synonym of @option{-fdump-scos}, kept for backwards compatibility.
3812 @item -gnatet=@var{path}
3813 @cindex @option{-gnatet=file} (@command{gcc})
3814 Generate target dependent information. The format of the output file is
3815 described in the section about switch @option{-gnateT}.
3817 @item -gnateT=@var{path}
3818 @cindex @option{-gnateT} (@command{gcc})
3819 Read target dependent information, such as endianness or sizes and alignments
3820 of base type. If this switch is passed, the default target dependent
3821 information of the compiler is replaced by the one read from the input file.
3822 This is used by tools other than the compiler, e.g. to do
3823 semantic analysis of programs that will run on some other target than
3824 the machine on which the tool is run.
3826 The following target dependent values should be defined,
3827 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3828 positive integer value, and fields marked with a question mark are
3829 boolean fields, where a value of 0 is False, and a value of 1 is True:
3831 @smallexample
3832 Bits_BE                    : Nat; -- Bits stored big-endian?
3833 Bits_Per_Unit              : Pos; -- Bits in a storage unit
3834 Bits_Per_Word              : Pos; -- Bits in a word
3835 Bytes_BE                   : Nat; -- Bytes stored big-endian?
3836 Char_Size                  : Pos; -- Standard.Character'Size
3837 Double_Float_Alignment     : Nat; -- Alignment of double float
3838 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
3839 Double_Size                : Pos; -- Standard.Long_Float'Size
3840 Float_Size                 : Pos; -- Standard.Float'Size
3841 Float_Words_BE             : Nat; -- Float words stored big-endian?
3842 Int_Size                   : Pos; -- Standard.Integer'Size
3843 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
3844 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
3845 Long_Size                  : Pos; -- Standard.Long_Integer'Size
3846 Maximum_Alignment          : Pos; -- Maximum permitted alignment
3847 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
3848 Pointer_Size               : Pos; -- System.Address'Size
3849 Short_Enums                : Nat; -- Short foreign convention enums?
3850 Short_Size                 : Pos; -- Standard.Short_Integer'Size
3851 Strict_Alignment           : Nat; -- Strict alignment?
3852 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3853 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
3854 Words_BE                   : Nat; -- Words stored big-endian?
3855 @end smallexample
3857 The format of the input file is as follows. First come the values of
3858 the variables defined above, with one line per value:
3860 @smallexample
3861 name  value
3862 @end smallexample
3864 where @code{name} is the name of the parameter, spelled out in full,
3865 and cased as in the above list, and @code{value} is an unsigned decimal
3866 integer. Two or more blanks separates the name from the value.
3868 All the variables must be present, in alphabetical order (i.e. the
3869 same order as the list above).
3871 Then there is a blank line to separate the two parts of the file. Then
3872 come the lines showing the floating-point types to be registered, with
3873 one line per registered mode:
3875 @smallexample
3876 name  digs float_rep size alignment
3877 @end smallexample
3879 where @code{name} is the string name of the type (which can have
3880 single spaces embedded in the name (e.g. long double), @code{digs} is
3881 the number of digits for the floating-point type, @code{float_rep} is
3882 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3883 AAMP), @code{size} is the size in bits, @code{alignment} is the
3884 alignment in bits. The name is followed by at least two blanks, fields
3885 are separated by at least one blank, and a LF character immediately
3886 follows the alignment field.
3888 Here is an example of a target parameterization file:
3890 @smallexample
3891 Bits_BE                       0
3892 Bits_Per_Unit                 8
3893 Bits_Per_Word                64
3894 Bytes_BE                      0
3895 Char_Size                     8
3896 Double_Float_Alignment        0
3897 Double_Scalar_Alignment       0
3898 Double_Size                  64
3899 Float_Size                   32
3900 Float_Words_BE                0
3901 Int_Size                     64
3902 Long_Double_Size            128
3903 Long_Long_Size               64
3904 Long_Size                    64
3905 Maximum_Alignment            16
3906 Max_Unaligned_Field          64
3907 Pointer_Size                 64
3908 Short_Size                   16
3909 Strict_Alignment              0
3910 System_Allocator_Alignment   16
3911 Wchar_T_Size                 32
3912 Words_BE                      0
3914 float         15  I  64  64
3915 double        15  I  64  64
3916 long double   18  I  80 128
3917 TF            33  I 128 128
3918 @end smallexample
3920 @item -gnateu
3921 @cindex @option{-gnateu} (@command{gcc})
3922 Ignore unrecognized validity, warning, and style switches that
3923 appear after this switch is given. This may be useful when
3924 compiling sources developed on a later version of the compiler
3925 with an earlier version. Of course the earlier version must
3926 support this switch.
3928 @item -gnateV
3929 @cindex @option{-gnateV} (@command{gcc})
3930 Check that all actual parameters of a subprogram call are valid according to
3931 the rules of validity checking (@pxref{Validity Checking}).
3933 @item -gnateY
3934 @cindex @option{-gnateY} (@command{gcc})
3935 Ignore all STYLE_CHECKS pragmas. Full legality checks
3936 are still carried out, but the pragmas have no effect
3937 on what style checks are active. This allows all style
3938 checking options to be controlled from the command line.
3940 @item -gnatE
3941 @cindex @option{-gnatE} (@command{gcc})
3942 Full dynamic elaboration checks.
3944 @item -gnatf
3945 @cindex @option{-gnatf} (@command{gcc})
3946 Full errors. Multiple errors per line, all undefined references, do not
3947 attempt to suppress cascaded errors.
3949 @item -gnatF
3950 @cindex @option{-gnatF} (@command{gcc})
3951 Externals names are folded to all uppercase.
3953 @item -gnatg
3954 @cindex @option{-gnatg} (@command{gcc})
3955 Internal GNAT implementation mode. This should not be used for
3956 applications programs, it is intended only for use by the compiler
3957 and its run-time library. For documentation, see the GNAT sources.
3958 Note that @option{-gnatg} implies
3959 @option{-gnatw.ge} and
3960 @option{-gnatyg}
3961 so that all standard warnings and all standard style options are turned on.
3962 All warnings and style messages are treated as errors.
3964 @item -gnatG=nn
3965 @cindex @option{-gnatG[nn]} (@command{gcc})
3966 List generated expanded code in source form.
3968 @item -gnath
3969 @cindex @option{-gnath} (@command{gcc})
3970 Output usage information. The output is written to @file{stdout}.
3972 @item -gnati@var{c}
3973 @cindex @option{-gnati} (@command{gcc})
3974 Identifier character set
3975 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3976 For details of the possible selections for @var{c},
3977 see @ref{Character Set Control}.
3979 @item -gnatI
3980 @cindex @option{-gnatI} (@command{gcc})
3981 Ignore representation clauses. When this switch is used,
3982 representation clauses are treated as comments. This is useful
3983 when initially porting code where you want to ignore rep clause
3984 problems, and also for compiling foreign code (particularly
3985 for use with ASIS). The representation clauses that are ignored
3986 are: enumeration_representation_clause, record_representation_clause,
3987 and attribute_definition_clause for the following attributes:
3988 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
3989 Object_Size, Size, Small, Stream_Size, and Value_Size.
3990 Note that this option should be used only for compiling -- the
3991 code is likely to malfunction at run time.
3993 Note that when @code{-gnatct} is used to generate trees for input
3994 into @code{ASIS} tools, these representation clauses are removed
3995 from the tree and ignored. This means that the tool will not see them.
3997 @item -gnatjnn
3998 @cindex @option{-gnatjnn} (@command{gcc})
3999 Reformat error messages to fit on nn character lines
4001 @item -gnatk=@var{n}
4002 @cindex @option{-gnatk} (@command{gcc})
4003 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
4005 @item -gnatl
4006 @cindex @option{-gnatl} (@command{gcc})
4007 Output full source listing with embedded error messages.
4009 @item -gnatL
4010 @cindex @option{-gnatL} (@command{gcc})
4011 Used in conjunction with -gnatG or -gnatD to intersperse original
4012 source lines (as comment lines with line numbers) in the expanded
4013 source output.
4015 @item -gnatm=@var{n}
4016 @cindex @option{-gnatm} (@command{gcc})
4017 Limit number of detected error or warning messages to @var{n}
4018 where @var{n} is in the range 1..999999. The default setting if
4019 no switch is given is 9999. If the number of warnings reaches this
4020 limit, then a message is output and further warnings are suppressed,
4021 but the compilation is continued. If the number of error messages
4022 reaches this limit, then a message is output and the compilation
4023 is abandoned. The equal sign here is optional. A value of zero
4024 means that no limit applies.
4026 @item -gnatn[12]
4027 @cindex @option{-gnatn} (@command{gcc})
4028 Activate inlining for subprograms for which pragma @code{Inline} is
4029 specified. This inlining is performed by the GCC back-end. An optional
4030 digit sets the inlining level: 1 for moderate inlining across modules
4031 or 2 for full inlining across modules. If no inlining level is specified,
4032 the compiler will pick it based on the optimization level.
4034 @item -gnatN
4035 @cindex @option{-gnatN} (@command{gcc})
4036 Activate front end inlining for subprograms for which
4037 pragma @code{Inline} is specified. This inlining is performed
4038 by the front end and will be visible in the
4039 @option{-gnatG} output.
4041 When using a gcc-based back end (in practice this means using any version
4042 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4043 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4044 Historically front end inlining was more extensive than the gcc back end
4045 inlining, but that is no longer the case.
4047 @item -gnato0
4048 @cindex @option{-gnato0} (@command{gcc})
4049 Suppresses overflow checking. This causes the behavior of the compiler to
4050 match the default for older versions where overflow checking was suppressed
4051 by default. This is equivalent to having
4052 @code{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
4054 @item -gnato??
4055 @cindex @option{-gnato??} (@command{gcc})
4056 Set default mode for handling generation of code to avoid intermediate
4057 arithmetic overflow. Here `@code{??}' is two digits, a
4058 single digit, or nothing. Each digit is one of the digits `@code{1}'
4059 through `@code{3}':
4061 @itemize @bullet
4062 @item   @code{1}:
4063 all intermediate overflows checked against base type (@code{STRICT})
4064 @item   @code{2}:
4065 minimize intermediate overflows (@code{MINIMIZED})
4066 @item   @code{3}:
4067 eliminate intermediate overflows (@code{ELIMINATED})
4068 @end itemize
4070 If only one digit appears then it applies to all
4071 cases; if two digits are given, then the first applies outside
4072 assertions, and the second within assertions.
4074 If no digits follow the @option{-gnato}, then it is equivalent to
4075 @option{-gnato11},
4076 causing all intermediate overflows to be handled in strict mode.
4078 This switch also causes arithmetic overflow checking to be performed
4079 (as though @code{pragma Unsuppress (Overflow_Mode)} had been specified.
4081 The default if no option @option{-gnato} is given is that overflow handling
4082 is in @code{STRICT} mode (computations done using the base type), and that
4083 overflow checking is enabled.
4085 Note that division by zero is a separate check that is not
4086 controlled by this switch (division by zero checking is on by default).
4088 See also @ref{Specifying the Desired Mode}.
4090 @item -gnatp
4091 @cindex @option{-gnatp} (@command{gcc})
4092 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4093 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4095 @item -gnat-p
4096 @cindex @option{-gnat-p} (@command{gcc})
4097 Cancel effect of previous @option{-gnatp} switch.
4099 @item -gnatP
4100 @cindex @option{-gnatP} (@command{gcc})
4101 Enable polling. This is required on some systems (notably Windows NT) to
4102 obtain asynchronous abort and asynchronous transfer of control capability.
4103 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4104 details.
4106 @item -gnatq
4107 @cindex @option{-gnatq} (@command{gcc})
4108 Don't quit. Try semantics, even if parse errors.
4110 @item -gnatQ
4111 @cindex @option{-gnatQ} (@command{gcc})
4112 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4113 Note that code generation is still suppressed in the presence of any
4114 errors, so even with @option{-gnatQ} no object file is generated.
4116 @item -gnatr
4117 @cindex @option{-gnatr} (@command{gcc})
4118 Treat pragma Restrictions as Restriction_Warnings.
4120 @item -gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}
4121 @cindex @option{-gnatR} (@command{gcc})
4122 Output representation information for declared types and objects.
4123 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4124 been given, since these two switches are not compatible.
4126 @item -gnatRm[s]
4127 Output convention and parameter passing mechanisms for all subprograms.
4129 @item -gnats
4130 @cindex @option{-gnats} (@command{gcc})
4131 Syntax check only.
4133 @item -gnatS
4134 @cindex @option{-gnatS} (@command{gcc})
4135 Print package Standard.
4137 @item -gnatt
4138 @cindex @option{-gnatt} (@command{gcc})
4139 Generate tree output file.
4141 @item -gnatT@var{nnn}
4142 @cindex @option{-gnatT} (@command{gcc})
4143 All compiler tables start at @var{nnn} times usual starting size.
4145 @item -gnatu
4146 @cindex @option{-gnatu} (@command{gcc})
4147 List units for this compilation.
4149 @item -gnatU
4150 @cindex @option{-gnatU} (@command{gcc})
4151 Tag all error messages with the unique string ``error:''
4153 @item -gnatv
4154 @cindex @option{-gnatv} (@command{gcc})
4155 Verbose mode. Full error output with source lines to @file{stdout}.
4157 @item -gnatV
4158 @cindex @option{-gnatV} (@command{gcc})
4159 Control level of validity checking (@pxref{Validity Checking}).
4161 @item -gnatw@var{xxx}
4162 @cindex @option{-gnatw} (@command{gcc})
4163 Warning mode where
4164 @var{xxx} is a string of option letters that denotes
4165 the exact warnings that
4166 are enabled or disabled (@pxref{Warning Message Control}).
4168 @item -gnatW@var{e}
4169 @cindex @option{-gnatW} (@command{gcc})
4170 Wide character encoding method
4171 (@var{e}=n/h/u/s/e/8).
4173 @item -gnatx
4174 @cindex @option{-gnatx} (@command{gcc})
4175 Suppress generation of cross-reference information.
4177 @item -gnatX
4178 @cindex @option{-gnatX} (@command{gcc})
4179 Enable GNAT implementation extensions and latest Ada version.
4181 @item -gnaty
4182 @cindex @option{-gnaty} (@command{gcc})
4183 Enable built-in style checks (@pxref{Style Checking}).
4185 @item -gnatz@var{m}
4186 @cindex @option{-gnatz} (@command{gcc})
4187 Distribution stub generation and compilation
4188 (@var{m}=r/c for receiver/caller stubs).
4190 @item -I@var{dir}
4191 @cindex @option{-I} (@command{gcc})
4192 @cindex RTL
4193 Direct GNAT to search the @var{dir} directory for source files needed by
4194 the current compilation
4195 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4197 @item -I-
4198 @cindex @option{-I-} (@command{gcc})
4199 @cindex RTL
4200 Except for the source file named in the command line, do not look for source
4201 files in the directory containing the source file named in the command line
4202 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4204 @item -mbig-switch
4205 @cindex @option{-mbig-switch} (@command{gcc})
4206 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4207 This standard gcc switch causes the compiler to use larger offsets in its
4208 jump table representation for @code{case} statements.
4209 This may result in less efficient code, but is sometimes necessary
4210 (for example on HP-UX targets)
4211 @cindex HP-UX and @option{-mbig-switch} option
4212 in order to compile large and/or nested @code{case} statements.
4214 @item -o @var{file}
4215 @cindex @option{-o} (@command{gcc})
4216 This switch is used in @command{gcc} to redirect the generated object file
4217 and its associated ALI file. Beware of this switch with GNAT, because it may
4218 cause the object file and ALI file to have different names which in turn
4219 may confuse the binder and the linker.
4221 @item -nostdinc
4222 @cindex @option{-nostdinc} (@command{gcc})
4223 Inhibit the search of the default location for the GNAT Run Time
4224 Library (RTL) source files.
4226 @item -nostdlib
4227 @cindex @option{-nostdlib} (@command{gcc})
4228 Inhibit the search of the default location for the GNAT Run Time
4229 Library (RTL) ALI files.
4231 @c @item -O@ovar{n}
4232 @c Expanding @ovar macro inline (explanation in macro def comments)
4233 @item -O@r{[}@var{n}@r{]}
4234 @cindex @option{-O} (@command{gcc})
4235 @var{n} controls the optimization level.
4237 @table @asis
4238 @item n = 0
4239 No optimization, the default setting if no @option{-O} appears
4241 @item n = 1
4242 Normal optimization, the default if you specify @option{-O} without
4243 an operand. A good compromise between code quality and compilation
4244 time.
4246 @item n = 2
4247 Extensive optimization, may improve execution time, possibly at the cost of
4248 substantially increased compilation time.
4250 @item n = 3
4251 Same as @option{-O2}, and also includes inline expansion for small subprograms
4252 in the same unit.
4254 @item n = s
4255 Optimize space usage
4256 @end table
4258 @noindent
4259 See also @ref{Optimization Levels}.
4262 @item -pass-exit-codes
4263 @cindex @option{-pass-exit-codes} (@command{gcc})
4264 Catch exit codes from the compiler and use the most meaningful as
4265 exit status.
4267 @item --RTS=@var{rts-path}
4268 @cindex @option{--RTS} (@command{gcc})
4269 Specifies the default location of the runtime library. Same meaning as the
4270 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4272 @item -S
4273 @cindex @option{-S} (@command{gcc})
4274 Used in place of @option{-c} to
4275 cause the assembler source file to be
4276 generated, using @file{.s} as the extension,
4277 instead of the object file.
4278 This may be useful if you need to examine the generated assembly code.
4280 @item -fverbose-asm
4281 @cindex @option{-fverbose-asm} (@command{gcc})
4282 Used in conjunction with @option{-S}
4283 to cause the generated assembly code file to be annotated with variable
4284 names, making it significantly easier to follow.
4286 @item -v
4287 @cindex @option{-v} (@command{gcc})
4288 Show commands generated by the @command{gcc} driver. Normally used only for
4289 debugging purposes or if you need to be sure what version of the
4290 compiler you are executing.
4292 @item -V @var{ver}
4293 @cindex @option{-V} (@command{gcc})
4294 Execute @var{ver} version of the compiler. This is the @command{gcc}
4295 version, not the GNAT version.
4297 @item -w
4298 @cindex @option{-w} (@command{gcc})
4299 Turn off warnings generated by the back end of the compiler. Use of
4300 this switch also causes the default for front end warnings to be set
4301 to suppress (as though @option{-gnatws} had appeared at the start of
4302 the options).
4304 @end table
4306 @c Combining qualifiers does not work on VMS
4307 You may combine a sequence of GNAT switches into a single switch. For
4308 example, the combined switch
4310 @cindex Combining GNAT switches
4311 @smallexample
4312 -gnatofi3
4313 @end smallexample
4315 @noindent
4316 is equivalent to specifying the following sequence of switches:
4318 @smallexample
4319 -gnato -gnatf -gnati3
4320 @end smallexample
4322 @noindent
4323 The following restrictions apply to the combination of switches
4324 in this manner:
4326 @itemize @bullet
4327 @item
4328 The switch @option{-gnatc} if combined with other switches must come
4329 first in the string.
4331 @item
4332 The switch @option{-gnats} if combined with other switches must come
4333 first in the string.
4335 @item
4336 The switches
4338 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4339 switches, and only one of them may appear in the command line.
4341 @item
4342 The switch @option{-gnat-p} may not be combined with any other switch.
4344 @item
4345 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4346 switch), then all further characters in the switch are interpreted
4347 as style modifiers (see description of @option{-gnaty}).
4349 @item
4350 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4351 switch), then all further characters in the switch are interpreted
4352 as debug flags (see description of @option{-gnatd}).
4354 @item
4355 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4356 switch), then all further characters in the switch are interpreted
4357 as warning mode modifiers (see description of @option{-gnatw}).
4359 @item
4360 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4361 switch), then all further characters in the switch are interpreted
4362 as validity checking options (@pxref{Validity Checking}).
4364 @item
4365 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4366 a combined list of options.
4367 @end itemize
4369 @node Output and Error Message Control
4370 @subsection Output and Error Message Control
4371 @findex stderr
4373 @noindent
4374 The standard default format for error messages is called ``brief format''.
4375 Brief format messages are written to @file{stderr} (the standard error
4376 file) and have the following form:
4378 @smallexample
4379 e.adb:3:04: Incorrect spelling of keyword "function"
4380 e.adb:4:20: ";" should be "is"
4381 @end smallexample
4383 @noindent
4384 The first integer after the file name is the line number in the file,
4385 and the second integer is the column number within the line.
4386 @code{GPS} can parse the error messages
4387 and point to the referenced character.
4388 The following switches provide control over the error message
4389 format:
4391 @table @option
4392 @c !sort!
4393 @item -gnatv
4394 @cindex @option{-gnatv} (@command{gcc})
4395 @findex stdout
4396 The v stands for verbose.
4397 The effect of this setting is to write long-format error
4398 messages to @file{stdout} (the standard output file.
4399 The same program compiled with the
4400 @option{-gnatv} switch would generate:
4402 @smallexample
4403 @cartouche
4404 3. funcion X (Q : Integer)
4405    |
4406 >>> Incorrect spelling of keyword "function"
4407 4. return Integer;
4408                  |
4409 >>> ";" should be "is"
4410 @end cartouche
4411 @end smallexample
4413 @noindent
4414 The vertical bar indicates the location of the error, and the @samp{>>>}
4415 prefix can be used to search for error messages. When this switch is
4416 used the only source lines output are those with errors.
4418 @item -gnatl
4419 @cindex @option{-gnatl} (@command{gcc})
4420 The @code{l} stands for list.
4421 This switch causes a full listing of
4422 the file to be generated. In the case where a body is
4423 compiled, the corresponding spec is also listed, along
4424 with any subunits. Typical output from compiling a package
4425 body @file{p.adb} might look like:
4427 @smallexample @c ada
4428 @cartouche
4429  Compiling: p.adb
4431      1. @b{package} @b{body} p @b{is}
4432      2.    @b{procedure} a;
4433      3.    @b{procedure} a @b{is} @b{separate};
4434      4. @b{begin}
4435      5.    @b{null}
4436                |
4437         >>> missing ";"
4439      6. @b{end};
4441 Compiling: p.ads
4443      1. @b{package} p @b{is}
4444      2.    @b{pragma} Elaborate_Body
4445                                 |
4446         >>> missing ";"
4448      3. @b{end} p;
4450 Compiling: p-a.adb
4452      1. @b{separate} p
4453                 |
4454         >>> missing "("
4456      2. @b{procedure} a @b{is}
4457      3. @b{begin}
4458      4.    @b{null}
4459                |
4460         >>> missing ";"
4462      5. @b{end};
4463 @end cartouche
4464 @end smallexample
4466 @noindent
4467 @findex stderr
4468 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4469 standard output is redirected, a brief summary is written to
4470 @file{stderr} (standard error) giving the number of error messages and
4471 warning messages generated.
4473 @item -gnatl=file
4474 @cindex @option{-gnatl=fname} (@command{gcc})
4475 This has the same effect as @option{-gnatl} except that the output is
4476 written to a file instead of to standard output. If the given name
4477 @file{fname} does not start with a period, then it is the full name
4478 of the file to be written. If @file{fname} is an extension, it is
4479 appended to the name of the file being compiled. For example, if
4480 file @file{xyz.adb} is compiled with @option{-gnatl=.lst},
4481 then the output is written to file xyz.adb.lst.
4483 @item -gnatU
4484 @cindex @option{-gnatU} (@command{gcc})
4485 This switch forces all error messages to be preceded by the unique
4486 string ``error:''. This means that error messages take a few more
4487 characters in space, but allows easy searching for and identification
4488 of error messages.
4490 @item -gnatb
4491 @cindex @option{-gnatb} (@command{gcc})
4492 The @code{b} stands for brief.
4493 This switch causes GNAT to generate the
4494 brief format error messages to @file{stderr} (the standard error
4495 file) as well as the verbose
4496 format message or full listing (which as usual is written to
4497 @file{stdout} (the standard output file).
4499 @item -gnatm=@var{n}
4500 @cindex @option{-gnatm} (@command{gcc})
4501 The @code{m} stands for maximum.
4502 @var{n} is a decimal integer in the
4503 range of 1 to 999999 and limits the number of error or warning
4504 messages to be generated. For example, using
4505 @option{-gnatm2} might yield
4507 @smallexample
4508 e.adb:3:04: Incorrect spelling of keyword "function"
4509 e.adb:5:35: missing ".."
4510 fatal error: maximum number of errors detected
4511 compilation abandoned
4512 @end smallexample
4514 @noindent
4515 The default setting if
4516 no switch is given is 9999. If the number of warnings reaches this
4517 limit, then a message is output and further warnings are suppressed,
4518 but the compilation is continued. If the number of error messages
4519 reaches this limit, then a message is output and the compilation
4520 is abandoned. A value of zero means that no limit applies.
4522 @noindent
4523 Note that the equal sign is optional, so the switches
4524 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4526 @item -gnatf
4527 @cindex @option{-gnatf} (@command{gcc})
4528 @cindex Error messages, suppressing
4529 The @code{f} stands for full.
4530 Normally, the compiler suppresses error messages that are likely to be
4531 redundant. This switch causes all error
4532 messages to be generated. In particular, in the case of
4533 references to undefined variables. If a given variable is referenced
4534 several times, the normal format of messages is
4535 @smallexample
4536 e.adb:7:07: "V" is undefined (more references follow)
4537 @end smallexample
4539 @noindent
4540 where the parenthetical comment warns that there are additional
4541 references to the variable @code{V}. Compiling the same program with the
4542 @option{-gnatf} switch yields
4544 @smallexample
4545 e.adb:7:07: "V" is undefined
4546 e.adb:8:07: "V" is undefined
4547 e.adb:8:12: "V" is undefined
4548 e.adb:8:16: "V" is undefined
4549 e.adb:9:07: "V" is undefined
4550 e.adb:9:12: "V" is undefined
4551 @end smallexample
4553 @noindent
4554 The @option{-gnatf} switch also generates additional information for
4555 some error messages.  Some examples are:
4557 @itemize @bullet
4558 @item
4559 Details on possibly non-portable unchecked conversion
4560 @item
4561 List possible interpretations for ambiguous calls
4562 @item
4563 Additional details on incorrect parameters
4564 @end itemize
4566 @item -gnatjnn
4567 @cindex @option{-gnatjnn} (@command{gcc})
4568 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4569 with continuation lines are treated as though the continuation lines were
4570 separate messages (and so a warning with two continuation lines counts as
4571 three warnings, and is listed as three separate messages).
4573 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4574 messages are output in a different manner. A message and all its continuation
4575 lines are treated as a unit, and count as only one warning or message in the
4576 statistics totals. Furthermore, the message is reformatted so that no line
4577 is longer than nn characters.
4579 @item -gnatq
4580 @cindex @option{-gnatq} (@command{gcc})
4581 The @code{q} stands for quit (really ``don't quit'').
4582 In normal operation mode, the compiler first parses the program and
4583 determines if there are any syntax errors. If there are, appropriate
4584 error messages are generated and compilation is immediately terminated.
4585 This switch tells
4586 GNAT to continue with semantic analysis even if syntax errors have been
4587 found. This may enable the detection of more errors in a single run. On
4588 the other hand, the semantic analyzer is more likely to encounter some
4589 internal fatal error when given a syntactically invalid tree.
4591 @item -gnatQ
4592 @cindex @option{-gnatQ} (@command{gcc})
4593 In normal operation mode, the @file{ALI} file is not generated if any
4594 illegalities are detected in the program. The use of @option{-gnatQ} forces
4595 generation of the @file{ALI} file. This file is marked as being in
4596 error, so it cannot be used for binding purposes, but it does contain
4597 reasonably complete cross-reference information, and thus may be useful
4598 for use by tools (e.g., semantic browsing tools or integrated development
4599 environments) that are driven from the @file{ALI} file. This switch
4600 implies @option{-gnatq}, since the semantic phase must be run to get a
4601 meaningful ALI file.
4603 In addition, if @option{-gnatt} is also specified, then the tree file is
4604 generated even if there are illegalities. It may be useful in this case
4605 to also specify @option{-gnatq} to ensure that full semantic processing
4606 occurs. The resulting tree file can be processed by ASIS, for the purpose
4607 of providing partial information about illegal units, but if the error
4608 causes the tree to be badly malformed, then ASIS may crash during the
4609 analysis.
4611 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4612 being in error, @command{gnatmake} will attempt to recompile the source when it
4613 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4615 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4616 since ALI files are never generated if @option{-gnats} is set.
4618 @end table
4620 @node Warning Message Control
4621 @subsection Warning Message Control
4622 @cindex Warning messages
4623 @noindent
4624 In addition to error messages, which correspond to illegalities as defined
4625 in the Ada Reference Manual, the compiler detects two kinds of warning
4626 situations.
4628 First, the compiler considers some constructs suspicious and generates a
4629 warning message to alert you to a possible error. Second, if the
4630 compiler detects a situation that is sure to raise an exception at
4631 run time, it generates a warning message. The following shows an example
4632 of warning messages:
4633 @smallexample
4634 e.adb:4:24: warning: creation of object may raise Storage_Error
4635 e.adb:10:17: warning: static value out of range
4636 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4637 @end smallexample
4639 @noindent
4640 GNAT considers a large number of situations as appropriate
4641 for the generation of warning messages. As always, warnings are not
4642 definite indications of errors. For example, if you do an out-of-range
4643 assignment with the deliberate intention of raising a
4644 @code{Constraint_Error} exception, then the warning that may be
4645 issued does not indicate an error. Some of the situations for which GNAT
4646 issues warnings (at least some of the time) are given in the following
4647 list. This list is not complete, and new warnings are often added to
4648 subsequent versions of GNAT. The list is intended to give a general idea
4649 of the kinds of warnings that are generated.
4651 @itemize @bullet
4652 @item
4653 Possible infinitely recursive calls
4655 @item
4656 Out-of-range values being assigned
4658 @item
4659 Possible order of elaboration problems
4661 @item
4662 Size not a multiple of alignment for a record type
4664 @item
4665 Assertions (pragma Assert) that are sure to fail
4667 @item
4668 Unreachable code
4670 @item
4671 Address clauses with possibly unaligned values, or where an attempt is
4672 made to overlay a smaller variable with a larger one.
4674 @item
4675 Fixed-point type declarations with a null range
4677 @item
4678 Direct_IO or Sequential_IO instantiated with a type that has access values
4680 @item
4681 Variables that are never assigned a value
4683 @item
4684 Variables that are referenced before being initialized
4686 @item
4687 Task entries with no corresponding @code{accept} statement
4689 @item
4690 Duplicate accepts for the same task entry in a @code{select}
4692 @item
4693 Objects that take too much storage
4695 @item
4696 Unchecked conversion between types of differing sizes
4698 @item
4699 Missing @code{return} statement along some execution path in a function
4701 @item
4702 Incorrect (unrecognized) pragmas
4704 @item
4705 Incorrect external names
4707 @item
4708 Allocation from empty storage pool
4710 @item
4711 Potentially blocking operation in protected type
4713 @item
4714 Suspicious parenthesization of expressions
4716 @item
4717 Mismatching bounds in an aggregate
4719 @item
4720 Attempt to return local value by reference
4722 @item
4723 Premature instantiation of a generic body
4725 @item
4726 Attempt to pack aliased components
4728 @item
4729 Out of bounds array subscripts
4731 @item
4732 Wrong length on string assignment
4734 @item
4735 Violations of style rules if style checking is enabled
4737 @item
4738 Unused @code{with} clauses
4740 @item
4741 @code{Bit_Order} usage that does not have any effect
4743 @item
4744 @code{Standard.Duration} used to resolve universal fixed expression
4746 @item
4747 Dereference of possibly null value
4749 @item
4750 Declaration that is likely to cause storage error
4752 @item
4753 Internal GNAT unit @code{with}'ed by application unit
4755 @item
4756 Values known to be out of range at compile time
4758 @item
4759 Unreferenced or unmodified variables. Note that a special
4760 exemption applies to variables which contain any of the substrings
4761 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
4762 are considered likely to be intentionally used in a situation where
4763 otherwise a warning would be given, so warnings of this kind are
4764 always suppressed for such variables.
4766 @item
4767 Address overlays that could clobber memory
4769 @item
4770 Unexpected initialization when address clause present
4772 @item
4773 Bad alignment for address clause
4775 @item
4776 Useless type conversions
4778 @item
4779 Redundant assignment statements and other redundant constructs
4781 @item
4782 Useless exception handlers
4784 @item
4785 Accidental hiding of name by child unit
4787 @item
4788 Access before elaboration detected at compile time
4790 @item
4791 A range in a @code{for} loop that is known to be null or might be null
4793 @end itemize
4795 @noindent
4796 The following section lists compiler switches that are available
4797 to control the handling of warning messages. It is also possible
4798 to exercise much finer control over what warnings are issued and
4799 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4800 gnat_rm, GNAT Reference manual}.
4802 @table @option
4803 @c !sort!
4804 @item -gnatwa
4805 @emph{Activate most optional warnings.}
4806 @cindex @option{-gnatwa} (@command{gcc})
4807 This switch activates most optional warning messages.  See the remaining list
4808 in this section for details on optional warning messages that can be
4809 individually controlled.  The warnings that are not turned on by this
4810 switch are:
4812 @itemize
4813 @item @option{-gnatwd} (implicit dereferencing)
4814 @item @option{-gnatw.d} (tag warnings with -gnatw switch)
4815 @item @option{-gnatwh} (hiding)
4816 @item @option{-gnatw.h} (holes in record layouts)
4817 @item @option{-gnatw.k} (redefinition of names in standard)
4818 @item @option{-gnatwl} (elaboration warnings)
4819 @item @option{-gnatw.l} (inherited aspects)
4820 @item @option{-gnatw.n} (atomic synchronization)
4821 @item @option{-gnatwo} (address clause overlay)
4822 @item @option{-gnatw.o} (values set by out parameters ignored)
4823 @item @option{-gnatw.s} (overridden size clause)
4824 @item @option{-gnatwt} (tracking of deleted conditional code)
4825 @item @option{-gnatw.u} (unordered enumeration)
4826 @item @option{-gnatw.w} (use of Warnings Off)
4827 @item @option{-gnatw.y} (reasons for package needing body)
4828 @end itemize
4830 All other optional warnings are turned on.
4832 @item -gnatwA
4833 @emph{Suppress all optional errors.}
4834 @cindex @option{-gnatwA} (@command{gcc})
4835 This switch suppresses all optional warning messages, see remaining list
4836 in this section for details on optional warning messages that can be
4837 individually controlled. Note that unlike switch @option{-gnatws}, the
4838 use of switch @option{-gnatwA} does not suppress warnings that are
4839 normally given unconditionally and cannot be individually controlled
4840 (for example, the warning about a missing exit path in a function).
4841 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4842 the use of switch @option{-gnatwA} can be individually turned back
4843 on. For example the use of switch @option{-gnatwA} followed by
4844 switch @option{-gnatwd} will suppress all optional warnings except
4845 the warnings for implicit dereferencing.
4847 @item -gnatw.a
4848 @emph{Activate warnings on failing assertions.}
4849 @cindex @option{-gnatw.a} (@command{gcc})
4850 @cindex Assert failures
4851 This switch activates warnings for assertions where the compiler can tell at
4852 compile time that the assertion will fail. Note that this warning is given
4853 even if assertions are disabled. The default is that such warnings are
4854 generated.
4856 @item -gnatw.A
4857 @emph{Suppress warnings on failing assertions.}
4858 @cindex @option{-gnatw.A} (@command{gcc})
4859 @cindex Assert failures
4860 This switch suppresses warnings for assertions where the compiler can tell at
4861 compile time that the assertion will fail.
4863 @item -gnatwb
4864 @emph{Activate warnings on bad fixed values.}
4865 @cindex @option{-gnatwb} (@command{gcc})
4866 @cindex Bad fixed values
4867 @cindex Fixed-point Small value
4868 @cindex Small value
4869 This switch activates warnings for static fixed-point expressions whose
4870 value is not an exact multiple of Small. Such values are implementation
4871 dependent, since an implementation is free to choose either of the multiples
4872 that surround the value. GNAT always chooses the closer one, but this is not
4873 required behavior, and it is better to specify a value that is an exact
4874 multiple, ensuring predictable execution. The default is that such warnings
4875 are not generated.
4877 @item -gnatwB
4878 @emph{Suppress warnings on bad fixed values.}
4879 @cindex @option{-gnatwB} (@command{gcc})
4880 This switch suppresses warnings for static fixed-point expressions whose
4881 value is not an exact multiple of Small.
4883 @item -gnatw.b
4884 @emph{Activate warnings on biased representation.}
4885 @cindex @option{-gnatw.b} (@command{gcc})
4886 @cindex Biased representation
4887 This switch activates warnings when a size clause, value size clause, component
4888 clause, or component size clause forces the use of biased representation for an
4889 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4890 to represent 10/11). The default is that such warnings are generated.
4892 @item -gnatw.B
4893 @emph{Suppress warnings on biased representation.}
4894 @cindex @option{-gnatwB} (@command{gcc})
4895 This switch suppresses warnings for representation clauses that force the use
4896 of biased representation.
4898 @item -gnatwc
4899 @emph{Activate warnings on conditionals.}
4900 @cindex @option{-gnatwc} (@command{gcc})
4901 @cindex Conditionals, constant
4902 This switch activates warnings for conditional expressions used in
4903 tests that are known to be True or False at compile time. The default
4904 is that such warnings are not generated.
4905 Note that this warning does
4906 not get issued for the use of boolean variables or constants whose
4907 values are known at compile time, since this is a standard technique
4908 for conditional compilation in Ada, and this would generate too many
4909 false positive warnings.
4911 This warning option also activates a special test for comparisons using
4912 the operators ``>='' and`` <=''.
4913 If the compiler can tell that only the equality condition is possible,
4914 then it will warn that the ``>'' or ``<'' part of the test
4915 is useless and that the operator could be replaced by ``=''.
4916 An example would be comparing a @code{Natural} variable <= 0.
4918 This warning option also generates warnings if
4919 one or both tests is optimized away in a membership test for integer
4920 values if the result can be determined at compile time. Range tests on
4921 enumeration types are not included, since it is common for such tests
4922 to include an end point.
4924 This warning can also be turned on using @option{-gnatwa}.
4926 @item -gnatwC
4927 @emph{Suppress warnings on conditionals.}
4928 @cindex @option{-gnatwC} (@command{gcc})
4929 This switch suppresses warnings for conditional expressions used in
4930 tests that are known to be True or False at compile time.
4932 @item -gnatw.c
4933 @emph{Activate warnings on missing component clauses.}
4934 @cindex @option{-gnatw.c} (@command{gcc})
4935 @cindex Component clause, missing
4936 This switch activates warnings for record components where a record
4937 representation clause is present and has component clauses for the
4938 majority, but not all, of the components. A warning is given for each
4939 component for which no component clause is present.
4941 @item -gnatw.C
4942 @emph{Suppress warnings on missing component clauses.}
4943 @cindex @option{-gnatwC} (@command{gcc})
4944 This switch suppresses warnings for record components that are
4945 missing a component clause in the situation described above.
4947 @item -gnatwd
4948 @emph{Activate warnings on implicit dereferencing.}
4949 @cindex @option{-gnatwd} (@command{gcc})
4950 If this switch is set, then the use of a prefix of an access type
4951 in an indexed component, slice, or selected component without an
4952 explicit @code{.all} will generate a warning. With this warning
4953 enabled, access checks occur only at points where an explicit
4954 @code{.all} appears in the source code (assuming no warnings are
4955 generated as a result of this switch). The default is that such
4956 warnings are not generated.
4958 @item -gnatwD
4959 @emph{Suppress warnings on implicit dereferencing.}
4960 @cindex @option{-gnatwD} (@command{gcc})
4961 @cindex Implicit dereferencing
4962 @cindex Dereferencing, implicit
4963 This switch suppresses warnings for implicit dereferences in
4964 indexed components, slices, and selected components.
4966 @item -gnatw.d
4967 @emph{Activate tagging of warning and info messages.}
4968 @cindex @option{-gnatw.d} (@command{gcc})
4969 If this switch is set, then warning messages are tagged, with one of the
4970 following strings:
4972 @table @option
4974 @item [-gnatw?]
4975 Used to tag warnings controlled by the switch @option{-gnatwx} where x
4976 is a letter a-z.
4978 @item [-gnatw.?]
4979 Used to tag warnings controlled by the switch @option{-gnatw.x} where x
4980 is a letter a-z.
4982 @item [-gnatel]
4983 Used to tag elaboration information (info) messages generated when the
4984 static model of elaboration is used and the @option{-gnatel} switch is set.
4986 @item [restriction warning]
4987 Used to tag warning messages for restriction violations, activated by use
4988 of the pragma @option{Restriction_Warnings}.
4990 @item [warning-as-error]
4991 Used to tag warning messages that have been converted to error messages by
4992 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
4993 the string "error: " rather than "warning: ".
4995 @item [enabled by default]
4996 Used to tag all other warnings that are always given by default, unless
4997 warnings are completely suppressed using pragma @option{Warnings(Off)} or
4998 the switch @option{-gnatws}.
5000 @end table
5002 @item -gnatw.D
5003 @emph{Deactivate tagging of warning and info messages messages.}
5004 @cindex @option{-gnatw.d} (@command{gcc})
5005 If this switch is set, then warning messages return to the default
5006 mode in which warnings and info messages are not tagged as described above for
5007 @code{-gnatw.d}.
5009 @item -gnatwe
5010 @emph{Treat warnings and style checks as errors.}
5011 @cindex @option{-gnatwe} (@command{gcc})
5012 @cindex Warnings, treat as error
5013 This switch causes warning messages and style check messages to be
5014 treated as errors.
5015 The warning string still appears, but the warning messages are counted
5016 as errors, and prevent the generation of an object file. Note that this
5017 is the only -gnatw switch that affects the handling of style check messages.
5018 Note also that this switch has no effect on info (information) messages, which
5019 are not treated as errors if this switch is present.
5021 @item -gnatw.e
5022 @emph{Activate every optional warning}
5023 @cindex @option{-gnatw.e} (@command{gcc})
5024 @cindex Warnings, activate every optional warning
5025 This switch activates all optional warnings, including those which
5026 are not activated by @code{-gnatwa}. The use of this switch is not
5027 recommended for normal use. If you turn this switch on, it is almost
5028 certain that you will get large numbers of useless warnings. The
5029 warnings that are excluded from @code{-gnatwa} are typically highly
5030 specialized warnings that are suitable for use only in code that has
5031 been specifically designed according to specialized coding rules.
5033 @item -gnatwf
5034 @emph{Activate warnings on unreferenced formals.}
5035 @cindex @option{-gnatwf} (@command{gcc})
5036 @cindex Formals, unreferenced
5037 This switch causes a warning to be generated if a formal parameter
5038 is not referenced in the body of the subprogram. This warning can
5039 also be turned on using @option{-gnatwu}. The
5040 default is that these warnings are not generated.
5042 @item -gnatwF
5043 @emph{Suppress warnings on unreferenced formals.}
5044 @cindex @option{-gnatwF} (@command{gcc})
5045 This switch suppresses warnings for unreferenced formal
5046 parameters. Note that the
5047 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5048 effect of warning on unreferenced entities other than subprogram
5049 formals.
5051 @item -gnatw.f
5052 @emph{Activate warnings on suspicious subprogram 'Access.}
5053 @cindex @option{-gnatw.f} (@command{gcc})
5054 This switch causes a warning to be generated if @code{P'Access} occurs
5055 in the same package where subprogram P is declared, and the
5056 @code{P'Access} is evaluated at elaboration time, and occurs before
5057 the body of P has been elaborated. For example, if we have
5058 @code{X : T := P'Access;}, then if X.all is subsequently called before
5059 the body of P is elaborated, it could cause
5060 access-before-elaboration. The default is that these warnings are not
5061 generated.
5063 @item -gnatw.F
5064 @emph{Suppress warnings on suspicious subprogram 'Access.}
5065 @cindex @option{-gnatw.F} (@command{gcc})
5066 This switch suppresses warnings for suspicious subprogram 'Access.
5068 @item -gnatwg
5069 @emph{Activate warnings on unrecognized pragmas.}
5070 @cindex @option{-gnatwg} (@command{gcc})
5071 @cindex Pragmas, unrecognized
5072 This switch causes a warning to be generated if an unrecognized
5073 pragma is encountered. Apart from issuing this warning, the
5074 pragma is ignored and has no effect. The default
5075 is that such warnings are issued (satisfying the Ada Reference
5076 Manual requirement that such warnings appear).
5078 @item -gnatwG
5079 @emph{Suppress warnings on unrecognized pragmas.}
5080 @cindex @option{-gnatwG} (@command{gcc})
5081 This switch suppresses warnings for unrecognized pragmas.
5083 @item -gnatw.g
5084 @emph{Warnings used for GNAT sources}
5085 @cindex @option{-gnatw.g} (@command{gcc})
5086 This switch sets the warning categories that are used by the standard
5087 GNAT style. Currently this is equivalent to
5088 @option{-gnatwAao.sI.C.V.X}
5089 but more warnings may be added in the future without advanced notice.
5091 @item -gnatwh
5092 @emph{Activate warnings on hiding.}
5093 @cindex @option{-gnatwh} (@command{gcc})
5094 @cindex Hiding of Declarations
5095 This switch activates warnings on hiding declarations.
5096 A declaration is considered hiding
5097 if it is for a non-overloadable entity, and it declares an entity with the
5098 same name as some other entity that is directly or use-visible. The default
5099 is that such warnings are not generated.
5101 @item -gnatwH
5102 @emph{Suppress warnings on hiding.}
5103 @cindex @option{-gnatwH} (@command{gcc})
5104 This switch suppresses warnings on hiding declarations.
5106 @item -gnatw.h
5107 @emph{Activate warnings on holes/gaps in records.}
5108 @cindex @option{-gnatw.h} (@command{gcc})
5109 @cindex Record Representation (gaps)
5110 This switch activates warnings on component clauses in record
5111 representation clauses that leave holes (gaps) in the record layout.
5112 If this warning option is active, then record representation clauses
5113 should specify a contiguous layout, adding unused fill fields if needed.
5115 @item -gnatw.H
5116 @emph{Suppress warnings on holes/gaps in records.}
5117 @cindex @option{-gnatw.H} (@command{gcc})
5118 This switch suppresses warnings on component clauses in record
5119 representation clauses that leave holes (haps) in the record layout.
5121 @item -gnatwi
5122 @emph{Activate warnings on implementation units.}
5123 @cindex @option{-gnatwi} (@command{gcc})
5124 This switch activates warnings for a @code{with} of an internal GNAT
5125 implementation unit, defined as any unit from the @code{Ada},
5126 @code{Interfaces}, @code{GNAT},
5127  or @code{System}
5128 hierarchies that is not
5129 documented in either the Ada Reference Manual or the GNAT
5130 Programmer's Reference Manual. Such units are intended only
5131 for internal implementation purposes and should not be @code{with}'ed
5132 by user programs. The default is that such warnings are generated
5134 @item -gnatwI
5135 @emph{Disable warnings on implementation units.}
5136 @cindex @option{-gnatwI} (@command{gcc})
5137 This switch disables warnings for a @code{with} of an internal GNAT
5138 implementation unit.
5140 @item -gnatw.i
5141 @emph{Activate warnings on overlapping actuals.}
5142 @cindex @option{-gnatw.i} (@command{gcc})
5143 This switch enables a warning on statically detectable overlapping actuals in
5144 a subprogram call, when one of the actuals is an in-out parameter, and the
5145 types of the actuals are not by-copy types. This warning is off by default.
5147 @item -gnatw.I
5148 @emph{Disable warnings on overlapping actuals.}
5149 @cindex @option{-gnatw.I} (@command{gcc})
5150 This switch disables warnings on overlapping actuals in a call..
5152 @item -gnatwj
5153 @emph{Activate warnings on obsolescent features (Annex J).}
5154 @cindex @option{-gnatwj} (@command{gcc})
5155 @cindex Features, obsolescent
5156 @cindex Obsolescent features
5157 If this warning option is activated, then warnings are generated for
5158 calls to subprograms marked with @code{pragma Obsolescent} and
5159 for use of features in Annex J of the Ada Reference Manual. In the
5160 case of Annex J, not all features are flagged. In particular use
5161 of the renamed packages (like @code{Text_IO}) and use of package
5162 @code{ASCII} are not flagged, since these are very common and
5163 would generate many annoying positive warnings. The default is that
5164 such warnings are not generated.
5166 In addition to the above cases, warnings are also generated for
5167 GNAT features that have been provided in past versions but which
5168 have been superseded (typically by features in the new Ada standard).
5169 For example, @code{pragma Ravenscar} will be flagged since its
5170 function is replaced by @code{pragma Profile(Ravenscar)}, and
5171 @code{pragma Interface_Name} will be flagged since its function
5172 is replaced by @code{pragma Import}.
5174 Note that this warning option functions differently from the
5175 restriction @code{No_Obsolescent_Features} in two respects.
5176 First, the restriction applies only to annex J features.
5177 Second, the restriction does flag uses of package @code{ASCII}.
5179 @item -gnatwJ
5180 @emph{Suppress warnings on obsolescent features (Annex J).}
5181 @cindex @option{-gnatwJ} (@command{gcc})
5182 This switch disables warnings on use of obsolescent features.
5184 @item -gnatwk
5185 @emph{Activate warnings on variables that could be constants.}
5186 @cindex @option{-gnatwk} (@command{gcc})
5187 This switch activates warnings for variables that are initialized but
5188 never modified, and then could be declared constants. The default is that
5189 such warnings are not given.
5191 @item -gnatwK
5192 @emph{Suppress warnings on variables that could be constants.}
5193 @cindex @option{-gnatwK} (@command{gcc})
5194 This switch disables warnings on variables that could be declared constants.
5196 @item -gnatw.k
5197 @emph{Activate warnings on redefinition of names in standard.}
5198 @cindex @option{-gnatw.k} (@command{gcc})
5199 This switch activates warnings for declarations that declare a name that
5200 is defined in package Standard. Such declarations can be confusing,
5201 especially since the names in package Standard continue to be directly
5202 visible, meaning that use visibiliy on such redeclared names does not
5203 work as expected. Names of discriminants and components in records are
5204 not included in this check.
5206 @item -gnatw.K
5207 @emph{Suppress warnings on redefinition of names in standard.}
5208 @cindex @option{-gnatwK} (@command{gcc})
5209 This switch activates warnings for declarations that declare a name that
5210 is defined in package Standard.
5212 @item -gnatwl
5213 @emph{Activate warnings for elaboration pragmas.}
5214 @cindex @option{-gnatwl} (@command{gcc})
5215 @cindex Elaboration, warnings
5216 This switch activates warnings for possible elaboration problems,
5217 including suspicious use
5218 of @code{Elaborate} pragmas, when using the static elaboration model, and
5219 possible situations that may raise @code{Program_Error} when using the
5220 dynamic elaboration model.
5221 See the section in this guide on elaboration checking for further details.
5222 The default is that such warnings
5223 are not generated.
5225 @item -gnatwL
5226 @emph{Suppress warnings for elaboration pragmas.}
5227 @cindex @option{-gnatwL} (@command{gcc})
5228 This switch suppresses warnings for possible elaboration problems.
5230 @item -gnatw.l
5231 @emph{List inherited aspects.}
5232 @cindex @option{-gnatw.l} (@command{gcc})
5233 This switch causes the compiler to list inherited invariants,
5234 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5235 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5237 @item -gnatw.L
5238 @emph{Suppress listing of inherited aspects.}
5239 @cindex @option{-gnatw.L} (@command{gcc})
5240 This switch suppresses listing of inherited aspects.
5242 @item -gnatwm
5243 @emph{Activate warnings on modified but unreferenced variables.}
5244 @cindex @option{-gnatwm} (@command{gcc})
5245 This switch activates warnings for variables that are assigned (using
5246 an initialization value or with one or more assignment statements) but
5247 whose value is never read. The warning is suppressed for volatile
5248 variables and also for variables that are renamings of other variables
5249 or for which an address clause is given.
5250 The default is that these warnings are not given.
5252 @item -gnatwM
5253 @emph{Disable warnings on modified but unreferenced variables.}
5254 @cindex @option{-gnatwM} (@command{gcc})
5255 This switch disables warnings for variables that are assigned or
5256 initialized, but never read.
5258 @item -gnatw.m
5259 @emph{Activate warnings on suspicious modulus values.}
5260 @cindex @option{-gnatw.m} (@command{gcc})
5261 This switch activates warnings for modulus values that seem suspicious.
5262 The cases caught are where the size is the same as the modulus (e.g.
5263 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5264 with no size clause. The guess in both cases is that 2**x was intended
5265 rather than x. In addition expressions of the form 2*x for small x
5266 generate a warning (the almost certainly accurate guess being that
5267 2**x was intended). The default is that these warnings are given.
5269 @item -gnatw.M
5270 @emph{Disable warnings on suspicious modulus values.}
5271 @cindex @option{-gnatw.M} (@command{gcc})
5272 This switch disables warnings for suspicious modulus values.
5274 @item -gnatwn
5275 @emph{Set normal warnings mode.}
5276 @cindex @option{-gnatwn} (@command{gcc})
5277 This switch sets normal warning mode, in which enabled warnings are
5278 issued and treated as warnings rather than errors. This is the default
5279 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5280 an explicit @option{-gnatws} or
5281 @option{-gnatwe}. It also cancels the effect of the
5282 implicit @option{-gnatwe} that is activated by the
5283 use of @option{-gnatg}.
5285 @item -gnatw.n
5286 @emph{Activate warnings on atomic synchronization.}
5287 @cindex @option{-gnatw.n} (@command{gcc})
5288 @cindex Atomic Synchronization, warnings
5289 This switch actives warnings when an access to an atomic variable
5290 requires the generation of atomic synchronization code. These
5291 warnings are off by default.
5292 @item -gnatw.N
5293 @emph{Suppress warnings on atomic synchronization.}
5294 @cindex @option{-gnatw.n} (@command{gcc})
5295 @cindex Atomic Synchronization, warnings
5296 This switch suppresses warnings when an access to an atomic variable
5297 requires the generation of atomic synchronization code.
5299 @item -gnatwo
5300 @emph{Activate warnings on address clause overlays.}
5301 @cindex @option{-gnatwo} (@command{gcc})
5302 @cindex Address Clauses, warnings
5303 This switch activates warnings for possibly unintended initialization
5304 effects of defining address clauses that cause one variable to overlap
5305 another. The default is that such warnings are generated.
5307 @item -gnatwO
5308 @emph{Suppress warnings on address clause overlays.}
5309 @cindex @option{-gnatwO} (@command{gcc})
5310 This switch suppresses warnings on possibly unintended initialization
5311 effects of defining address clauses that cause one variable to overlap
5312 another.
5314 @item -gnatw.o
5315 @emph{Activate warnings on modified but unreferenced out parameters.}
5316 @cindex @option{-gnatw.o} (@command{gcc})
5317 This switch activates warnings for variables that are modified by using
5318 them as actuals for a call to a procedure with an out mode formal, where
5319 the resulting assigned value is never read. It is applicable in the case
5320 where there is more than one out mode formal. If there is only one out
5321 mode formal, the warning is issued by default (controlled by -gnatwu).
5322 The warning is suppressed for volatile
5323 variables and also for variables that are renamings of other variables
5324 or for which an address clause is given.
5325 The default is that these warnings are not given.
5327 @item -gnatw.O
5328 @emph{Disable warnings on modified but unreferenced out parameters.}
5329 @cindex @option{-gnatw.O} (@command{gcc})
5330 This switch suppresses warnings for variables that are modified by using
5331 them as actuals for a call to a procedure with an out mode formal, where
5332 the resulting assigned value is never read.
5334 @item -gnatwp
5335 @emph{Activate warnings on ineffective pragma Inlines.}
5336 @cindex @option{-gnatwp} (@command{gcc})
5337 @cindex Inlining, warnings
5338 This switch activates warnings for failure of front end inlining
5339 (activated by @option{-gnatN}) to inline a particular call. There are
5340 many reasons for not being able to inline a call, including most
5341 commonly that the call is too complex to inline. The default is
5342 that such warnings are not given.
5343 Warnings on ineffective inlining by the gcc back-end can be activated
5344 separately, using the gcc switch -Winline.
5346 @item -gnatwP
5347 @emph{Suppress warnings on ineffective pragma Inlines.}
5348 @cindex @option{-gnatwP} (@command{gcc})
5349 This switch suppresses warnings on ineffective pragma Inlines. If the
5350 inlining mechanism cannot inline a call, it will simply ignore the
5351 request silently.
5353 @item -gnatw.p
5354 @emph{Activate warnings on parameter ordering.}
5355 @cindex @option{-gnatw.p} (@command{gcc})
5356 @cindex Parameter order, warnings
5357 This switch activates warnings for cases of suspicious parameter
5358 ordering when the list of arguments are all simple identifiers that
5359 match the names of the formals, but are in a different order. The
5360 warning is suppressed if any use of named parameter notation is used,
5361 so this is the appropriate way to suppress a false positive (and
5362 serves to emphasize that the "misordering" is deliberate). The
5363 default is that such warnings are not given.
5365 @item -gnatw.P
5366 @emph{Suppress warnings on parameter ordering.}
5367 @cindex @option{-gnatw.P} (@command{gcc})
5368 This switch suppresses warnings on cases of suspicious parameter
5369 ordering.
5371 @item -gnatwq
5372 @emph{Activate warnings on questionable missing parentheses.}
5373 @cindex @option{-gnatwq} (@command{gcc})
5374 @cindex Parentheses, warnings
5375 This switch activates warnings for cases where parentheses are not used and
5376 the result is potential ambiguity from a readers point of view. For example
5377 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5378 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5379 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5380 follow the rule of always parenthesizing to make the association clear, and
5381 this warning switch warns if such parentheses are not present. The default
5382 is that these warnings are given.
5384 @item -gnatwQ
5385 @emph{Suppress warnings on questionable missing parentheses.}
5386 @cindex @option{-gnatwQ} (@command{gcc})
5387 This switch suppresses warnings for cases where the association is not
5388 clear and the use of parentheses is preferred.
5390 @item -gnatwr
5391 @emph{Activate warnings on redundant constructs.}
5392 @cindex @option{-gnatwr} (@command{gcc})
5393 This switch activates warnings for redundant constructs. The following
5394 is the current list of constructs regarded as redundant:
5396 @itemize @bullet
5397 @item
5398 Assignment of an item to itself.
5399 @item
5400 Type conversion that converts an expression to its own type.
5401 @item
5402 Use of the attribute @code{Base} where @code{typ'Base} is the same
5403 as @code{typ}.
5404 @item
5405 Use of pragma @code{Pack} when all components are placed by a record
5406 representation clause.
5407 @item
5408 Exception handler containing only a reraise statement (raise with no
5409 operand) which has no effect.
5410 @item
5411 Use of the operator abs on an operand that is known at compile time
5412 to be non-negative
5413 @item
5414 Comparison of boolean expressions to an explicit True value.
5415 @end itemize
5417 The default is that warnings for redundant constructs are not given.
5419 @item -gnatwR
5420 @emph{Suppress warnings on redundant constructs.}
5421 @cindex @option{-gnatwR} (@command{gcc})
5422 This switch suppresses warnings for redundant constructs.
5424 @item -gnatw.r
5425 @emph{Activate warnings for object renaming function.}
5426 @cindex @option{-gnatw.r} (@command{gcc})
5427 This switch activates warnings for an object renaming that renames a
5428 function call, which is equivalent to a constant declaration (as
5429 opposed to renaming the function itself).  The default is that these
5430 warnings are given.
5432 @item -gnatw.R
5433 @emph{Suppress warnings for object renaming function.}
5434 @cindex @option{-gnatwT} (@command{gcc})
5435 This switch suppresses warnings for object renaming function.
5437 @item -gnatws
5438 @emph{Suppress all warnings.}
5439 @cindex @option{-gnatws} (@command{gcc})
5440 This switch completely suppresses the
5441 output of all warning messages from the GNAT front end, including
5442 both warnings that can be controlled by switches described in this
5443 section, and those that are normally given unconditionally. The
5444 effect of this suppress action can only be cancelled by a subsequent
5445 use of the switch @option{-gnatwn}.
5447 Note that switch @option{-gnatws} does not suppress
5448 warnings from the @command{gcc} back end.
5449 To suppress these back end warnings as well, use the switch @option{-w}
5450 in addition to @option{-gnatws}. Also this switch has no effect on the
5451 handling of style check messages.
5453 @item -gnatw.s
5454 @emph{Activate warnings on overridden size clauses.}
5455 @cindex @option{-gnatw.s} (@command{gcc})
5456 @cindex Record Representation (component sizes)
5457 This switch activates warnings on component clauses in record
5458 representation clauses where the length given overrides that
5459 specified by an explicit size clause for the component type. A
5460 warning is similarly given in the array case if a specified
5461 component size overrides an explicit size clause for the array
5462 component type.
5464 @item -gnatw.S
5465 @emph{Suppress warnings on overridden size clauses.}
5466 @cindex @option{-gnatw.S} (@command{gcc})
5467 This switch suppresses warnings on component clauses in record
5468 representation clauses that override size clauses, and similar
5469 warnings when an array component size overrides a size clause.
5471 @item -gnatwt
5472 @emph{Activate warnings for tracking of deleted conditional code.}
5473 @cindex @option{-gnatwt} (@command{gcc})
5474 @cindex Deactivated code, warnings
5475 @cindex Deleted code, warnings
5476 This switch activates warnings for tracking of code in conditionals (IF and
5477 CASE statements) that is detected to be dead code which cannot be executed, and
5478 which is removed by the front end. This warning is off by default. This may be
5479 useful for detecting deactivated code in certified applications.
5481 @item -gnatwT
5482 @emph{Suppress warnings for tracking of deleted conditional code.}
5483 @cindex @option{-gnatwT} (@command{gcc})
5484 This switch suppresses warnings for tracking of deleted conditional code.
5486 @item -gnatw.t
5487 @emph{Activate warnings on suspicious contracts.}
5488 @cindex @option{-gnatw.t} (@command{gcc})
5489 This switch activates warnings on suspicious postconditions (whether a
5490 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5491 and suspicious contract cases (pragma @code{Contract_Cases}). A
5492 function postcondition or contract case is suspicious when no postcondition
5493 or contract case for this function mentions the result of the function.
5494 A procedure postcondition or contract case is suspicious when it only
5495 refers to the pre-state of the procedure, because in that case it should
5496 rather be expressed as a precondition. The default is that such warnings
5497 are not generated.
5499 @item -gnatw.T
5500 @emph{Suppress warnings on suspicious contracts.}
5501 @cindex @option{-gnatw.T} (@command{gcc})
5502 This switch suppresses warnings on suspicious postconditions.
5504 @item -gnatwu
5505 @emph{Activate warnings on unused entities.}
5506 @cindex @option{-gnatwu} (@command{gcc})
5507 This switch activates warnings to be generated for entities that
5508 are declared but not referenced, and for units that are @code{with}'ed
5509 and not
5510 referenced. In the case of packages, a warning is also generated if
5511 no entities in the package are referenced. This means that if a with'ed
5512 package is referenced but the only references are in @code{use}
5513 clauses or @code{renames}
5514 declarations, a warning is still generated. A warning is also generated
5515 for a generic package that is @code{with}'ed but never instantiated.
5516 In the case where a package or subprogram body is compiled, and there
5517 is a @code{with} on the corresponding spec
5518 that is only referenced in the body,
5519 a warning is also generated, noting that the
5520 @code{with} can be moved to the body. The default is that
5521 such warnings are not generated.
5522 This switch also activates warnings on unreferenced formals
5523 (it includes the effect of @option{-gnatwf}).
5525 @item -gnatwU
5526 @emph{Suppress warnings on unused entities.}
5527 @cindex @option{-gnatwU} (@command{gcc})
5528 This switch suppresses warnings for unused entities and packages.
5529 It also turns off warnings on unreferenced formals (and thus includes
5530 the effect of @option{-gnatwF}).
5532 @item -gnatw.u
5533 @emph{Activate warnings on unordered enumeration types.}
5534 @cindex @option{-gnatw.u} (@command{gcc})
5535 This switch causes enumeration types to be considered as conceptually
5536 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5537 The effect is to generate warnings in clients that use explicit comparisons
5538 or subranges, since these constructs both treat objects of the type as
5539 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5540 which the type is declared, or its body or subunits.) Please refer to
5541 the description of pragma @code{Ordered} in the
5542 @cite{@value{EDITION} Reference Manual} for further details.
5543 The default is that such warnings are not generated.
5545 @item -gnatw.U
5546 @emph{Deactivate warnings on unordered enumeration types.}
5547 @cindex @option{-gnatw.U} (@command{gcc})
5548 This switch causes all enumeration types to be considered as ordered, so
5549 that no warnings are given for comparisons or subranges for any type.
5551 @item -gnatwv
5552 @emph{Activate warnings on unassigned variables.}
5553 @cindex @option{-gnatwv} (@command{gcc})
5554 @cindex Unassigned variable warnings
5555 This switch activates warnings for access to variables which
5556 may not be properly initialized. The default is that
5557 such warnings are generated.
5559 @item -gnatwV
5560 @emph{Suppress warnings on unassigned variables.}
5561 @cindex @option{-gnatwV} (@command{gcc})
5562 This switch suppresses warnings for access to variables which
5563 may not be properly initialized.
5564 For variables of a composite type, the warning can also be suppressed in
5565 Ada 2005 by using a default initialization with a box. For example, if
5566 Table is an array of records whose components are only partially uninitialized,
5567 then the following code:
5569 @smallexample @c ada
5570    Tab : Table := (@b{others} => <>);
5571 @end smallexample
5573 will suppress warnings on subsequent statements that access components
5574 of variable Tab.
5576 @item -gnatw.v
5577 @emph{Activate info messages for non-default bit order.}
5578 @cindex @option{-gnatw.v} (@command{gcc})
5579 @cindex bit order warnings
5580 This switch activates messages (labeled "info", they are not warnings,
5581 just informational messages) about the effects of non-default bit-order
5582 on records to which a component clause is applied. The effect of specifying
5583 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5584 these messages, which are given by default, are useful in understanding the
5585 exact consequences of using this feature.
5587 @item -gnatw.V
5588 @emph{Suppress info messages for non-default bit order.}
5589 @cindex @option{-gnatw.V} (@command{gcc})
5590 This switch suppresses information messages for the effects of specifying
5591 non-default bit order on record components with component clauses.
5593 @item -gnatww
5594 @emph{Activate warnings on wrong low bound assumption.}
5595 @cindex @option{-gnatww} (@command{gcc})
5596 @cindex String indexing warnings
5597 This switch activates warnings for indexing an unconstrained string parameter
5598 with a literal or S'Length. This is a case where the code is assuming that the
5599 low bound is one, which is in general not true (for example when a slice is
5600 passed). The default is that such warnings are generated.
5602 @item -gnatwW
5603 @emph{Suppress warnings on wrong low bound assumption.}
5604 @cindex @option{-gnatwW} (@command{gcc})
5605 This switch suppresses warnings for indexing an unconstrained string parameter
5606 with a literal or S'Length. Note that this warning can also be suppressed
5607 in a particular case by adding an
5608 assertion that the lower bound is 1,
5609 as shown in the following example.
5611 @smallexample @c ada
5612    @b{procedure} K (S : String) @b{is}
5613       @b{pragma} Assert (S'First = 1);
5614       @dots{}
5615 @end smallexample
5617 @item -gnatw.w
5618 @emph{Activate warnings on Warnings Off pragmas}
5619 @cindex @option{-gnatw.w} (@command{gcc})
5620 @cindex Warnings Off control
5621 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5622 where either the pragma is entirely useless (because it suppresses no
5623 warnings), or it could be replaced by @code{pragma Unreferenced} or
5624 @code{pragma Unmodified}.
5625 Also activates warnings for the case of
5626 Warnings (Off, String), where either there is no matching
5627 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
5628 The default is that these warnings are not given.
5630 @item -gnatw.W
5631 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5632 @cindex @option{-gnatw.W} (@command{gcc})
5633 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
5635 @item -gnatwx
5636 @emph{Activate warnings on Export/Import pragmas.}
5637 @cindex @option{-gnatwx} (@command{gcc})
5638 @cindex Export/Import pragma warnings
5639 This switch activates warnings on Export/Import pragmas when
5640 the compiler detects a possible conflict between the Ada and
5641 foreign language calling sequences. For example, the use of
5642 default parameters in a convention C procedure is dubious
5643 because the C compiler cannot supply the proper default, so
5644 a warning is issued. The default is that such warnings are
5645 generated.
5647 @item -gnatwX
5648 @emph{Suppress warnings on Export/Import pragmas.}
5649 @cindex @option{-gnatwX} (@command{gcc})
5650 This switch suppresses warnings on Export/Import pragmas.
5651 The sense of this is that you are telling the compiler that
5652 you know what you are doing in writing the pragma, and it
5653 should not complain at you.
5655 @item -gnatw.x
5656 @emph{Activate warnings for No_Exception_Propagation mode.}
5657 @cindex @option{-gnatwm} (@command{gcc})
5658 This switch activates warnings for exception usage when pragma Restrictions
5659 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5660 explicit exception raises which are not covered by a local handler, and for
5661 exception handlers which do not cover a local raise. The default is that these
5662 warnings are not given.
5664 @item -gnatw.X
5665 @emph{Disable warnings for No_Exception_Propagation mode.}
5666 This switch disables warnings for exception usage when pragma Restrictions
5667 (No_Exception_Propagation) is in effect.
5669 @item -gnatwy
5670 @emph{Activate warnings for Ada compatibility issues.}
5671 @cindex @option{-gnatwy} (@command{gcc})
5672 @cindex Ada compatibility issues warnings
5673 For the most part, newer versions of Ada are upwards compatible
5674 with older versions. For example, Ada 2005 programs will almost
5675 always work when compiled as Ada 2012.
5676 However there are some exceptions (for example the fact that
5677 @code{some} is now a reserved word in Ada 2012). This
5678 switch activates several warnings to help in identifying
5679 and correcting such incompatibilities. The default is that
5680 these warnings are generated. Note that at one point Ada 2005
5681 was called Ada 0Y, hence the choice of character.
5683 @item -gnatwY
5684 @emph{Disable warnings for Ada compatibility issues.}
5685 @cindex @option{-gnatwY} (@command{gcc})
5686 @cindex Ada compatibility issues warnings
5687 This switch suppresses the warnings intended to help in identifying
5688 incompatibilities between Ada language versions.
5690 @item -gnatw.y
5691 @emph{Activate information messages for why package spec needs body}
5692 @cindex @option{-gnatw.y} (@command{gcc})
5693 @cindex Package spec needing body
5694 There are a number of cases in which a package spec needs a body.
5695 For example, the use of pragma Elaborate_Body, or the declaration
5696 of a procedure specification requiring a completion. This switch
5697 causes information messages to be output showing why a package
5698 specification requires a body. This can be useful in the case of
5699 a large package specification which is unexpectedly requiring a
5700 body. The default is that such information messages are not output.
5702 @item -gnatw.Y
5703 @emph{Disable information messages for why package spec needs body}
5704 @cindex @option{-gnatw.Y} (@command{gcc})
5705 @cindex No information messages for why package spec needs body
5706 This switch suppresses the output of information messages showing why
5707 a package specification needs a body.
5709 @item -gnatwz
5710 @emph{Activate warnings on unchecked conversions.}
5711 @cindex @option{-gnatwz} (@command{gcc})
5712 @cindex Unchecked_Conversion warnings
5713 This switch activates warnings for unchecked conversions
5714 where the types are known at compile time to have different
5715 sizes. The default
5716 is that such warnings are generated. Warnings are also
5717 generated for subprogram pointers with different conventions,
5718 and, on VMS only, for data pointers with different conventions.
5720 @item -gnatwZ
5721 @emph{Suppress warnings on unchecked conversions.}
5722 @cindex @option{-gnatwZ} (@command{gcc})
5723 This switch suppresses warnings for unchecked conversions
5724 where the types are known at compile time to have different
5725 sizes or conventions.
5727 @item -gnatw.z
5728 @emph{Activate warnings for size not a multiple of alignment.}
5729 @cindex @option{-gnatw.z} (@command{gcc})
5730 @cindex Size/Alignment warnings
5731 This switch activates warnings for cases of record types with
5732 specified @code{Size} and @code{Alignment} attributes where the
5733 size is not a multiple of the alignment, resulting in an object
5734 size that is greater than the specified size. The default
5735 is that such warnings are generated.
5737 @item -gnatw.Z
5738 @emph{Suppress warnings for size not a multiple of alignment.}
5739 @cindex @option{-gnatw.Z} (@command{gcc})
5740 @cindex Size/Alignment warnings
5741 This switch suppresses warnings for cases of record types with
5742 specified @code{Size} and @code{Alignment} attributes where the
5743 size is not a multiple of the alignment, resulting in an object
5744 size that is greater than the specified size.
5745 The warning can also be
5746 suppressed by giving an explicit @code{Object_Size} value.
5748 @item -Wunused
5749 @cindex @option{-Wunused}
5750 The warnings controlled by the @option{-gnatw} switch are generated by
5751 the front end of the compiler. The @option{GCC} back end can provide
5752 additional warnings and they are controlled by the @option{-W} switch.
5753 For example, @option{-Wunused} activates back end
5754 warnings for entities that are declared but not referenced.
5756 @item -Wuninitialized
5757 @cindex @option{-Wuninitialized}
5758 Similarly, @option{-Wuninitialized} activates
5759 the back end warning for uninitialized variables. This switch must be
5760 used in conjunction with an optimization level greater than zero.
5762 @item -Wstack-usage=@var{len}
5763 @cindex @option{-Wstack-usage}
5764 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5765 See @ref{Static Stack Usage Analysis} for details.
5767 @item -Wall
5768 @cindex @option{-Wall}
5769 This switch enables most warnings from the @option{GCC} back end.
5770 The code generator detects a number of warning situations that are missed
5771 by the @option{GNAT} front end, and this switch can be used to activate them.
5772 The use of this switch also sets the default front end warning mode to
5773 @option{-gnatwa}, that is, most front end warnings activated as well.
5775 @item -w
5776 @cindex @option{-w}
5777 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5778 The use of this switch also sets the default front end warning mode to
5779 @option{-gnatws}, that is, front end warnings suppressed as well.
5781 @item -Werror
5782 @cindex @option{-Werror}
5783 This switch causes warnings from the @option{GCC} back end to be treated as
5784 errors.  The warning string still appears, but the warning messages are
5785 counted as errors, and prevent the generation of an object file.
5787 @end table
5789 @noindent
5790 A string of warning parameters can be used in the same parameter. For example:
5792 @smallexample
5793 -gnatwaGe
5794 @end smallexample
5796 @noindent
5797 will turn on all optional warnings except for unrecognized pragma warnings,
5798 and also specify that warnings should be treated as errors.
5800 When no switch @option{-gnatw} is used, this is equivalent to:
5802 @table @option
5803 @c !sort!
5804 @item -gnatw.a
5805 @item -gnatwB
5806 @item -gnatw.b
5807 @item -gnatwC
5808 @item -gnatw.C
5809 @item -gnatwD
5810 @item -gnatwF
5811 @item -gnatwg
5812 @item -gnatwH
5813 @item -gnatwi
5814 @item -gnatw.I
5815 @item -gnatwJ
5816 @item -gnatwK
5817 @item -gnatwL
5818 @item -gnatw.L
5819 @item -gnatwM
5820 @item -gnatw.m
5821 @item -gnatwn
5822 @item -gnatwo
5823 @item -gnatw.O
5824 @item -gnatwP
5825 @item -gnatw.P
5826 @item -gnatwq
5827 @item -gnatwR
5828 @item -gnatw.R
5829 @item -gnatw.S
5830 @item -gnatwT
5831 @item -gnatw.T
5832 @item -gnatwU
5833 @item -gnatwv
5834 @item -gnatww
5835 @item -gnatw.W
5836 @item -gnatwx
5837 @item -gnatw.X
5838 @item -gnatwy
5839 @item -gnatwz
5841 @end table
5843 @node Debugging and Assertion Control
5844 @subsection Debugging and Assertion Control
5846 @table @option
5847 @item -gnata
5848 @cindex @option{-gnata} (@command{gcc})
5849 @findex Assert
5850 @findex Debug
5851 @cindex Assertions
5853 @noindent
5854 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5855 are ignored. This switch, where @samp{a} stands for assert, causes
5856 @code{Assert} and @code{Debug} pragmas to be activated.
5858 The pragmas have the form:
5860 @smallexample
5861 @cartouche
5862    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5863                       @var{static-string-expression}@r{]})
5864    @b{pragma} Debug (@var{procedure call})
5865 @end cartouche
5866 @end smallexample
5868 @noindent
5869 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5870 If the result is @code{True}, the pragma has no effect (other than
5871 possible side effects from evaluating the expression). If the result is
5872 @code{False}, the exception @code{Assert_Failure} declared in the package
5873 @code{System.Assertions} is
5874 raised (passing @var{static-string-expression}, if present, as the
5875 message associated with the exception). If no string expression is
5876 given the default is a string giving the file name and line number
5877 of the pragma.
5879 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5880 @code{pragma Debug} may appear within a declaration sequence, allowing
5881 debugging procedures to be called between declarations.
5883 @end table
5885 @node Validity Checking
5886 @subsection Validity Checking
5887 @findex Validity Checking
5889 @noindent
5890 The Ada Reference Manual defines the concept of invalid values (see
5891 RM 13.9.1). The primary source of invalid values is uninitialized
5892 variables. A scalar variable that is left uninitialized may contain
5893 an invalid value; the concept of invalid does not apply to access or
5894 composite types.
5896 It is an error to read an invalid value, but the RM does not require
5897 run-time checks to detect such errors, except for some minimal
5898 checking to prevent erroneous execution (i.e. unpredictable
5899 behavior). This corresponds to the @option{-gnatVd} switch below,
5900 which is the default. For example, by default, if the expression of a
5901 case statement is invalid, it will raise Constraint_Error rather than
5902 causing a wild jump, and if an array index on the left-hand side of an
5903 assignment is invalid, it will raise Constraint_Error rather than
5904 overwriting an arbitrary memory location.
5906 The @option{-gnatVa} may be used to enable additional validity checks,
5907 which are not required by the RM. These checks are often very
5908 expensive (which is why the RM does not require them). These checks
5909 are useful in tracking down uninitialized variables, but they are
5910 not usually recommended for production builds, and in particular
5911 we do not recommend using these extra validity checking options in
5912 combination with optimization, since this can confuse the optimizer.
5913 If performance is a consideration, leading to the need to optimize,
5914 then the validity checking options should not be used.
5916 The other @option{-gnatV@var{x}} switches below allow finer-grained
5917 control; you can enable whichever validity checks you desire. However,
5918 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5919 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5920 sufficient for non-debugging use.
5922 The @option{-gnatB} switch tells the compiler to assume that all
5923 values are valid (that is, within their declared subtype range)
5924 except in the context of a use of the Valid attribute. This means
5925 the compiler can generate more efficient code, since the range
5926 of values is better known at compile time. However, an uninitialized
5927 variable can cause wild jumps and memory corruption in this mode.
5929 The @option{-gnatV@var{x}} switch allows control over the validity
5930 checking mode as described below.
5931 The @code{x} argument is a string of letters that
5932 indicate validity checks that are performed or not performed in addition
5933 to the default checks required by Ada as described above.
5935 @table @option
5936 @c !sort!
5937 @item -gnatVa
5938 @emph{All validity checks.}
5939 @cindex @option{-gnatVa} (@command{gcc})
5940 All validity checks are turned on.
5941 That is, @option{-gnatVa} is
5942 equivalent to @option{gnatVcdfimorst}.
5944 @item -gnatVc
5945 @emph{Validity checks for copies.}
5946 @cindex @option{-gnatVc} (@command{gcc})
5947 The right hand side of assignments, and the initializing values of
5948 object declarations are validity checked.
5950 @item -gnatVd
5951 @emph{Default (RM) validity checks.}
5952 @cindex @option{-gnatVd} (@command{gcc})
5953 Some validity checks are done by default following normal Ada semantics
5954 (RM 13.9.1 (9-11)).
5955 A check is done in case statements that the expression is within the range
5956 of the subtype. If it is not, Constraint_Error is raised.
5957 For assignments to array components, a check is done that the expression used
5958 as index is within the range. If it is not, Constraint_Error is raised.
5959 Both these validity checks may be turned off using switch @option{-gnatVD}.
5960 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5961 switch @option{-gnatVd} will leave the checks turned on.
5962 Switch @option{-gnatVD} should be used only if you are sure that all such
5963 expressions have valid values. If you use this switch and invalid values
5964 are present, then the program is erroneous, and wild jumps or memory
5965 overwriting may occur.
5967 @item -gnatVe
5968 @emph{Validity checks for elementary components.}
5969 @cindex @option{-gnatVe} (@command{gcc})
5970 In the absence of this switch, assignments to record or array components are
5971 not validity checked, even if validity checks for assignments generally
5972 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5973 require valid data, but assignment of individual components does. So for
5974 example, there is a difference between copying the elements of an array with a
5975 slice assignment, compared to assigning element by element in a loop. This
5976 switch allows you to turn off validity checking for components, even when they
5977 are assigned component by component.
5979 @item -gnatVf
5980 @emph{Validity checks for floating-point values.}
5981 @cindex @option{-gnatVf} (@command{gcc})
5982 In the absence of this switch, validity checking occurs only for discrete
5983 values. If @option{-gnatVf} is specified, then validity checking also applies
5984 for floating-point values, and NaNs and infinities are considered invalid,
5985 as well as out of range values for constrained types. Note that this means
5986 that standard IEEE infinity mode is not allowed. The exact contexts
5987 in which floating-point values are checked depends on the setting of other
5988 options. For example,
5989 @option{-gnatVif} or
5990 @option{-gnatVfi}
5991 (the order does not matter) specifies that floating-point parameters of mode
5992 @code{in} should be validity checked.
5994 @item -gnatVi
5995 @emph{Validity checks for @code{in} mode parameters}
5996 @cindex @option{-gnatVi} (@command{gcc})
5997 Arguments for parameters of mode @code{in} are validity checked in function
5998 and procedure calls at the point of call.
6000 @item -gnatVm
6001 @emph{Validity checks for @code{in out} mode parameters.}
6002 @cindex @option{-gnatVm} (@command{gcc})
6003 Arguments for parameters of mode @code{in out} are validity checked in
6004 procedure calls at the point of call. The @code{'m'} here stands for
6005 modify, since this concerns parameters that can be modified by the call.
6006 Note that there is no specific option to test @code{out} parameters,
6007 but any reference within the subprogram will be tested in the usual
6008 manner, and if an invalid value is copied back, any reference to it
6009 will be subject to validity checking.
6011 @item -gnatVn
6012 @emph{No validity checks.}
6013 @cindex @option{-gnatVn} (@command{gcc})
6014 This switch turns off all validity checking, including the default checking
6015 for case statements and left hand side subscripts. Note that the use of
6016 the switch @option{-gnatp} suppresses all run-time checks, including
6017 validity checks, and thus implies @option{-gnatVn}. When this switch
6018 is used, it cancels any other @option{-gnatV} previously issued.
6020 @item -gnatVo
6021 @emph{Validity checks for operator and attribute operands.}
6022 @cindex @option{-gnatVo} (@command{gcc})
6023 Arguments for predefined operators and attributes are validity checked.
6024 This includes all operators in package @code{Standard},
6025 the shift operators defined as intrinsic in package @code{Interfaces}
6026 and operands for attributes such as @code{Pos}. Checks are also made
6027 on individual component values for composite comparisons, and on the
6028 expressions in type conversions and qualified expressions. Checks are
6029 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6031 @item -gnatVp
6032 @emph{Validity checks for parameters.}
6033 @cindex @option{-gnatVp} (@command{gcc})
6034 This controls the treatment of parameters within a subprogram (as opposed
6035 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6036 of parameters on a call. If either of these call options is used, then
6037 normally an assumption is made within a subprogram that the input arguments
6038 have been validity checking at the point of call, and do not need checking
6039 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6040 is not made, and parameters are not assumed to be valid, so their validity
6041 will be checked (or rechecked) within the subprogram.
6043 @item -gnatVr
6044 @emph{Validity checks for function returns.}
6045 @cindex @option{-gnatVr} (@command{gcc})
6046 The expression in @code{return} statements in functions is validity
6047 checked.
6049 @item -gnatVs
6050 @emph{Validity checks for subscripts.}
6051 @cindex @option{-gnatVs} (@command{gcc})
6052 All subscripts expressions are checked for validity, whether they appear
6053 on the right side or left side (in default mode only left side subscripts
6054 are validity checked).
6056 @item -gnatVt
6057 @emph{Validity checks for tests.}
6058 @cindex @option{-gnatVt} (@command{gcc})
6059 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6060 statements are checked, as well as guard expressions in entry calls.
6062 @end table
6064 @noindent
6065 The @option{-gnatV} switch may be followed by
6066 a string of letters
6067 to turn on a series of validity checking options.
6068 For example,
6069 @option{-gnatVcr}
6070 specifies that in addition to the default validity checking, copies and
6071 function return expressions are to be validity checked.
6072 In order to make it easier
6073 to specify the desired combination of effects,
6074 the upper case letters @code{CDFIMORST} may
6075 be used to turn off the corresponding lower case option.
6076 Thus
6077 @option{-gnatVaM}
6078 turns on all validity checking options except for
6079 checking of @code{@b{in out}} procedure arguments.
6081 The specification of additional validity checking generates extra code (and
6082 in the case of @option{-gnatVa} the code expansion can be substantial).
6083 However, these additional checks can be very useful in detecting
6084 uninitialized variables, incorrect use of unchecked conversion, and other
6085 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6086 is useful in conjunction with the extra validity checking, since this
6087 ensures that wherever possible uninitialized variables have invalid values.
6089 See also the pragma @code{Validity_Checks} which allows modification of
6090 the validity checking mode at the program source level, and also allows for
6091 temporary disabling of validity checks.
6093 @node Style Checking
6094 @subsection Style Checking
6095 @findex Style checking
6097 @noindent
6098 The @option{-gnatyx} switch
6099 @cindex @option{-gnaty} (@command{gcc})
6100 causes the compiler to
6101 enforce specified style rules. A limited set of style rules has been used
6102 in writing the GNAT sources themselves. This switch allows user programs
6103 to activate all or some of these checks. If the source program fails a
6104 specified style check, an appropriate message is given, preceded by
6105 the character sequence ``(style)''. This message does not prevent
6106 successful compilation (unless the @option{-gnatwe} switch is used).
6108 Note that this is by no means intended to be a general facility for
6109 checking arbitrary coding standards. It is simply an embedding of the
6110 style rules we have chosen for the GNAT sources. If you are starting
6111 a project which does not have established style standards, you may
6112 find it useful to adopt the entire set of GNAT coding standards, or
6113 some subset of them.
6114 @ifclear FSFEDITION
6115 If you already have an established set of coding
6116 standards, then the selected style checking options may
6117 indeed correspond to choices you have made, but for general checking
6118 of an existing set of coding rules, you should look to the gnatcheck
6119 tool, which is designed for that purpose.
6120 @end ifclear
6122 The string @var{x} is a sequence of letters or digits
6123 indicating the particular style
6124 checks to be performed. The following checks are defined:
6126 @table @option
6127 @c !sort!
6128 @item 0-9
6129 @emph{Specify indentation level.}
6130 If a digit from 1-9 appears
6131 in the string after @option{-gnaty}
6132 then proper indentation is checked, with the digit indicating the
6133 indentation level required. A value of zero turns off this style check.
6134 The general style of required indentation is as specified by
6135 the examples in the Ada Reference Manual. Full line comments must be
6136 aligned with the @code{--} starting on a column that is a multiple of
6137 the alignment level, or they may be aligned the same way as the following
6138 non-blank line (this is useful when full line comments appear in the middle
6139 of a statement, or they may be aligned with the source line on the previous
6140 non-blank line.
6142 @item a
6143 @emph{Check attribute casing.}
6144 Attribute names, including the case of keywords such as @code{digits}
6145 used as attributes names, must be written in mixed case, that is, the
6146 initial letter and any letter following an underscore must be uppercase.
6147 All other letters must be lowercase.
6149 @item A
6150 @emph{Use of array index numbers in array attributes.}
6151 When using the array attributes First, Last, Range,
6152 or Length, the index number must be omitted for one-dimensional arrays
6153 and is required for multi-dimensional arrays.
6155 @item b
6156 @emph{Blanks not allowed at statement end.}
6157 Trailing blanks are not allowed at the end of statements. The purpose of this
6158 rule, together with h (no horizontal tabs), is to enforce a canonical format
6159 for the use of blanks to separate source tokens.
6161 @item B
6162 @emph{Check Boolean operators.}
6163 The use of AND/OR operators is not permitted except in the cases of modular
6164 operands, array operands, and simple stand-alone boolean variables or
6165 boolean constants. In all other cases @code{and then}/@code{or else} are
6166 required.
6168 @item c
6169 @emph{Check comments, double space.}
6170 Comments must meet the following set of rules:
6172 @itemize @bullet
6174 @item
6175 The ``@code{--}'' that starts the column must either start in column one,
6176 or else at least one blank must precede this sequence.
6178 @item
6179 Comments that follow other tokens on a line must have at least one blank
6180 following the ``@code{--}'' at the start of the comment.
6182 @item
6183 Full line comments must have at least two blanks following the
6184 ``@code{--}'' that starts the comment, with the following exceptions.
6186 @item
6187 A line consisting only of the ``@code{--}'' characters, possibly preceded
6188 by blanks is permitted.
6190 @item
6191 A comment starting with ``@code{--x}'' where @code{x} is a special character
6192 is permitted.
6193 This allows proper processing of the output generated by specialized tools
6194 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6195 annotation
6196 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6197 special character is defined as being in one of the ASCII ranges
6198 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6199 Note that this usage is not permitted
6200 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6202 @item
6203 A line consisting entirely of minus signs, possibly preceded by blanks, is
6204 permitted. This allows the construction of box comments where lines of minus
6205 signs are used to form the top and bottom of the box.
6207 @item
6208 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6209 least one blank follows the initial ``@code{--}''. Together with the preceding
6210 rule, this allows the construction of box comments, as shown in the following
6211 example:
6212 @smallexample
6213 ---------------------------
6214 -- This is a box comment --
6215 -- with two text lines.  --
6216 ---------------------------
6217 @end smallexample
6218 @end itemize
6220 @item C
6221 @emph{Check comments, single space.}
6222 This is identical to @code{c} except that only one space
6223 is required following the @code{--} of a comment instead of two.
6225 @item d
6226 @emph{Check no DOS line terminators present.}
6227 All lines must be terminated by a single ASCII.LF
6228 character (in particular the DOS line terminator sequence CR/LF is not
6229 allowed).
6231 @item e
6232 @emph{Check end/exit labels.}
6233 Optional labels on @code{end} statements ending subprograms and on
6234 @code{exit} statements exiting named loops, are required to be present.
6236 @item f
6237 @emph{No form feeds or vertical tabs.}
6238 Neither form feeds nor vertical tab characters are permitted
6239 in the source text.
6241 @item g
6242 @emph{GNAT style mode.}
6243 The set of style check switches is set to match that used by the GNAT sources.
6244 This may be useful when developing code that is eventually intended to be
6245 incorporated into GNAT. Currently this is equivalent to @option{-gnatwydISux})
6246 but additional style switches may be added to this set in the future without
6247 advance notice.
6249 @item h
6250 @emph{No horizontal tabs.}
6251 Horizontal tab characters are not permitted in the source text.
6252 Together with the b (no blanks at end of line) check, this
6253 enforces a canonical form for the use of blanks to separate
6254 source tokens.
6256 @item i
6257 @emph{Check if-then layout.}
6258 The keyword @code{then} must appear either on the same
6259 line as corresponding @code{if}, or on a line on its own, lined
6260 up under the @code{if}.
6262 @item I
6263 @emph{check mode IN keywords.}
6264 Mode @code{in} (the default mode) is not
6265 allowed to be given explicitly. @code{in out} is fine,
6266 but not @code{in} on its own.
6268 @item k
6269 @emph{Check keyword casing.}
6270 All keywords must be in lower case (with the exception of keywords
6271 such as @code{digits} used as attribute names to which this check
6272 does not apply).
6274 @item l
6275 @emph{Check layout.}
6276 Layout of statement and declaration constructs must follow the
6277 recommendations in the Ada Reference Manual, as indicated by the
6278 form of the syntax rules. For example an @code{else} keyword must
6279 be lined up with the corresponding @code{if} keyword.
6281 There are two respects in which the style rule enforced by this check
6282 option are more liberal than those in the Ada Reference Manual. First
6283 in the case of record declarations, it is permissible to put the
6284 @code{record} keyword on the same line as the @code{type} keyword, and
6285 then the @code{end} in @code{end record} must line up under @code{type}.
6286 This is also permitted when the type declaration is split on two lines.
6287 For example, any of the following three layouts is acceptable:
6289 @smallexample @c ada
6290 @cartouche
6291 @b{type} q @b{is} @b{record}
6292    a : integer;
6293    b : integer;
6294 @b{end} @b{record};
6296 @b{type} q @b{is}
6297    @b{record}
6298       a : integer;
6299       b : integer;
6300    @b{end} @b{record};
6302 @b{type} q @b{is}
6303    @b{record}
6304       a : integer;
6305       b : integer;
6306 @b{end} @b{record};
6308 @end cartouche
6309 @end smallexample
6311 @noindent
6312 Second, in the case of a block statement, a permitted alternative
6313 is to put the block label on the same line as the @code{declare} or
6314 @code{begin} keyword, and then line the @code{end} keyword up under
6315 the block label. For example both the following are permitted:
6317 @smallexample @c ada
6318 @cartouche
6319 Block : @b{declare}
6320    A : Integer := 3;
6321 @b{begin}
6322    Proc (A, A);
6323 @b{end} Block;
6325 Block :
6326    @b{declare}
6327       A : Integer := 3;
6328    @b{begin}
6329       Proc (A, A);
6330    @b{end} Block;
6331 @end cartouche
6332 @end smallexample
6334 @noindent
6335 The same alternative format is allowed for loops. For example, both of
6336 the following are permitted:
6338 @smallexample @c ada
6339 @cartouche
6340 Clear : @b{while} J < 10 @b{loop}
6341    A (J) := 0;
6342 @b{end} @b{loop} Clear;
6344 Clear :
6345    @b{while} J < 10 @b{loop}
6346       A (J) := 0;
6347    @b{end} @b{loop} Clear;
6348 @end cartouche
6349 @end smallexample
6351 @item Lnnn
6352 @emph{Set maximum nesting level.}
6353 The maximum level of nesting of constructs (including subprograms, loops,
6354 blocks, packages, and conditionals) may not exceed the given value
6355 @option{nnn}. A value of zero disconnects this style check.
6357 @item m
6358 @emph{Check maximum line length.}
6359 The length of source lines must not exceed 79 characters, including
6360 any trailing blanks. The value of 79 allows convenient display on an
6361 80 character wide device or window, allowing for possible special
6362 treatment of 80 character lines. Note that this count is of
6363 characters in the source text. This means that a tab character counts
6364 as one character in this count and a wide character sequence counts as
6365 a single character (however many bytes are needed in the encoding).
6367 @item Mnnn
6368 @emph{Set maximum line length.}
6369 The length of lines must not exceed the
6370 given value @option{nnn}. The maximum value that can be specified is 32767.
6371 If neither style option for setting the line length is used, then the
6372 default is 255. This also controls the maximum length of lexical elements,
6373 where the only restriction is that they must fit on a single line.
6375 @item n
6376 @emph{Check casing of entities in Standard.}
6377 Any identifier from Standard must be cased
6378 to match the presentation in the Ada Reference Manual (for example,
6379 @code{Integer} and @code{ASCII.NUL}).
6381 @item N
6382 @emph{Turn off all style checks.}
6383 All style check options are turned off.
6385 @item o
6386 @emph{Check order of subprogram bodies.}
6387 All subprogram bodies in a given scope
6388 (e.g.@: a package body) must be in alphabetical order. The ordering
6389 rule uses normal Ada rules for comparing strings, ignoring casing
6390 of letters, except that if there is a trailing numeric suffix, then
6391 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6392 before Junk10).
6394 @item O
6395 @emph{Check that overriding subprograms are explicitly marked as such.}
6396 The declaration of a primitive operation of a type extension that overrides
6397 an inherited operation must carry an overriding indicator.
6399 @item p
6400 @emph{Check pragma casing.}
6401 Pragma names must be written in mixed case, that is, the
6402 initial letter and any letter following an underscore must be uppercase.
6403 All other letters must be lowercase. An exception is that SPARK_Mode is
6404 allowed as an alternative for Spark_Mode.
6406 @item r
6407 @emph{Check references.}
6408 All identifier references must be cased in the same way as the
6409 corresponding declaration. No specific casing style is imposed on
6410 identifiers. The only requirement is for consistency of references
6411 with declarations.
6413 @item s
6414 @emph{Check separate specs.}
6415 Separate declarations (``specs'') are required for subprograms (a
6416 body is not allowed to serve as its own declaration). The only
6417 exception is that parameterless library level procedures are
6418 not required to have a separate declaration. This exception covers
6419 the most frequent form of main program procedures.
6421 @item S
6422 @emph{Check no statements after @code{then}/@code{else}.}
6423 No statements are allowed
6424 on the same line as a @code{then} or @code{else} keyword following the
6425 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6426 affected, and a special exception allows a pragma to appear after @code{else}.
6428 @item t
6429 @emph{Check token spacing.}
6430 The following token spacing rules are enforced:
6432 @itemize @bullet
6434 @item
6435 The keywords @code{abs} and @code{not} must be followed by a space.
6437 @item
6438 The token @code{=>} must be surrounded by spaces.
6440 @item
6441 The token @code{<>} must be preceded by a space or a left parenthesis.
6443 @item
6444 Binary operators other than @code{**} must be surrounded by spaces.
6445 There is no restriction on the layout of the @code{**} binary operator.
6447 @item
6448 Colon must be surrounded by spaces.
6450 @item
6451 Colon-equal (assignment, initialization) must be surrounded by spaces.
6453 @item
6454 Comma must be the first non-blank character on the line, or be
6455 immediately preceded by a non-blank character, and must be followed
6456 by a space.
6458 @item
6459 If the token preceding a left parenthesis ends with a letter or digit, then
6460 a space must separate the two tokens.
6462 @item
6463 if the token following a right parenthesis starts with a letter or digit, then
6464 a space must separate the two tokens.
6466 @item
6467 A right parenthesis must either be the first non-blank character on
6468 a line, or it must be preceded by a non-blank character.
6470 @item
6471 A semicolon must not be preceded by a space, and must not be followed by
6472 a non-blank character.
6474 @item
6475 A unary plus or minus may not be followed by a space.
6477 @item
6478 A vertical bar must be surrounded by spaces.
6479 @end itemize
6481 Exactly one blank (and no other white space) must appear between
6482 a @code{not} token and a following @code{in} token.
6484 @item u
6485 @emph{Check unnecessary blank lines.}
6486 Unnecessary blank lines are not allowed. A blank line is considered
6487 unnecessary if it appears at the end of the file, or if more than
6488 one blank line occurs in sequence.
6490 @item x
6491 @emph{Check extra parentheses.}
6492 Unnecessary extra level of parentheses (C-style) are not allowed
6493 around conditions in @code{if} statements, @code{while} statements and
6494 @code{exit} statements.
6496 @item y
6497 @emph{Set all standard style check options}
6498 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6499 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6500 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6501 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6503 @item -
6504 @emph{Remove style check options}
6505 This causes any subsequent options in the string to act as canceling the
6506 corresponding style check option. To cancel maximum nesting level control,
6507 use @option{L} parameter witout any integer value after that, because any
6508 digit following @option{-} in the parameter string of the @option{-gnaty}
6509 option will be threated as canceling indentation check. The same is true
6510 for @option{M} parameter. @option{y} and @option{N} parameters are not
6511 allowed after @option{-}.
6513 @item +
6514 This causes any subsequent options in the string to enable the corresponding
6515 style check option. That is, it cancels the effect of a previous -,
6516 if any.
6518 @end table
6520 @noindent
6521 In the above rules, appearing in column one is always permitted, that is,
6522 counts as meeting either a requirement for a required preceding space,
6523 or as meeting a requirement for no preceding space.
6525 Appearing at the end of a line is also always permitted, that is, counts
6526 as meeting either a requirement for a following space, or as meeting
6527 a requirement for no following space.
6529 @noindent
6530 If any of these style rules is violated, a message is generated giving
6531 details on the violation. The initial characters of such messages are
6532 always ``@code{(style)}''. Note that these messages are treated as warning
6533 messages, so they normally do not prevent the generation of an object
6534 file. The @option{-gnatwe} switch can be used to treat warning messages,
6535 including style messages, as fatal errors.
6537 The switch
6538 @option{-gnaty} on its own (that is not
6539 followed by any letters or digits) is equivalent
6540 to the use of @option{-gnatyy} as described above, that is all
6541 built-in standard style check options are enabled.
6544 The switch
6545 @option{-gnatyN}
6546 clears any previously set style checks.
6548 @node Run-Time Checks
6549 @subsection Run-Time Checks
6550 @cindex Division by zero
6551 @cindex Access before elaboration
6552 @cindex Checks, division by zero
6553 @cindex Checks, access before elaboration
6554 @cindex Checks, stack overflow checking
6556 @noindent
6557 By default, the following checks are suppressed: integer overflow
6558 checks, stack overflow checks, and checks for access before
6559 elaboration on subprogram calls. All other checks, including range
6560 checks and array bounds checks, are turned on by default. The
6561 following @command{gcc} switches refine this default behavior.
6563 @table @option
6564 @c !sort!
6565 @item -gnatp
6566 @cindex @option{-gnatp} (@command{gcc})
6567 @cindex Suppressing checks
6568 @cindex Checks, suppressing
6569 @findex Suppress
6570 This switch causes the unit to be compiled
6571 as though @code{pragma Suppress (All_checks)}
6572 had been present in the source. Validity checks are also eliminated (in
6573 other words @option{-gnatp} also implies @option{-gnatVn}.
6574 Use this switch to improve the performance
6575 of the code at the expense of safety in the presence of invalid data or
6576 program bugs.
6578 Note that when checks are suppressed, the compiler is allowed, but not
6579 required, to omit the checking code. If the run-time cost of the
6580 checking code is zero or near-zero, the compiler will generate it even
6581 if checks are suppressed. In particular, if the compiler can prove
6582 that a certain check will necessarily fail, it will generate code to
6583 do an unconditional ``raise'', even if checks are suppressed. The
6584 compiler warns in this case. Another case in which checks may not be
6585 eliminated is when they are embedded in certain run time routines such
6586 as math library routines.
6588 Of course, run-time checks are omitted whenever the compiler can prove
6589 that they will not fail, whether or not checks are suppressed.
6591 Note that if you suppress a check that would have failed, program
6592 execution is erroneous, which means the behavior is totally
6593 unpredictable. The program might crash, or print wrong answers, or
6594 do anything else. It might even do exactly what you wanted it to do
6595 (and then it might start failing mysteriously next week or next
6596 year). The compiler will generate code based on the assumption that
6597 the condition being checked is true, which can result in erroneous
6598 execution if that assumption is wrong.
6600 The checks subject to suppression include all the checks defined by
6601 the Ada standard, the additional implementation defined checks
6602 @code{Alignment_Check},
6603 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, and
6604 @code{Validity_Check}, as well as any checks introduced using
6605 @code{pragma Check_Name}. Note that @code{Atomic_Synchronization}
6606 is not automatically suppressed by use of this option.
6608 If the code depends on certain checks being active, you can use
6609 pragma @code{Unsuppress} either as a configuration pragma or as
6610 a local pragma to make sure that a specified check is performed
6611 even if @option{gnatp} is specified.
6613 The @option{-gnatp} switch has no effect if a subsequent
6614 @option{-gnat-p} switch appears.
6616 @item -gnat-p
6617 @cindex @option{-gnat-p} (@command{gcc})
6618 @cindex Suppressing checks
6619 @cindex Checks, suppressing
6620 @findex Suppress
6621 This switch cancels the effect of a previous @option{gnatp} switch.
6623 @item -gnato??
6624 @cindex @option{-gnato??} (@command{gcc})
6625 @cindex Overflow checks
6626 @cindex Overflow mode
6627 @cindex Check, overflow
6628 This switch controls the mode used for computing intermediate
6629 arithmetic integer operations, and also enables overflow checking.
6630 For a full description of overflow mode and checking control, see
6631 the ``Overflow Check Handling in GNAT'' appendix in this
6632 User's Guide.
6634 Overflow checks are always enabled by this switch. The argument
6635 controls the mode, using the codes
6637 @itemize
6638 @item 1 = STRICT
6639 In STRICT mode, intermediate operations are always done using the
6640 base type, and overflow checking ensures that the result is within
6641 the base type range.
6643 @item 2 = MINIMIZED
6644 In MINIMIZED mode, overflows in intermediate operations are avoided
6645 where possible by using a larger integer type for the computation
6646 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6647 the result fits in this larger integer type.
6649 @item 3 = ELIMINATED
6650 In ELIMINATED mode, overflows in intermediate operations are avoided
6651 by using multi-precision arithmetic. In this case, overflow checking
6652 has no effect on intermediate operations (since overflow is impossible).
6653 @end itemize
6655 If two digits are present after @option{-gnato} then the first digit
6656 sets the mode for expressions outside assertions, and the second digit
6657 sets the mode for expressions within assertions. Here assertions is used
6658 in the technical sense (which includes for example precondition and
6659 postcondition expressions).
6661 If one digit is present, the corresponding mode is applicable to both
6662 expressions within and outside assertion expressions.
6664 If no digits are present, the default is to enable overflow checks
6665 and set STRICT mode for both kinds of expressions. This is compatible
6666 with the use of @option{-gnato} in previous versions of GNAT.
6668 @findex Machine_Overflows
6669 Note that the @option{-gnato??} switch does not affect the code generated
6670 for any floating-point operations; it applies only to integer semantics.
6671 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6672 attribute set to @code{False} and the normal mode of operation is to
6673 generate IEEE NaN and infinite values on overflow or invalid operations
6674 (such as dividing 0.0 by 0.0).
6676 The reason that we distinguish overflow checking from other kinds of
6677 range constraint checking is that a failure of an overflow check, unlike
6678 for example the failure of a range check, can result in an incorrect
6679 value, but cannot cause random memory destruction (like an out of range
6680 subscript), or a wild jump (from an out of range case value). Overflow
6681 checking is also quite expensive in time and space, since in general it
6682 requires the use of double length arithmetic.
6684 Note again that the default is @option{-gnato00},
6685 so overflow checking is not performed in default mode. This means that out of
6686 the box, with the default settings, @value{EDITION} does not do all the checks
6687 expected from the language description in the Ada Reference Manual.
6688 If you want all constraint checks to be performed, as described in this Manual,
6689 then you must explicitly use the @option{-gnato??}
6690 switch either on the @command{gnatmake} or @command{gcc} command.
6692 @item -gnatE
6693 @cindex @option{-gnatE} (@command{gcc})
6694 @cindex Elaboration checks
6695 @cindex Check, elaboration
6696 Enables dynamic checks for access-before-elaboration
6697 on subprogram calls and generic instantiations.
6698 Note that @option{-gnatE} is not necessary for safety, because in the
6699 default mode, GNAT ensures statically that the checks would not fail.
6700 For full details of the effect and use of this switch,
6701 @xref{Compiling with gcc}.
6703 @item -fstack-check
6704 @cindex @option{-fstack-check} (@command{gcc})
6705 @cindex Stack Overflow Checking
6706 @cindex Checks, stack overflow checking
6707 Activates stack overflow checking. For full details of the effect and use of
6708 this switch see @ref{Stack Overflow Checking}.
6709 @end table
6711 @findex Unsuppress
6712 @noindent
6713 The setting of these switches only controls the default setting of the
6714 checks. You may modify them using either @code{Suppress} (to remove
6715 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6716 the program source.
6718 @node Using gcc for Syntax Checking
6719 @subsection Using @command{gcc} for Syntax Checking
6720 @table @option
6721 @item -gnats
6722 @cindex @option{-gnats} (@command{gcc})
6724 @noindent
6725 The @code{s} stands for ``syntax''.
6727 Run GNAT in syntax checking only mode. For
6728 example, the command
6730 @smallexample
6731 $ gcc -c -gnats x.adb
6732 @end smallexample
6734 @noindent
6735 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6736 series of files in a single command
6737 , and can use wild cards to specify such a group of files.
6738 Note that you must specify the @option{-c} (compile
6739 only) flag in addition to the @option{-gnats} flag.
6741 You may use other switches in conjunction with @option{-gnats}. In
6742 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6743 format of any generated error messages.
6745 When the source file is empty or contains only empty lines and/or comments,
6746 the output is a warning:
6748 @smallexample
6749 $ gcc -c -gnats -x ada toto.txt
6750 toto.txt:1:01: warning: empty file, contains no compilation units
6752 @end smallexample
6754 Otherwise, the output is simply the error messages, if any. No object file or
6755 ALI file is generated by a syntax-only compilation. Also, no units other
6756 than the one specified are accessed. For example, if a unit @code{X}
6757 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6758 check only mode does not access the source file containing unit
6759 @code{Y}.
6761 @cindex Multiple units, syntax checking
6762 Normally, GNAT allows only a single unit in a source file. However, this
6763 restriction does not apply in syntax-check-only mode, and it is possible
6764 to check a file containing multiple compilation units concatenated
6765 together. This is primarily used by the @code{gnatchop} utility
6766 (@pxref{Renaming Files with gnatchop}).
6767 @end table
6769 @node Using gcc for Semantic Checking
6770 @subsection Using @command{gcc} for Semantic Checking
6771 @table @option
6772 @item -gnatc
6773 @cindex @option{-gnatc} (@command{gcc})
6775 @noindent
6776 The @code{c} stands for ``check''.
6777 Causes the compiler to operate in semantic check mode,
6778 with full checking for all illegalities specified in the
6779 Ada Reference Manual, but without generation of any object code
6780 (no object file is generated).
6782 Because dependent files must be accessed, you must follow the GNAT
6783 semantic restrictions on file structuring to operate in this mode:
6785 @itemize @bullet
6786 @item
6787 The needed source files must be accessible
6788 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6790 @item
6791 Each file must contain only one compilation unit.
6793 @item
6794 The file name and unit name must match (@pxref{File Naming Rules}).
6795 @end itemize
6797 The output consists of error messages as appropriate. No object file is
6798 generated. An @file{ALI} file is generated for use in the context of
6799 cross-reference tools, but this file is marked as not being suitable
6800 for binding (since no object file is generated).
6801 The checking corresponds exactly to the notion of
6802 legality in the Ada Reference Manual.
6804 Any unit can be compiled in semantics-checking-only mode, including
6805 units that would not normally be compiled (subunits,
6806 and specifications where a separate body is present).
6807 @end table
6809 @node Compiling Different Versions of Ada
6810 @subsection Compiling Different Versions of Ada
6812 @noindent
6813 The switches described in this section allow you to explicitly specify
6814 the version of the Ada language that your programs are written in.
6815 The default mode is Ada 2012,
6816 but you can also specify Ada 95, Ada 2005 mode, or
6817 indicate Ada 83 compatibility mode.
6819 @table @option
6820 @cindex Compatibility with Ada 83
6822 @item -gnat83 (Ada 83 Compatibility Mode)
6823 @cindex @option{-gnat83} (@command{gcc})
6824 @cindex ACVC, Ada 83 tests
6825 @cindex Ada 83 mode
6827 @noindent
6828 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6829 specifies that the program is to be compiled in Ada 83 mode. With
6830 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6831 semantics where this can be done easily.
6832 It is not possible to guarantee this switch does a perfect
6833 job; some subtle tests, such as are
6834 found in earlier ACVC tests (and that have been removed from the ACATS suite
6835 for Ada 95), might not compile correctly.
6836 Nevertheless, this switch may be useful in some circumstances, for example
6837 where, due to contractual reasons, existing code needs to be maintained
6838 using only Ada 83 features.
6840 With few exceptions (most notably the need to use @code{<>} on
6841 @cindex Generic formal parameters
6842 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6843 reserved words, and the use of packages
6844 with optional bodies), it is not necessary to specify the
6845 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6846 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6847 a correct Ada 83 program is usually also a correct program
6848 in these later versions of the language standard.
6849 For further information, please refer to @ref{Compatibility and Porting Guide}.
6851 @item -gnat95 (Ada 95 mode)
6852 @cindex @option{-gnat95} (@command{gcc})
6853 @cindex Ada 95 mode
6855 @noindent
6856 This switch directs the compiler to implement the Ada 95 version of the
6857 language.
6858 Since Ada 95 is almost completely upwards
6859 compatible with Ada 83, Ada 83 programs may generally be compiled using
6860 this switch (see the description of the @option{-gnat83} switch for further
6861 information about Ada 83 mode).
6862 If an Ada 2005 program is compiled in Ada 95 mode,
6863 uses of the new Ada 2005 features will cause error
6864 messages or warnings.
6866 This switch also can be used to cancel the effect of a previous
6867 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6868 switch earlier in the command line.
6870 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6871 @cindex @option{-gnat05} (@command{gcc})
6872 @cindex @option{-gnat2005} (@command{gcc})
6873 @cindex Ada 2005 mode
6875 @noindent
6876 This switch directs the compiler to implement the Ada 2005 version of the
6877 language, as documented in the official Ada standards document.
6878 Since Ada 2005 is almost completely upwards
6879 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6880 may generally be compiled using this switch (see the description of the
6881 @option{-gnat83} and @option{-gnat95} switches for further
6882 information).
6884 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6885 @cindex @option{-gnat12} (@command{gcc})
6886 @cindex @option{-gnat2012} (@command{gcc})
6887 @cindex Ada 2012 mode
6889 @noindent
6890 This switch directs the compiler to implement the Ada 2012 version of the
6891 language (also the default).
6892 Since Ada 2012 is almost completely upwards
6893 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6894 Ada 83 and Ada 95 programs
6895 may generally be compiled using this switch (see the description of the
6896 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6897 for further information).
6899 @item -gnatX (Enable GNAT Extensions)
6900 @cindex @option{-gnatX} (@command{gcc})
6901 @cindex Ada language extensions
6902 @cindex GNAT extensions
6904 @noindent
6905 This switch directs the compiler to implement the latest version of the
6906 language (currently Ada 2012) and also to enable certain GNAT implementation
6907 extensions that are not part of any Ada standard. For a full list of these
6908 extensions, see the GNAT reference manual.
6910 @end table
6912 @node Character Set Control
6913 @subsection Character Set Control
6914 @table @option
6915 @item -gnati@var{c}
6916 @cindex @option{-gnati} (@command{gcc})
6918 @noindent
6919 Normally GNAT recognizes the Latin-1 character set in source program
6920 identifiers, as described in the Ada Reference Manual.
6921 This switch causes
6922 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6923 single character  indicating the character set, as follows:
6925 @table @code
6926 @item 1
6927 ISO 8859-1 (Latin-1) identifiers
6929 @item 2
6930 ISO 8859-2 (Latin-2) letters allowed in identifiers
6932 @item 3
6933 ISO 8859-3 (Latin-3) letters allowed in identifiers
6935 @item 4
6936 ISO 8859-4 (Latin-4) letters allowed in identifiers
6938 @item 5
6939 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6941 @item 9
6942 ISO 8859-15 (Latin-9) letters allowed in identifiers
6944 @item p
6945 IBM PC letters (code page 437) allowed in identifiers
6947 @item 8
6948 IBM PC letters (code page 850) allowed in identifiers
6950 @item f
6951 Full upper-half codes allowed in identifiers
6953 @item n
6954 No upper-half codes allowed in identifiers
6956 @item w
6957 Wide-character codes (that is, codes greater than 255)
6958 allowed in identifiers
6959 @end table
6961 @xref{Foreign Language Representation}, for full details on the
6962 implementation of these character sets.
6964 @item -gnatW@var{e}
6965 @cindex @option{-gnatW} (@command{gcc})
6966 Specify the method of encoding for wide characters.
6967 @var{e} is one of the following:
6969 @table @code
6971 @item h
6972 Hex encoding (brackets coding also recognized)
6974 @item u
6975 Upper half encoding (brackets encoding also recognized)
6977 @item s
6978 Shift/JIS encoding (brackets encoding also recognized)
6980 @item e
6981 EUC encoding (brackets encoding also recognized)
6983 @item 8
6984 UTF-8 encoding (brackets encoding also recognized)
6986 @item b
6987 Brackets encoding only (default value)
6988 @end table
6989 For full details on these encoding
6990 methods see @ref{Wide_Character Encodings}.
6991 Note that brackets coding is always accepted, even if one of the other
6992 options is specified, so for example @option{-gnatW8} specifies that both
6993 brackets and UTF-8 encodings will be recognized. The units that are
6994 with'ed directly or indirectly will be scanned using the specified
6995 representation scheme, and so if one of the non-brackets scheme is
6996 used, it must be used consistently throughout the program. However,
6997 since brackets encoding is always recognized, it may be conveniently
6998 used in standard libraries, allowing these libraries to be used with
6999 any of the available coding schemes.
7001 Note that brackets encoding only applies to program text. Within comments,
7002 brackets are considered to be normal graphic characters, and bracket sequences
7003 are never recognized as wide characters.
7005 If no @option{-gnatW?} parameter is present, then the default
7006 representation is normally Brackets encoding only. However, if the
7007 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7008 byte order mark or BOM for UTF-8), then these three characters are
7009 skipped and the default representation for the file is set to UTF-8.
7011 Note that the wide character representation that is specified (explicitly
7012 or by default) for the main program also acts as the default encoding used
7013 for Wide_Text_IO files if not specifically overridden by a WCEM form
7014 parameter.
7016 @end table
7018 When no @option{-gnatW?} is specified, then characters (other than wide
7019 characters represented using brackets notation) are treated as 8-bit
7020 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7021 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7022 characters in the range 16#00#..16#1F# are not accepted in program text
7023 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7024 in program text, but allowed and ignored in comments. Note in particular
7025 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7026 as an end of line in this default mode. If your source program contains
7027 instances of the NEL character used as a line terminator,
7028 you must use UTF-8 encoding for the whole
7029 source program. In default mode, all lines must be ended by a standard
7030 end of line sequence (CR, CR/LF, or LF).
7032 Note that the convention of simply accepting all upper half characters in
7033 comments means that programs that use standard ASCII for program text, but
7034 UTF-8 encoding for comments are accepted in default mode, providing that the
7035 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7036 This is a common mode for many programs with foreign language comments.
7038 @node File Naming Control
7039 @subsection File Naming Control
7041 @table @option
7042 @item -gnatk@var{n}
7043 @cindex @option{-gnatk} (@command{gcc})
7044 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7045 1-999, indicates the maximum allowable length of a file name (not
7046 including the @file{.ads} or @file{.adb} extension). The default is not
7047 to enable file name krunching.
7049 For the source file naming rules, @xref{File Naming Rules}.
7050 @end table
7052 @node Subprogram Inlining Control
7053 @subsection Subprogram Inlining Control
7055 @table @option
7056 @c !sort!
7057 @item -gnatn[12]
7058 @cindex @option{-gnatn} (@command{gcc})
7059 The @code{n} here is intended to suggest the first syllable of the
7060 word ``inline''.
7061 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7062 inlining to actually occur, optimization must be enabled and, in order
7063 to enable inlining of subprograms specified by pragma @code{Inline},
7064 you must also specify this switch.
7065 In the absence of this switch, GNAT does not attempt
7066 inlining and does not need to access the bodies of
7067 subprograms for which @code{pragma Inline} is specified if they are not
7068 in the current unit.
7070 You can optionally specify the inlining level: 1 for moderate inlining across
7071 modules, which is a good compromise between compilation times and performances
7072 at run time, or 2 for full inlining across modules, which may bring about
7073 longer compilation times. If no inlining level is specified, the compiler will
7074 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7075 @option{-Os} and 2 for @option{-O3}.
7077 If you specify this switch the compiler will access these bodies,
7078 creating an extra source dependency for the resulting object file, and
7079 where possible, the call will be inlined.
7080 For further details on when inlining is possible
7081 see @ref{Inlining of Subprograms}.
7083 @item -gnatN
7084 @cindex @option{-gnatN} (@command{gcc})
7085 This switch activates front-end inlining which also
7086 generates additional dependencies.
7088 When using a gcc-based back end (in practice this means using any version
7089 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7090 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7091 Historically front end inlining was more extensive than the gcc back end
7092 inlining, but that is no longer the case.
7093 @end table
7095 @node Auxiliary Output Control
7096 @subsection Auxiliary Output Control
7098 @table @option
7099 @item -gnatt
7100 @cindex @option{-gnatt} (@command{gcc})
7101 @cindex Writing internal trees
7102 @cindex Internal trees, writing to file
7103 Causes GNAT to write the internal tree for a unit to a file (with the
7104 extension @file{.adt}.
7105 This not normally required, but is used by separate analysis tools.
7106 Typically
7107 these tools do the necessary compilations automatically, so you should
7108 not have to specify this switch in normal operation.
7109 Note that the combination of switches @option{-gnatct}
7110 generates a tree in the form required by ASIS applications.
7112 @item -gnatu
7113 @cindex @option{-gnatu} (@command{gcc})
7114 Print a list of units required by this compilation on @file{stdout}.
7115 The listing includes all units on which the unit being compiled depends
7116 either directly or indirectly.
7118 @item -pass-exit-codes
7119 @cindex @option{-pass-exit-codes} (@command{gcc})
7120 If this switch is not used, the exit code returned by @command{gcc} when
7121 compiling multiple files indicates whether all source files have
7122 been successfully used to generate object files or not.
7124 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7125 exit status and allows an integrated development environment to better
7126 react to a compilation failure. Those exit status are:
7128 @table @asis
7129 @item 5
7130 There was an error in at least one source file.
7131 @item 3
7132 At least one source file did not generate an object file.
7133 @item 2
7134 The compiler died unexpectedly (internal error for example).
7135 @item 0
7136 An object file has been generated for every source file.
7137 @end table
7138 @end table
7140 @node Debugging Control
7141 @subsection Debugging Control
7143 @table @option
7144 @c !sort!
7145 @cindex Debugging options
7146 @item -gnatd@var{x}
7147 @cindex @option{-gnatd} (@command{gcc})
7148 Activate internal debugging switches. @var{x} is a letter or digit, or
7149 string of letters or digits, which specifies the type of debugging
7150 outputs desired. Normally these are used only for internal development
7151 or system debugging purposes. You can find full documentation for these
7152 switches in the body of the @code{Debug} unit in the compiler source
7153 file @file{debug.adb}.
7155 @item -gnatG[=nn]
7156 @cindex @option{-gnatG} (@command{gcc})
7157 This switch causes the compiler to generate auxiliary output containing
7158 a pseudo-source listing of the generated expanded code. Like most Ada
7159 compilers, GNAT works by first transforming the high level Ada code into
7160 lower level constructs. For example, tasking operations are transformed
7161 into calls to the tasking run-time routines. A unique capability of GNAT
7162 is to list this expanded code in a form very close to normal Ada source.
7163 This is very useful in understanding the implications of various Ada
7164 usage on the efficiency of the generated code. There are many cases in
7165 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7166 generate a lot of run-time code. By using @option{-gnatG} you can identify
7167 these cases, and consider whether it may be desirable to modify the coding
7168 approach to improve efficiency.
7170 The optional parameter @code{nn} if present after -gnatG specifies an
7171 alternative maximum line length that overrides the normal default of 72.
7172 This value is in the range 40-999999, values less than 40 being silently
7173 reset to 40. The equal sign is optional.
7175 The format of the output is very similar to standard Ada source, and is
7176 easily understood by an Ada programmer. The following special syntactic
7177 additions correspond to low level features used in the generated code that
7178 do not have any exact analogies in pure Ada source form. The following
7179 is a partial list of these special constructions. See the spec
7180 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7182 If the switch @option{-gnatL} is used in conjunction with
7183 @cindex @option{-gnatL} (@command{gcc})
7184 @option{-gnatG}, then the original source lines are interspersed
7185 in the expanded source (as comment lines with the original line number).
7187 @table @code
7188 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7189 Shows the storage pool being used for an allocator.
7191 @item at end @var{procedure-name};
7192 Shows the finalization (cleanup) procedure for a scope.
7194 @item (if @var{expr} then @var{expr} else @var{expr})
7195 Conditional expression equivalent to the @code{x?y:z} construction in C.
7197 @item @var{target}^(@var{source})
7198 A conversion with floating-point truncation instead of rounding.
7200 @item @var{target}?(@var{source})
7201 A conversion that bypasses normal Ada semantic checking. In particular
7202 enumeration types and fixed-point types are treated simply as integers.
7204 @item @var{target}?^(@var{source})
7205 Combines the above two cases.
7207 @item @var{x} #/ @var{y}
7208 @itemx @var{x} #mod @var{y}
7209 @itemx @var{x} #* @var{y}
7210 @itemx @var{x} #rem @var{y}
7211 A division or multiplication of fixed-point values which are treated as
7212 integers without any kind of scaling.
7214 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7215 Shows the storage pool associated with a @code{free} statement.
7217 @item [subtype or type declaration]
7218 Used to list an equivalent declaration for an internally generated
7219 type that is referenced elsewhere in the listing.
7221 @c @item freeze @var{type-name} @ovar{actions}
7222 @c Expanding @ovar macro inline (explanation in macro def comments)
7223 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7224 Shows the point at which @var{type-name} is frozen, with possible
7225 associated actions to be performed at the freeze point.
7227 @item reference @var{itype}
7228 Reference (and hence definition) to internal type @var{itype}.
7230 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7231 Intrinsic function call.
7233 @item @var{label-name} : label
7234 Declaration of label @var{labelname}.
7236 @item #$ @var{subprogram-name}
7237 An implicit call to a run-time support routine
7238 (to meet the requirement of H.3.1(9) in a
7239 convenient manner).
7241 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7242 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7243 @var{expr}, but handled more efficiently).
7245 @item [constraint_error]
7246 Raise the @code{Constraint_Error} exception.
7248 @item @var{expression}'reference
7249 A pointer to the result of evaluating @var{expression}.
7251 @item @var{target-type}!(@var{source-expression})
7252 An unchecked conversion of @var{source-expression} to @var{target-type}.
7254 @item [@var{numerator}/@var{denominator}]
7255 Used to represent internal real literals (that) have no exact
7256 representation in base 2-16 (for example, the result of compile time
7257 evaluation of the expression 1.0/27.0).
7258 @end table
7260 @item -gnatD[=nn]
7261 @cindex @option{-gnatD} (@command{gcc})
7262 When used in conjunction with @option{-gnatG}, this switch causes
7263 the expanded source, as described above for
7264 @option{-gnatG} to be written to files with names
7265 @file{xxx.dg}, where @file{xxx} is the normal file name,
7266 instead of to the standard output file. For
7267 example, if the source file name is @file{hello.adb}, then a file
7268 @file{hello.adb.dg} will be written.  The debugging
7269 information generated by the @command{gcc} @option{-g} switch
7270 will refer to the generated @file{xxx.dg} file. This allows
7271 you to do source level debugging using the generated code which is
7272 sometimes useful for complex code, for example to find out exactly
7273 which part of a complex construction raised an exception. This switch
7274 also suppress generation of cross-reference information (see
7275 @option{-gnatx}) since otherwise the cross-reference information
7276 would refer to the @file{.dg} file, which would cause
7277 confusion since this is not the original source file.
7279 Note that @option{-gnatD} actually implies @option{-gnatG}
7280 automatically, so it is not necessary to give both options.
7281 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7283 If the switch @option{-gnatL} is used in conjunction with
7284 @cindex @option{-gnatL} (@command{gcc})
7285 @option{-gnatDG}, then the original source lines are interspersed
7286 in the expanded source (as comment lines with the original line number).
7288 The optional parameter @code{nn} if present after -gnatD specifies an
7289 alternative maximum line length that overrides the normal default of 72.
7290 This value is in the range 40-999999, values less than 40 being silently
7291 reset to 40. The equal sign is optional.
7293 @item -gnatr
7294 @cindex @option{-gnatr} (@command{gcc})
7295 @cindex pragma Restrictions
7296 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7297 so that violation of restrictions causes warnings rather than illegalities.
7298 This is useful during the development process when new restrictions are added
7299 or investigated. The switch also causes pragma Profile to be treated as
7300 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7301 restriction warnings rather than restrictions.
7303 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7304 @cindex @option{-gnatR} (@command{gcc})
7305 This switch controls output from the compiler of a listing showing
7306 representation information for declared types and objects. For
7307 @option{-gnatR0}, no information is output (equivalent to omitting
7308 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7309 so @option{-gnatR} with no parameter has the same effect), size and alignment
7310 information is listed for declared array and record types. For
7311 @option{-gnatR2}, size and alignment information is listed for all
7312 declared types and objects. The @code{Linker_Section} is also listed for any
7313 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7314 latter case occurs for objects of a type for which a @code{Linker_Section}
7315 is set).
7317 Finally @option{-gnatR3} includes symbolic
7318 expressions for values that are computed at run time for
7319 variant records. These symbolic expressions have a mostly obvious
7320 format with #n being used to represent the value of the n'th
7321 discriminant. See source files @file{repinfo.ads/adb} in the
7322 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7323 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7324 the output is to a file with the name @file{file.rep} where
7325 file is the name of the corresponding source file.
7327 @item -gnatRm[s]
7328 This form of the switch controls output of subprogram conventions
7329 and parameter passing mechanisms for all subprograms. A following
7330 @code{s} means output to a file as described above.
7332 Note that it is possible for record components to have zero size. In
7333 this case, the component clause uses an obvious extension of permitted
7334 Ada syntax, for example @code{at 0 range 0 .. -1}.
7336 Representation information requires that code be generated (since it is the
7337 code generator that lays out complex data structures). If an attempt is made
7338 to output representation information when no code is generated, for example
7339 when a subunit is compiled on its own, then no information can be generated
7340 and the compiler outputs a message to this effect.
7342 @item -gnatS
7343 @cindex @option{-gnatS} (@command{gcc})
7344 The use of the switch @option{-gnatS} for an
7345 Ada compilation will cause the compiler to output a
7346 representation of package Standard in a form very
7347 close to standard Ada. It is not quite possible to
7348 do this entirely in standard Ada (since new
7349 numeric base types cannot be created in standard
7350 Ada), but the output is easily
7351 readable to any Ada programmer, and is useful to
7352 determine the characteristics of target dependent
7353 types in package Standard.
7355 @item -gnatx
7356 @cindex @option{-gnatx} (@command{gcc})
7357 Normally the compiler generates full cross-referencing information in
7358 the @file{ALI} file. This information is used by a number of tools,
7359 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7360 suppresses this information. This saves some space and may slightly
7361 speed up compilation, but means that these tools cannot be used.
7362 @end table
7364 @node Exception Handling Control
7365 @subsection Exception Handling Control
7367 @noindent
7368 GNAT uses two methods for handling exceptions at run-time. The
7369 @code{setjmp/longjmp} method saves the context when entering
7370 a frame with an exception handler. Then when an exception is
7371 raised, the context can be restored immediately, without the
7372 need for tracing stack frames. This method provides very fast
7373 exception propagation, but introduces significant overhead for
7374 the use of exception handlers, even if no exception is raised.
7376 The other approach is called ``zero cost'' exception handling.
7377 With this method, the compiler builds static tables to describe
7378 the exception ranges. No dynamic code is required when entering
7379 a frame containing an exception handler. When an exception is
7380 raised, the tables are used to control a back trace of the
7381 subprogram invocation stack to locate the required exception
7382 handler. This method has considerably poorer performance for
7383 the propagation of exceptions, but there is no overhead for
7384 exception handlers if no exception is raised. Note that in this
7385 mode and in the context of mixed Ada and C/C++ programming,
7386 to propagate an exception through a C/C++ code, the C/C++ code
7387 must be compiled with the @option{-funwind-tables} GCC's
7388 option.
7390 The following switches may be used to control which of the
7391 two exception handling methods is used.
7393 @table @option
7394 @c !sort!
7396 @item --RTS=sjlj
7397 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7398 This switch causes the setjmp/longjmp run-time (when available) to be used
7399 for exception handling. If the default
7400 mechanism for the target is zero cost exceptions, then
7401 this switch can be used to modify this default, and must be
7402 used for all units in the partition.
7403 This option is rarely used. One case in which it may be
7404 advantageous is if you have an application where exception
7405 raising is common and the overall performance of the
7406 application is improved by favoring exception propagation.
7408 @item --RTS=zcx
7409 @cindex @option{--RTS=zcx} (@command{gnatmake})
7410 @cindex Zero Cost Exceptions
7411 This switch causes the zero cost approach to be used
7412 for exception handling. If this is the default mechanism for the
7413 target (see below), then this switch is unneeded. If the default
7414 mechanism for the target is setjmp/longjmp exceptions, then
7415 this switch can be used to modify this default, and must be
7416 used for all units in the partition.
7417 This option can only be used if the zero cost approach
7418 is available for the target in use, otherwise it will generate an error.
7419 @end table
7421 @noindent
7422 The same option @option{--RTS} must be used both for @command{gcc}
7423 and @command{gnatbind}. Passing this option to @command{gnatmake}
7424 (@pxref{Switches for gnatmake}) will ensure the required consistency
7425 through the compilation and binding steps.
7427 @node Units to Sources Mapping Files
7428 @subsection Units to Sources Mapping Files
7430 @table @option
7432 @item -gnatem=@var{path}
7433 @cindex @option{-gnatem} (@command{gcc})
7434 A mapping file is a way to communicate to the compiler two mappings:
7435 from unit names to file names (without any directory information) and from
7436 file names to path names (with full directory information). These mappings
7437 are used by the compiler to short-circuit the path search.
7439 The use of mapping files is not required for correct operation of the
7440 compiler, but mapping files can improve efficiency, particularly when
7441 sources are read over a slow network connection. In normal operation,
7442 you need not be concerned with the format or use of mapping files,
7443 and the @option{-gnatem} switch is not a switch that you would use
7444 explicitly. It is intended primarily for use by automatic tools such as
7445 @command{gnatmake} running under the project file facility. The
7446 description here of the format of mapping files is provided
7447 for completeness and for possible use by other tools.
7449 A mapping file is a sequence of sets of three lines. In each set, the
7450 first line is the unit name, in lower case, with @code{%s} appended
7451 for specs and @code{%b} appended for bodies; the second line is the
7452 file name; and the third line is the path name.
7454 Example:
7455 @smallexample
7456    main%b
7457    main.2.ada
7458    /gnat/project1/sources/main.2.ada
7459 @end smallexample
7461 When the switch @option{-gnatem} is specified, the compiler will
7462 create in memory the two mappings from the specified file. If there is
7463 any problem (nonexistent file, truncated file or duplicate entries),
7464 no mapping will be created.
7466 Several @option{-gnatem} switches may be specified; however, only the
7467 last one on the command line will be taken into account.
7469 When using a project file, @command{gnatmake} creates a temporary
7470 mapping file and communicates it to the compiler using this switch.
7472 @end table
7474 @node Integrated Preprocessing
7475 @subsection Integrated Preprocessing
7477 @noindent
7478 GNAT sources may be preprocessed immediately before compilation.
7479 In this case, the actual
7480 text of the source is not the text of the source file, but is derived from it
7481 through a process called preprocessing. Integrated preprocessing is specified
7482 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7483 indicates, through a text file, the preprocessing data to be used.
7484 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7485 Note that integrated preprocessing applies only to Ada source files, it is
7486 not available for configuration pragma files.
7488 @noindent
7489 Note that when integrated preprocessing is used, the output from the
7490 preprocessor is not written to any external file. Instead it is passed
7491 internally to the compiler. If you need to preserve the result of
7492 preprocessing in a file, then you should use @command{gnatprep}
7493 to perform the desired preprocessing in stand-alone mode.
7495 @noindent
7496 It is recommended that @command{gnatmake} switch -s should be
7497 used when Integrated Preprocessing is used. The reason is that preprocessing
7498 with another Preprocessing Data file without changing the sources will
7499 not trigger recompilation without this switch.
7501 @noindent
7502 Note that @command{gnatmake} switch -m will almost
7503 always trigger recompilation for sources that are preprocessed,
7504 because @command{gnatmake} cannot compute the checksum of the source after
7505 preprocessing.
7507 @noindent
7508 The actual preprocessing function is described in details in section
7509 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7510 preprocessing is triggered and parameterized.
7512 @table @code
7514 @item -gnatep=@var{file}
7515 @cindex @option{-gnatep} (@command{gcc})
7516 This switch indicates to the compiler the file name (without directory
7517 information) of the preprocessor data file to use. The preprocessor data file
7518 should be found in the source directories. Note that when the compiler is
7519 called by a builder such as (@command{gnatmake} with a project
7520 file, if the object directory is not also a source directory, the builder needs
7521 to be called with @option{-x}.
7523 @noindent
7524 A preprocessing data file is a text file with significant lines indicating
7525 how should be preprocessed either a specific source or all sources not
7526 mentioned in other lines. A significant line is a nonempty, non-comment line.
7527 Comments are similar to Ada comments.
7529 @noindent
7530 Each significant line starts with either a literal string or the character '*'.
7531 A literal string is the file name (without directory information) of the source
7532 to preprocess. A character '*' indicates the preprocessing for all the sources
7533 that are not specified explicitly on other lines (order of the lines is not
7534 significant). It is an error to have two lines with the same file name or two
7535 lines starting with the character '*'.
7537 @noindent
7538 After the file name or the character '*', another optional literal string
7539 indicating the file name of the definition file to be used for preprocessing
7540 (@pxref{Form of Definitions File}). The definition files are found by the
7541 compiler in one of the source directories. In some cases, when compiling
7542 a source in a directory other than the current directory, if the definition
7543 file is in the current directory, it may be necessary to add the current
7544 directory as a source directory through switch -I., otherwise
7545 the compiler would not find the definition file.
7547 @noindent
7548 Then, optionally, switches similar to those of @code{gnatprep} may
7549 be found. Those switches are:
7551 @table @code
7553 @item -b
7554 Causes both preprocessor lines and the lines deleted by
7555 preprocessing to be replaced by blank lines, preserving the line number.
7556 This switch is always implied; however, if specified after @option{-c}
7557 it cancels the effect of @option{-c}.
7559 @item -c
7560 Causes both preprocessor lines and the lines deleted
7561 by preprocessing to be retained as comments marked
7562 with the special string ``@code{--! }''.
7564 @item -Dsymbol=value
7565 Define or redefine a symbol, associated with value. A symbol is an Ada
7566 identifier, or an Ada reserved word, with the exception of @code{if},
7567 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7568 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7569 word. A symbol declared with this switch replaces a symbol with the
7570 same name defined in a definition file.
7572 @item -s
7573 Causes a sorted list of symbol names and values to be
7574 listed on the standard output file.
7576 @item -u
7577 Causes undefined symbols to be treated as having the value @code{FALSE}
7578 in the context
7579 of a preprocessor test. In the absence of this option, an undefined symbol in
7580 a @code{#if} or @code{#elsif} test will be treated as an error.
7582 @end table
7584 @noindent
7585 Examples of valid lines in a preprocessor data file:
7587 @smallexample
7588   "toto.adb"  "prep.def" -u
7589   --  preprocess "toto.adb", using definition file "prep.def",
7590   --  undefined symbol are False.
7592   * -c -DVERSION=V101
7593   --  preprocess all other sources without a definition file;
7594   --  suppressed lined are commented; symbol VERSION has the value V101.
7596   "titi.adb" "prep2.def" -s
7597   --  preprocess "titi.adb", using definition file "prep2.def";
7598   --  list all symbols with their values.
7599 @end smallexample
7601 @item -gnateDsymbol@r{[}=value@r{]}
7602 @cindex @option{-gnateD} (@command{gcc})
7603 Define or redefine a preprocessing symbol, associated with value. If no value
7604 is given on the command line, then the value of the symbol is @code{True}.
7605 A symbol is an identifier, following normal Ada (case-insensitive)
7606 rules for its syntax, and value is either an arbitrary string between double
7607 quotes or any sequence (including an empty sequence) of characters from the
7608 set (letters, digits, period, underline).
7609 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7610 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7612 @noindent
7613 Examples:
7615 @smallexample
7616    -gnateDToto=Titi
7617    -gnateDFoo
7618    -gnateDFoo=\"Foo-Bar\"
7619 @end smallexample
7621 @noindent
7622 A symbol declared with this switch on the command line replaces a
7623 symbol with the same name either in a definition file or specified with a
7624 switch -D in the preprocessor data file.
7626 @noindent
7627 This switch is similar to switch @option{-D} of @code{gnatprep}.
7629 @item -gnateG
7630 When integrated preprocessing is performed and the preprocessor modifies
7631 the source text, write the result of this preprocessing into a file
7632 <source>.prep.
7634 @end table
7636 @node Code Generation Control
7637 @subsection Code Generation Control
7639 @noindent
7641 The GCC technology provides a wide range of target dependent
7642 @option{-m} switches for controlling
7643 details of code generation with respect to different versions of
7644 architectures. This includes variations in instruction sets (e.g.@:
7645 different members of the power pc family), and different requirements
7646 for optimal arrangement of instructions (e.g.@: different members of
7647 the x86 family). The list of available @option{-m} switches may be
7648 found in the GCC documentation.
7650 Use of these @option{-m} switches may in some cases result in improved
7651 code performance.
7653 The @value{EDITION} technology is tested and qualified without any
7654 @option{-m} switches,
7655 so generally the most reliable approach is to avoid the use of these
7656 switches. However, we generally expect most of these switches to work
7657 successfully with @value{EDITION}, and many customers have reported successful
7658 use of these options.
7660 Our general advice is to avoid the use of @option{-m} switches unless
7661 special needs lead to requirements in this area. In particular,
7662 there is no point in using @option{-m} switches to improve performance
7663 unless you actually see a performance improvement.
7666 @node Search Paths and the Run-Time Library (RTL)
7667 @section Search Paths and the Run-Time Library (RTL)
7669 @noindent
7670 With the GNAT source-based library system, the compiler must be able to
7671 find source files for units that are needed by the unit being compiled.
7672 Search paths are used to guide this process.
7674 The compiler compiles one source file whose name must be given
7675 explicitly on the command line. In other words, no searching is done
7676 for this file. To find all other source files that are needed (the most
7677 common being the specs of units), the compiler examines the following
7678 directories, in the following order:
7680 @enumerate
7681 @item
7682 The directory containing the source file of the main unit being compiled
7683 (the file name on the command line).
7685 @item
7686 Each directory named by an @option{-I} switch given on the
7687 @command{gcc} command line, in the order given.
7689 @item
7690 @findex ADA_PRJ_INCLUDE_FILE
7691 Each of the directories listed in the text file whose name is given
7692 by the @env{ADA_PRJ_INCLUDE_FILE} environment variable.
7694 @noindent
7695 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
7696 driver when project files are used. It should not normally be set
7697 by other means.
7699 @item
7700 @findex ADA_INCLUDE_PATH
7701 Each of the directories listed in the value of the
7702 @env{ADA_INCLUDE_PATH} environment variable.
7703 Construct this value
7704 exactly as the @env{PATH} environment variable: a list of directory
7705 names separated by colons (semicolons when working with the NT version).
7707 @item
7708 The content of the @file{ada_source_path} file which is part of the GNAT
7709 installation tree and is used to store standard libraries such as the
7710 GNAT Run Time Library (RTL) source files.
7711 @ref{Installing a library}
7712 @end enumerate
7714 @noindent
7715 Specifying the switch @option{-I-}
7716 inhibits the use of the directory
7717 containing the source file named in the command line. You can still
7718 have this directory on your search path, but in this case it must be
7719 explicitly requested with a @option{-I} switch.
7721 Specifying the switch @option{-nostdinc}
7722 inhibits the search of the default location for the GNAT Run Time
7723 Library (RTL) source files.
7725 The compiler outputs its object files and ALI files in the current
7726 working directory.
7727 Caution: The object file can be redirected with the @option{-o} switch;
7728 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7729 so the @file{ALI} file will not go to the right place. Therefore, you should
7730 avoid using the @option{-o} switch.
7732 @findex System.IO
7733 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7734 children make up the GNAT RTL, together with the simple @code{System.IO}
7735 package used in the @code{"Hello World"} example. The sources for these units
7736 are needed by the compiler and are kept together in one directory. Not
7737 all of the bodies are needed, but all of the sources are kept together
7738 anyway. In a normal installation, you need not specify these directory
7739 names when compiling or binding. Either the environment variables or
7740 the built-in defaults cause these files to be found.
7742 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7743 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7744 consisting of child units of @code{GNAT}. This is a collection of generally
7745 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7746 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7748 Besides simplifying access to the RTL, a major use of search paths is
7749 in compiling sources from multiple directories. This can make
7750 development environments much more flexible.
7752 @node Order of Compilation Issues
7753 @section Order of Compilation Issues
7755 @noindent
7756 If, in our earlier example, there was a spec for the @code{hello}
7757 procedure, it would be contained in the file @file{hello.ads}; yet this
7758 file would not have to be explicitly compiled. This is the result of the
7759 model we chose to implement library management. Some of the consequences
7760 of this model are as follows:
7762 @itemize @bullet
7763 @item
7764 There is no point in compiling specs (except for package
7765 specs with no bodies) because these are compiled as needed by clients. If
7766 you attempt a useless compilation, you will receive an error message.
7767 It is also useless to compile subunits because they are compiled as needed
7768 by the parent.
7770 @item
7771 There are no order of compilation requirements: performing a
7772 compilation never obsoletes anything. The only way you can obsolete
7773 something and require recompilations is to modify one of the
7774 source files on which it depends.
7776 @item
7777 There is no library as such, apart from the ALI files
7778 (@pxref{The Ada Library Information Files}, for information on the format
7779 of these files). For now we find it convenient to create separate ALI files,
7780 but eventually the information therein may be incorporated into the object
7781 file directly.
7783 @item
7784 When you compile a unit, the source files for the specs of all units
7785 that it @code{with}'s, all its subunits, and the bodies of any generics it
7786 instantiates must be available (reachable by the search-paths mechanism
7787 described above), or you will receive a fatal error message.
7788 @end itemize
7790 @node Examples
7791 @section Examples
7793 @noindent
7794 The following are some typical Ada compilation command line examples:
7796 @table @code
7797 @item $ gcc -c xyz.adb
7798 Compile body in file @file{xyz.adb} with all default options.
7800 @item $ gcc -c -O2 -gnata xyz-def.adb
7802 Compile the child unit package in file @file{xyz-def.adb} with extensive
7803 optimizations, and pragma @code{Assert}/@code{Debug} statements
7804 enabled.
7806 @item $ gcc -c -gnatc abc-def.adb
7807 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7808 mode.
7809 @end table
7811 @node Binding with gnatbind
7812 @chapter Binding with @code{gnatbind}
7813 @findex gnatbind
7815 @menu
7816 * Running gnatbind::
7817 * Switches for gnatbind::
7818 * Command-Line Access::
7819 * Search Paths for gnatbind::
7820 * Examples of gnatbind Usage::
7821 @end menu
7823 @noindent
7824 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7825 to bind compiled GNAT objects.
7827 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7828 driver (see @ref{The GNAT Driver and Project Files}).
7830 The @code{gnatbind} program performs four separate functions:
7832 @enumerate
7833 @item
7834 Checks that a program is consistent, in accordance with the rules in
7835 Chapter 10 of the Ada Reference Manual. In particular, error
7836 messages are generated if a program uses inconsistent versions of a
7837 given unit.
7839 @item
7840 Checks that an acceptable order of elaboration exists for the program
7841 and issues an error message if it cannot find an order of elaboration
7842 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7844 @item
7845 Generates a main program incorporating the given elaboration order.
7846 This program is a small Ada package (body and spec) that
7847 must be subsequently compiled
7848 using the GNAT compiler. The necessary compilation step is usually
7849 performed automatically by @command{gnatlink}. The two most important
7850 functions of this program
7851 are to call the elaboration routines of units in an appropriate order
7852 and to call the main program.
7854 @item
7855 Determines the set of object files required by the given main program.
7856 This information is output in the forms of comments in the generated program,
7857 to be read by the @command{gnatlink} utility used to link the Ada application.
7858 @end enumerate
7860 @node Running gnatbind
7861 @section Running @code{gnatbind}
7863 @noindent
7864 The form of the @code{gnatbind} command is
7866 @smallexample
7867 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7868 @c Expanding @ovar macro inline (explanation in macro def comments)
7869 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7870 @end smallexample
7872 @noindent
7873 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7874 unit body. @code{gnatbind} constructs an Ada
7875 package in two files whose names are
7876 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7877 For example, if given the
7878 parameter @file{hello.ali}, for a main program contained in file
7879 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7880 and @file{b~hello.adb}.
7882 When doing consistency checking, the binder takes into consideration
7883 any source files it can locate. For example, if the binder determines
7884 that the given main program requires the package @code{Pack}, whose
7885 @file{.ALI}
7886 file is @file{pack.ali} and whose corresponding source spec file is
7887 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7888 (using the same search path conventions as previously described for the
7889 @command{gcc} command). If it can locate this source file, it checks that
7890 the time stamps
7891 or source checksums of the source and its references to in @file{ALI} files
7892 match. In other words, any @file{ALI} files that mentions this spec must have
7893 resulted from compiling this version of the source file (or in the case
7894 where the source checksums match, a version close enough that the
7895 difference does not matter).
7897 @cindex Source files, use by binder
7898 The effect of this consistency checking, which includes source files, is
7899 that the binder ensures that the program is consistent with the latest
7900 version of the source files that can be located at bind time. Editing a
7901 source file without compiling files that depend on the source file cause
7902 error messages to be generated by the binder.
7904 For example, suppose you have a main program @file{hello.adb} and a
7905 package @code{P}, from file @file{p.ads} and you perform the following
7906 steps:
7908 @enumerate
7909 @item
7910 Enter @code{gcc -c hello.adb} to compile the main program.
7912 @item
7913 Enter @code{gcc -c p.ads} to compile package @code{P}.
7915 @item
7916 Edit file @file{p.ads}.
7918 @item
7919 Enter @code{gnatbind hello}.
7920 @end enumerate
7922 @noindent
7923 At this point, the file @file{p.ali} contains an out-of-date time stamp
7924 because the file @file{p.ads} has been edited. The attempt at binding
7925 fails, and the binder generates the following error messages:
7927 @smallexample
7928 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7929 error: "p.ads" has been modified and must be recompiled
7930 @end smallexample
7932 @noindent
7933 Now both files must be recompiled as indicated, and then the bind can
7934 succeed, generating a main program. You need not normally be concerned
7935 with the contents of this file, but for reference purposes a sample
7936 binder output file is given in @ref{Example of Binder Output File}.
7938 In most normal usage, the default mode of @command{gnatbind} which is to
7939 generate the main package in Ada, as described in the previous section.
7940 In particular, this means that any Ada programmer can read and understand
7941 the generated main program. It can also be debugged just like any other
7942 Ada code provided the @option{-g} switch is used for
7943 @command{gnatbind} and @command{gnatlink}.
7945 @node Switches for gnatbind
7946 @section Switches for @command{gnatbind}
7948 @noindent
7949 The following switches are available with @code{gnatbind}; details will
7950 be presented in subsequent sections.
7952 @menu
7953 * Consistency-Checking Modes::
7954 * Binder Error Message Control::
7955 * Elaboration Control::
7956 * Output Control::
7957 * Dynamic Allocation Control::
7958 * Binding with Non-Ada Main Programs::
7959 * Binding Programs with No Main Subprogram::
7960 @end menu
7962 @table @option
7963 @c !sort!
7965 @item --version
7966 @cindex @option{--version} @command{gnatbind}
7967 Display Copyright and version, then exit disregarding all other options.
7969 @item --help
7970 @cindex @option{--help} @command{gnatbind}
7971 If @option{--version} was not used, display usage, then exit disregarding
7972 all other options.
7974 @item -a
7975 @cindex @option{-a} @command{gnatbind}
7976 Indicates that, if supported by the platform, the adainit procedure should
7977 be treated as an initialisation routine by the linker (a constructor). This
7978 is intended to be used by the Project Manager to automatically initialize
7979 shared Stand-Alone Libraries.
7981 @item -aO
7982 @cindex @option{-aO} (@command{gnatbind})
7983 Specify directory to be searched for ALI files.
7985 @item -aI
7986 @cindex @option{-aI} (@command{gnatbind})
7987 Specify directory to be searched for source file.
7989 @item -A@r{[=}@var{filename}@r{]}
7990 @cindex @option{-A} (@command{gnatbind})
7991 Output ALI list (to standard output or to the named file).
7993 @item -b
7994 @cindex @option{-b} (@command{gnatbind})
7995 Generate brief messages to @file{stderr} even if verbose mode set.
7997 @item -c
7998 @cindex @option{-c} (@command{gnatbind})
7999 Check only, no generation of binder output file.
8001 @item -d@var{nn}@r{[}k@r{|}m@r{]}
8002 @cindex @option{-d@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8003 This switch can be used to change the default task stack size value
8004 to a specified size @var{nn}, which is expressed in bytes by default, or
8005 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8006 with @var{m}.
8007 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8008 in effect, to completing all task specs with
8009 @smallexample @c ada
8010    @b{pragma} Storage_Size (nn);
8011 @end smallexample
8012 When they do not already have such a pragma.
8014 @item -D@var{nn}@r{[}k@r{|}m@r{]}
8015 @cindex @option{-D} (@command{gnatbind})
8016 This switch can be used to change the default secondary stack size value
8017 to a specified size @var{nn}, which is expressed in bytes by default, or
8018 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8019 with @var{m}.
8021 The secondary stack is used to deal with functions that return a variable
8022 sized result, for example a function returning an unconstrained
8023 String. There are two ways in which this secondary stack is allocated.
8025 For most targets, the secondary stack is growing on demand and is allocated
8026 as a chain of blocks in the heap. The -D option is not very
8027 relevant. It only give some control over the size of the allocated
8028 blocks (whose size is the minimum of the default secondary stack size value,
8029 and the actual size needed for the current allocation request).
8031 For certain targets, notably VxWorks 653,
8032 the secondary stack is allocated by carving off a fixed ratio chunk of the
8033 primary task stack. The -D option is used to define the
8034 size of the environment task's secondary stack.
8036 @item -e
8037 @cindex @option{-e} (@command{gnatbind})
8038 Output complete list of elaboration-order dependencies.
8040 @item -E
8041 @cindex @option{-E} (@command{gnatbind})
8042 Store tracebacks in exception occurrences when the target supports it.
8043 @ignore
8044 @c The following may get moved to an appendix
8045 This option is currently supported on the following targets:
8046 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8047 @end ignore
8048 See also the packages @code{GNAT.Traceback} and
8049 @code{GNAT.Traceback.Symbolic} for more information.
8050 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8051 @command{gcc} option.
8053 @item -F
8054 @cindex @option{-F} (@command{gnatbind})
8055 Force the checks of elaboration flags. @command{gnatbind} does not normally
8056 generate checks of elaboration flags for the main executable, except when
8057 a Stand-Alone Library is used. However, there are cases when this cannot be
8058 detected by gnatbind. An example is importing an interface of a Stand-Alone
8059 Library through a pragma Import and only specifying through a linker switch
8060 this Stand-Alone Library. This switch is used to guarantee that elaboration
8061 flag checks are generated.
8063 @item -h
8064 @cindex @option{-h} (@command{gnatbind})
8065 Output usage (help) information
8067 @item -H32
8068 @cindex @option{-H32} (@command{gnatbind})
8069 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8070 For further details see @ref{Dynamic Allocation Control}.
8072 @item -H64
8073 @cindex @option{-H64} (@command{gnatbind})
8074 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8075 @cindex @code{__gnat_malloc}
8076 For further details see @ref{Dynamic Allocation Control}.
8078 @item -I
8079 @cindex @option{-I} (@command{gnatbind})
8080 Specify directory to be searched for source and ALI files.
8082 @item -I-
8083 @cindex @option{-I-} (@command{gnatbind})
8084 Do not look for sources in the current directory where @code{gnatbind} was
8085 invoked, and do not look for ALI files in the directory containing the
8086 ALI file named in the @code{gnatbind} command line.
8088 @item -l
8089 @cindex @option{-l} (@command{gnatbind})
8090 Output chosen elaboration order.
8092 @item -L@var{xxx}
8093 @cindex @option{-L} (@command{gnatbind})
8094 Bind the units for library building. In this case the adainit and
8095 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8096 are renamed to @var{xxx}init and
8097 @var{xxx}final.
8098 Implies -n.
8099 (@xref{GNAT and Libraries}, for more details.)
8101 @item -Mxyz
8102 @cindex @option{-M} (@command{gnatbind})
8103 Rename generated main program from main to xyz. This option is
8104 supported on cross environments only.
8106 @item -m@var{n}
8107 @cindex @option{-m} (@command{gnatbind})
8108 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8109 in the range 1..999999. The default value if no switch is
8110 given is 9999. If the number of warnings reaches this limit, then a
8111 message is output and further warnings are suppressed, the bind
8112 continues in this case. If the number of errors reaches this
8113 limit, then a message is output and the bind is abandoned.
8114 A value of zero means that no limit is enforced. The equal
8115 sign is optional.
8117 @item -n
8118 @cindex @option{-n} (@command{gnatbind})
8119 No main program.
8121 @item -nostdinc
8122 @cindex @option{-nostdinc} (@command{gnatbind})
8123 Do not look for sources in the system default directory.
8125 @item -nostdlib
8126 @cindex @option{-nostdlib} (@command{gnatbind})
8127 Do not look for library files in the system default directory.
8129 @item --RTS=@var{rts-path}
8130 @cindex @option{--RTS} (@code{gnatbind})
8131 Specifies the default location of the runtime library. Same meaning as the
8132 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8134 @item -o @var{file}
8135 @cindex @option{-o } (@command{gnatbind})
8136 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8137 Note that if this option is used, then linking must be done manually,
8138 gnatlink cannot be used.
8140 @item -O@r{[=}@var{filename}@r{]}
8141 @cindex @option{-O} (@command{gnatbind})
8142 Output object list (to standard output or to the named file).
8144 @item -p
8145 @cindex @option{-p} (@command{gnatbind})
8146 Pessimistic (worst-case) elaboration order
8148 @item -P
8149 @cindex @option{-P} (@command{gnatbind})
8150 Generate binder file suitable for CodePeer.
8152 @item -R
8153 @cindex @option{-R} (@command{gnatbind})
8154 Output closure source list, which includes all non-run-time units that are
8155 included in the bind.
8157 @item -Ra
8158 @cindex @option{-Ra} (@command{gnatbind})
8159 Like @option{-R} but the list includes run-time units.
8161 @item -s
8162 @cindex @option{-s} (@command{gnatbind})
8163 Require all source files to be present.
8165 @item -S@var{xxx}
8166 @cindex @option{-S} (@command{gnatbind})
8167 Specifies the value to be used when detecting uninitialized scalar
8168 objects with pragma Initialize_Scalars.
8169 The @var{xxx} string specified with the switch is one of:
8170 @itemize @bullet
8172 @item ``@option{in}'' for an invalid value
8173 If zero is invalid for the discrete type in question,
8174 then the scalar value is set to all zero bits.
8175 For signed discrete types, the largest possible negative value of
8176 the underlying scalar is set (i.e. a one bit followed by all zero bits).
8177 For unsigned discrete types, the underlying scalar value is set to all
8178 one bits. For floating-point types, a NaN value is set
8179 (see body of package System.Scalar_Values for exact values).
8181 @item ``@option{lo}'' for low value
8182 If zero is invalid for the discrete type in question,
8183 then the scalar value is set to all zero bits.
8184 For signed discrete types, the largest possible negative value of
8185 the underlying scalar is set (i.e. a one bit followed by all zero bits).
8186 For unsigned discrete types, the underlying scalar value is set to all
8187 zero bits. For floating-point, a small value is set
8188 (see body of package System.Scalar_Values for exact values).
8190 @item ``@option{hi}'' for high value
8191 If zero is invalid for the discrete type in question,
8192 then the scalar value is set to all one bits.
8193 For signed discrete types, the largest possible positive value of
8194 the underlying scalar is set (i.e. a zero bit followed by all one bits).
8195 For unsigned discrete types, the underlying scalar value is set to all
8196 one bits. For floating-point, a large value is set
8197 (see body of package System.Scalar_Values for exact values).
8199 @item ``@option{@var{xx}}'' for hex value (two hex digits)
8200 The underlying scalar is set to a value consisting of repeated bytes, whose
8201 value corresponds to the given value. For example if @option{BF} is given,
8202 then a 32-bit scalar value will be set to the bit patterm 16#BFBFBFBF#.
8203 @end itemize
8205 In addition, you can specify @option{-Sev} to indicate that the value is
8206 to be set at run time. In this case, the program will look for an environment
8207 @cindex GNAT_INIT_SCALARS
8208 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8209 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8210 If no environment variable is found, or if it does not have a valid value,
8211 then the default is @option{in} (invalid values).
8213 @item -static
8214 @cindex @option{-static} (@code{gnatbind})
8215 Link against a static GNAT run time.
8217 @item -shared
8218 @cindex @option{-shared} (@code{gnatbind})
8219 Link against a shared GNAT run time when available.
8221 @item -t
8222 @cindex @option{-t} (@code{gnatbind})
8223 Tolerate time stamp and other consistency errors
8225 @item -T@var{n}
8226 @cindex @option{-T} (@code{gnatbind})
8227 Set the time slice value to @var{n} milliseconds. If the system supports
8228 the specification of a specific time slice value, then the indicated value
8229 is used. If the system does not support specific time slice values, but
8230 does support some general notion of round-robin scheduling, then any
8231 nonzero value will activate round-robin scheduling.
8233 A value of zero is treated specially. It turns off time
8234 slicing, and in addition, indicates to the tasking run time that the
8235 semantics should match as closely as possible the Annex D
8236 requirements of the Ada RM, and in particular sets the default
8237 scheduling policy to @code{FIFO_Within_Priorities}.
8239 @item -u@var{n}
8240 @cindex @option{-u} (@code{gnatbind})
8241 Enable dynamic stack usage, with @var{n} results stored and displayed
8242 at program termination. A result is generated when a task
8243 terminates. Results that can't be stored are displayed on the fly, at
8244 task termination. This option is currently not supported on Itanium
8245 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8247 @item -v
8248 @cindex @option{-v} (@code{gnatbind})
8249 Verbose mode. Write error messages, header, summary output to
8250 @file{stdout}.
8252 @item -w@var{x}
8253 @cindex @option{-w} (@code{gnatbind})
8254 Warning mode (@var{x}=s/e for suppress/treat as error)
8257 @item -Wx@var{e}
8258 @cindex @option{-Wx} (@code{gnatbind})
8259 Override default wide character encoding for standard Text_IO files.
8261 @item -x
8262 @cindex @option{-x} (@code{gnatbind})
8263 Exclude source files (check object consistency only).
8266 @item -X@var{nnn}
8267 @cindex @option{-X@var{nnn}} (@code{gnatbind})
8268 Set default exit status value, normally 0 for POSIX compliance.
8271 @item -y
8272 @cindex @option{-y} (@code{gnatbind})
8273 Enable leap seconds support in @code{Ada.Calendar} and its children.
8275 @item -z
8276 @cindex @option{-z} (@code{gnatbind})
8277 No main subprogram.
8278 @end table
8280 @noindent
8281 You may obtain this listing of switches by running @code{gnatbind} with
8282 no arguments.
8284 @node Consistency-Checking Modes
8285 @subsection Consistency-Checking Modes
8287 @noindent
8288 As described earlier, by default @code{gnatbind} checks
8289 that object files are consistent with one another and are consistent
8290 with any source files it can locate. The following switches control binder
8291 access to sources.
8293 @table @option
8294 @c !sort!
8295 @item -s
8296 @cindex @option{-s} (@code{gnatbind})
8297 Require source files to be present. In this mode, the binder must be
8298 able to locate all source files that are referenced, in order to check
8299 their consistency. In normal mode, if a source file cannot be located it
8300 is simply ignored. If you specify this switch, a missing source
8301 file is an error.
8303 @item -Wx@var{e}
8304 @cindex @option{-Wx} (@code{gnatbind})
8305 Override default wide character encoding for standard Text_IO files.
8306 Normally the default wide character encoding method used for standard
8307 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8308 the main source input (see description of switch
8309 @option{-gnatWx} for the compiler). The
8310 use of this switch for the binder (which has the same set of
8311 possible arguments) overrides this default as specified.
8313 @item -x
8314 @cindex @option{-x} (@code{gnatbind})
8315 Exclude source files. In this mode, the binder only checks that ALI
8316 files are consistent with one another. Source files are not accessed.
8317 The binder runs faster in this mode, and there is still a guarantee that
8318 the resulting program is self-consistent.
8319 If a source file has been edited since it was last compiled, and you
8320 specify this switch, the binder will not detect that the object
8321 file is out of date with respect to the source file. Note that this is the
8322 mode that is automatically used by @command{gnatmake} because in this
8323 case the checking against sources has already been performed by
8324 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8326 @end table
8328 @node Binder Error Message Control
8329 @subsection Binder Error Message Control
8331 @noindent
8332 The following switches provide control over the generation of error
8333 messages from the binder:
8335 @table @option
8336 @c !sort!
8337 @item -v
8338 @cindex @option{-v} (@code{gnatbind})
8339 Verbose mode. In the normal mode, brief error messages are generated to
8340 @file{stderr}. If this switch is present, a header is written
8341 to @file{stdout} and any error messages are directed to @file{stdout}.
8342 All that is written to @file{stderr} is a brief summary message.
8344 @item -b
8345 @cindex @option{-b} (@code{gnatbind})
8346 Generate brief error messages to @file{stderr} even if verbose mode is
8347 specified. This is relevant only when used with the
8348 @option{-v} switch.
8350 @item -m@var{n}
8351 @cindex @option{-m} (@code{gnatbind})
8352 Limits the number of error messages to @var{n}, a decimal integer in the
8353 range 1-999. The binder terminates immediately if this limit is reached.
8355 @item -M@var{xxx}
8356 @cindex @option{-M} (@code{gnatbind})
8357 Renames the generated main program from @code{main} to @code{xxx}.
8358 This is useful in the case of some cross-building environments, where
8359 the actual main program is separate from the one generated
8360 by @code{gnatbind}.
8362 @item -ws
8363 @cindex @option{-ws} (@code{gnatbind})
8364 @cindex Warnings
8365 Suppress all warning messages.
8367 @item -we
8368 @cindex @option{-we} (@code{gnatbind})
8369 Treat any warning messages as fatal errors.
8372 @item -t
8373 @cindex @option{-t} (@code{gnatbind})
8374 @cindex Time stamp checks, in binder
8375 @cindex Binder consistency checks
8376 @cindex Consistency checks, in binder
8377 The binder performs a number of consistency checks including:
8379 @itemize @bullet
8380 @item
8381 Check that time stamps of a given source unit are consistent
8382 @item
8383 Check that checksums of a given source unit are consistent
8384 @item
8385 Check that consistent versions of @code{GNAT} were used for compilation
8386 @item
8387 Check consistency of configuration pragmas as required
8388 @end itemize
8390 @noindent
8391 Normally failure of such checks, in accordance with the consistency
8392 requirements of the Ada Reference Manual, causes error messages to be
8393 generated which abort the binder and prevent the output of a binder
8394 file and subsequent link to obtain an executable.
8396 The @option{-t} switch converts these error messages
8397 into warnings, so that
8398 binding and linking can continue to completion even in the presence of such
8399 errors. The result may be a failed link (due to missing symbols), or a
8400 non-functional executable which has undefined semantics.
8401 @emph{This means that
8402 @option{-t} should be used only in unusual situations,
8403 with extreme care.}
8404 @end table
8406 @node Elaboration Control
8407 @subsection Elaboration Control
8409 @noindent
8410 The following switches provide additional control over the elaboration
8411 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8413 @table @option
8414 @item -p
8415 @cindex @option{-p} (@code{gnatbind})
8416 Normally the binder attempts to choose an elaboration order that is
8417 likely to minimize the likelihood of an elaboration order error resulting
8418 in raising a @code{Program_Error} exception. This switch reverses the
8419 action of the binder, and requests that it deliberately choose an order
8420 that is likely to maximize the likelihood of an elaboration error.
8421 This is useful in ensuring portability and avoiding dependence on
8422 accidental fortuitous elaboration ordering.
8424 Normally it only makes sense to use the @option{-p}
8425 switch if dynamic
8426 elaboration checking is used (@option{-gnatE} switch used for compilation).
8427 This is because in the default static elaboration mode, all necessary
8428 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8429 These implicit pragmas are still respected by the binder in
8430 @option{-p} mode, so a
8431 safe elaboration order is assured.
8433 Note that @option{-p} is not intended for
8434 production use; it is more for debugging/experimental use.
8435 @end table
8437 @node Output Control
8438 @subsection Output Control
8440 @noindent
8441 The following switches allow additional control over the output
8442 generated by the binder.
8444 @table @option
8445 @c !sort!
8447 @item -c
8448 @cindex @option{-c} (@code{gnatbind})
8449 Check only. Do not generate the binder output file. In this mode the
8450 binder performs all error checks but does not generate an output file.
8452 @item -e
8453 @cindex @option{-e} (@code{gnatbind})
8454 Output complete list of elaboration-order dependencies, showing the
8455 reason for each dependency. This output can be rather extensive but may
8456 be useful in diagnosing problems with elaboration order. The output is
8457 written to @file{stdout}.
8459 @item -h
8460 @cindex @option{-h} (@code{gnatbind})
8461 Output usage information. The output is written to @file{stdout}.
8463 @item -K
8464 @cindex @option{-K} (@code{gnatbind})
8465 Output linker options to @file{stdout}. Includes library search paths,
8466 contents of pragmas Ident and Linker_Options, and libraries added
8467 by @code{gnatbind}.
8469 @item -l
8470 @cindex @option{-l} (@code{gnatbind})
8471 Output chosen elaboration order. The output is written to @file{stdout}.
8473 @item -O
8474 @cindex @option{-O} (@code{gnatbind})
8475 Output full names of all the object files that must be linked to provide
8476 the Ada component of the program. The output is written to @file{stdout}.
8477 This list includes the files explicitly supplied and referenced by the user
8478 as well as implicitly referenced run-time unit files. The latter are
8479 omitted if the corresponding units reside in shared libraries. The
8480 directory names for the run-time units depend on the system configuration.
8482 @item -o @var{file}
8483 @cindex @option{-o} (@code{gnatbind})
8484 Set name of output file to @var{file} instead of the normal
8485 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8486 binder generated body filename.
8487 Note that if this option is used, then linking must be done manually.
8488 It is not possible to use gnatlink in this case, since it cannot locate
8489 the binder file.
8491 @item -r
8492 @cindex @option{-r} (@code{gnatbind})
8493 Generate list of @code{pragma Restrictions} that could be applied to
8494 the current unit. This is useful for code audit purposes, and also may
8495 be used to improve code generation in some cases.
8497 @end table
8499 @node Dynamic Allocation Control
8500 @subsection Dynamic Allocation Control
8502 @noindent
8503 The heap control switches -- @option{-H32} and @option{-H64} --
8504 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8505 They only affect compiler-generated allocations via @code{__gnat_malloc};
8506 explicit calls to @code{malloc} and related functions from the C
8507 run-time library are unaffected.
8509 @table @option
8510 @item -H32
8511 Allocate memory on 32-bit heap
8513 @item -H64
8514 Allocate memory on 64-bit heap.  This is the default
8515 unless explicitly overridden by a @code{'Size} clause on the access type.
8516 @end table
8518 @noindent
8519 These switches are only effective on VMS platforms.
8522 @node Binding with Non-Ada Main Programs
8523 @subsection Binding with Non-Ada Main Programs
8525 @noindent
8526 In our description so far we have assumed that the main
8527 program is in Ada, and that the task of the binder is to generate a
8528 corresponding function @code{main} that invokes this Ada main
8529 program. GNAT also supports the building of executable programs where
8530 the main program is not in Ada, but some of the called routines are
8531 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8532 The following switch is used in this situation:
8534 @table @option
8535 @item -n
8536 @cindex @option{-n} (@code{gnatbind})
8537 No main program. The main program is not in Ada.
8538 @end table
8540 @noindent
8541 In this case, most of the functions of the binder are still required,
8542 but instead of generating a main program, the binder generates a file
8543 containing the following callable routines:
8545 @table @code
8546 @item adainit
8547 @findex adainit
8548 You must call this routine to initialize the Ada part of the program by
8549 calling the necessary elaboration routines. A call to @code{adainit} is
8550 required before the first call to an Ada subprogram.
8552 Note that it is assumed that the basic execution environment must be setup
8553 to be appropriate for Ada execution at the point where the first Ada
8554 subprogram is called. In particular, if the Ada code will do any
8555 floating-point operations, then the FPU must be setup in an appropriate
8556 manner. For the case of the x86, for example, full precision mode is
8557 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8558 that the FPU is in the right state.
8560 @item adafinal
8561 @findex adafinal
8562 You must call this routine to perform any library-level finalization
8563 required by the Ada subprograms. A call to @code{adafinal} is required
8564 after the last call to an Ada subprogram, and before the program
8565 terminates.
8566 @end table
8568 @noindent
8569 If the @option{-n} switch
8570 @cindex @option{-n} (@command{gnatbind})
8571 @cindex Binder, multiple input files
8572 is given, more than one ALI file may appear on
8573 the command line for @code{gnatbind}. The normal @dfn{closure}
8574 calculation is performed for each of the specified units. Calculating
8575 the closure means finding out the set of units involved by tracing
8576 @code{with} references. The reason it is necessary to be able to
8577 specify more than one ALI file is that a given program may invoke two or
8578 more quite separate groups of Ada units.
8580 The binder takes the name of its output file from the last specified ALI
8581 file, unless overridden by the use of the @option{-o file}.
8582 @cindex @option{-o} (@command{gnatbind})
8583 The output is an Ada unit in source form that can be compiled with GNAT.
8584 This compilation occurs automatically as part of the @command{gnatlink}
8585 processing.
8587 Currently the GNAT run time requires a FPU using 80 bits mode
8588 precision. Under targets where this is not the default it is required to
8589 call GNAT.Float_Control.Reset before using floating point numbers (this
8590 include float computation, float input and output) in the Ada code. A
8591 side effect is that this could be the wrong mode for the foreign code
8592 where floating point computation could be broken after this call.
8594 @node Binding Programs with No Main Subprogram
8595 @subsection Binding Programs with No Main Subprogram
8597 @noindent
8598 It is possible to have an Ada program which does not have a main
8599 subprogram. This program will call the elaboration routines of all the
8600 packages, then the finalization routines.
8602 The following switch is used to bind programs organized in this manner:
8604 @table @option
8605 @item -z
8606 @cindex @option{-z} (@code{gnatbind})
8607 Normally the binder checks that the unit name given on the command line
8608 corresponds to a suitable main subprogram. When this switch is used,
8609 a list of ALI files can be given, and the execution of the program
8610 consists of elaboration of these units in an appropriate order. Note
8611 that the default wide character encoding method for standard Text_IO
8612 files is always set to Brackets if this switch is set (you can use
8613 the binder switch
8614 @option{-Wx} to override this default).
8615 @end table
8617 @node Command-Line Access
8618 @section Command-Line Access
8620 @noindent
8621 The package @code{Ada.Command_Line} provides access to the command-line
8622 arguments and program name. In order for this interface to operate
8623 correctly, the two variables
8625 @smallexample
8626 @group
8627 int gnat_argc;
8628 char **gnat_argv;
8629 @end group
8630 @end smallexample
8632 @noindent
8633 @findex gnat_argv
8634 @findex gnat_argc
8635 are declared in one of the GNAT library routines. These variables must
8636 be set from the actual @code{argc} and @code{argv} values passed to the
8637 main program. With no @option{n} present, @code{gnatbind}
8638 generates the C main program to automatically set these variables.
8639 If the @option{n} switch is used, there is no automatic way to
8640 set these variables. If they are not set, the procedures in
8641 @code{Ada.Command_Line} will not be available, and any attempt to use
8642 them will raise @code{Constraint_Error}. If command line access is
8643 required, your main program must set @code{gnat_argc} and
8644 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8647 @node Search Paths for gnatbind
8648 @section Search Paths for @code{gnatbind}
8650 @noindent
8651 The binder takes the name of an ALI file as its argument and needs to
8652 locate source files as well as other ALI files to verify object consistency.
8654 For source files, it follows exactly the same search rules as @command{gcc}
8655 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8656 directories searched are:
8658 @enumerate
8659 @item
8660 The directory containing the ALI file named in the command line, unless
8661 the switch @option{-I-} is specified.
8663 @item
8664 All directories specified by @option{-I}
8665 switches on the @code{gnatbind}
8666 command line, in the order given.
8668 @item
8669 @findex ADA_PRJ_OBJECTS_FILE
8670 Each of the directories listed in the text file whose name is given
8671 by the @env{ADA_PRJ_OBJECTS_FILE} environment variable.
8673 @noindent
8674 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
8675 driver when project files are used. It should not normally be set
8676 by other means.
8678 @item
8679 @findex ADA_OBJECTS_PATH
8680 Each of the directories listed in the value of the
8681 @env{ADA_OBJECTS_PATH} environment variable.
8682 Construct this value
8683 exactly as the @env{PATH} environment variable: a list of directory
8684 names separated by colons (semicolons when working with the NT version
8685 of GNAT).
8687 @item
8688 The content of the @file{ada_object_path} file which is part of the GNAT
8689 installation tree and is used to store standard libraries such as the
8690 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8691 specified.
8692 @ref{Installing a library}
8693 @end enumerate
8695 @noindent
8696 In the binder the switch @option{-I}
8697 @cindex @option{-I} (@command{gnatbind})
8698 is used to specify both source and
8699 library file paths. Use @option{-aI}
8700 @cindex @option{-aI} (@command{gnatbind})
8701 instead if you want to specify
8702 source paths only, and @option{-aO}
8703 @cindex @option{-aO} (@command{gnatbind})
8704 if you want to specify library paths
8705 only. This means that for the binder
8706 @option{-I}@var{dir} is equivalent to
8707 @option{-aI}@var{dir}
8708 @option{-aO}@var{dir}.
8709 The binder generates the bind file (a C language source file) in the
8710 current working directory.
8712 @findex Ada
8713 @findex System
8714 @findex Interfaces
8715 @findex GNAT
8716 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8717 children make up the GNAT Run-Time Library, together with the package
8718 GNAT and its children, which contain a set of useful additional
8719 library functions provided by GNAT. The sources for these units are
8720 needed by the compiler and are kept together in one directory. The ALI
8721 files and object files generated by compiling the RTL are needed by the
8722 binder and the linker and are kept together in one directory, typically
8723 different from the directory containing the sources. In a normal
8724 installation, you need not specify these directory names when compiling
8725 or binding. Either the environment variables or the built-in defaults
8726 cause these files to be found.
8728 Besides simplifying access to the RTL, a major use of search paths is
8729 in compiling sources from multiple directories. This can make
8730 development environments much more flexible.
8732 @node Examples of gnatbind Usage
8733 @section Examples of @code{gnatbind} Usage
8735 @noindent
8736 This section contains a number of examples of using the GNAT binding
8737 utility @code{gnatbind}.
8739 @table @code
8740 @item gnatbind hello
8741 The main program @code{Hello} (source program in @file{hello.adb}) is
8742 bound using the standard switch settings. The generated main program is
8743 @file{b~hello.adb}. This is the normal, default use of the binder.
8745 @item gnatbind hello -o mainprog.adb
8746 The main program @code{Hello} (source program in @file{hello.adb}) is
8747 bound using the standard switch settings. The generated main program is
8748 @file{mainprog.adb} with the associated spec in
8749 @file{mainprog.ads}. Note that you must specify the body here not the
8750 spec. Note that if this option is used, then linking must be done manually,
8751 since gnatlink will not be able to find the generated file.
8752 @end table
8754 @c ------------------------------------
8755 @node Linking with gnatlink
8756 @chapter Linking with @command{gnatlink}
8757 @c ------------------------------------
8758 @findex gnatlink
8760 @noindent
8761 This chapter discusses @command{gnatlink}, a tool that links
8762 an Ada program and builds an executable file. This utility
8763 invokes the system linker (via the @command{gcc} command)
8764 with a correct list of object files and library references.
8765 @command{gnatlink} automatically determines the list of files and
8766 references for the Ada part of a program. It uses the binder file
8767 generated by the @command{gnatbind} to determine this list.
8769 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8770 driver (see @ref{The GNAT Driver and Project Files}).
8772 @menu
8773 * Running gnatlink::
8774 * Switches for gnatlink::
8775 @end menu
8777 @node Running gnatlink
8778 @section Running @command{gnatlink}
8780 @noindent
8781 The form of the @command{gnatlink} command is
8783 @smallexample
8784 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8785 @c            @ovar{non-Ada objects} @ovar{linker options}
8786 @c Expanding @ovar macro inline (explanation in macro def comments)
8787 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8788            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8790 @end smallexample
8792 @noindent
8793 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8794 non-Ada objects
8795 or linker options) may be in any order, provided that no non-Ada object may
8796 be mistaken for a main @file{ALI} file.
8797 Any file name @file{F} without the @file{.ali}
8798 extension will be taken as the main @file{ALI} file if a file exists
8799 whose name is the concatenation of @file{F} and @file{.ali}.
8801 @noindent
8802 @file{@var{mainprog}.ali} references the ALI file of the main program.
8803 The @file{.ali} extension of this file can be omitted. From this
8804 reference, @command{gnatlink} locates the corresponding binder file
8805 @file{b~@var{mainprog}.adb} and, using the information in this file along
8806 with the list of non-Ada objects and linker options, constructs a
8807 linker command file to create the executable.
8809 The arguments other than the @command{gnatlink} switches and the main
8810 @file{ALI} file are passed to the linker uninterpreted.
8811 They typically include the names of
8812 object files for units written in other languages than Ada and any library
8813 references required to resolve references in any of these foreign language
8814 units, or in @code{Import} pragmas in any Ada units.
8816 @var{linker options} is an optional list of linker specific
8817 switches.
8818 The default linker called by gnatlink is @command{gcc} which in
8819 turn calls the appropriate system linker.
8821 One useful option for the linker is @option{-s}: it reduces the size of the
8822 executable by removing all symbol table and relocation information from the
8823 executable.
8825 Standard options for the linker such as @option{-lmy_lib} or
8826 @option{-Ldir} can be added as is.
8827 For options that are not recognized by
8828 @command{gcc} as linker options, use the @command{gcc} switches
8829 @option{-Xlinker} or @option{-Wl,}.
8831 Refer to the GCC documentation for
8832 details.
8834 Here is an example showing how to generate a linker map:
8836 @smallexample
8837 $ gnatlink my_prog -Wl,-Map,MAPFILE
8838 @end smallexample
8840 Using @var{linker options} it is possible to set the program stack and
8841 heap size.
8842 See @ref{Setting Stack Size from gnatlink} and
8843 @ref{Setting Heap Size from gnatlink}.
8845 @command{gnatlink} determines the list of objects required by the Ada
8846 program and prepends them to the list of objects passed to the linker.
8847 @command{gnatlink} also gathers any arguments set by the use of
8848 @code{pragma Linker_Options} and adds them to the list of arguments
8849 presented to the linker.
8852 @node Switches for gnatlink
8853 @section Switches for @command{gnatlink}
8855 @noindent
8856 The following switches are available with the @command{gnatlink} utility:
8858 @table @option
8859 @c !sort!
8861 @item --version
8862 @cindex @option{--version} @command{gnatlink}
8863 Display Copyright and version, then exit disregarding all other options.
8865 @item --help
8866 @cindex @option{--help} @command{gnatlink}
8867 If @option{--version} was not used, display usage, then exit disregarding
8868 all other options.
8870 @item -f
8871 @cindex Command line length
8872 @cindex @option{-f} (@command{gnatlink})
8873 On some targets, the command line length is limited, and @command{gnatlink}
8874 will generate a separate file for the linker if the list of object files
8875 is too long.
8876 The @option{-f} switch forces this file
8877 to be generated even if
8878 the limit is not exceeded. This is useful in some cases to deal with
8879 special situations where the command line length is exceeded.
8881 @item -g
8882 @cindex Debugging information, including
8883 @cindex @option{-g} (@command{gnatlink})
8884 The option to include debugging information causes the Ada bind file (in
8885 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8886 @option{-g}.
8887 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8888 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8889 Without @option{-g}, the binder removes these files by
8890 default. The same procedure apply if a C bind file was generated using
8891 @option{-C} @code{gnatbind} option, in this case the filenames
8892 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8894 @item -n
8895 @cindex @option{-n} (@command{gnatlink})
8896 Do not compile the file generated by the binder. This may be used when
8897 a link is rerun with different options, but there is no need to recompile
8898 the binder file.
8900 @item -v
8901 @cindex @option{-v} (@command{gnatlink})
8902 Causes additional information to be output, including a full list of the
8903 included object files. This switch option is most useful when you want
8904 to see what set of object files are being used in the link step.
8906 @item -v -v
8907 @cindex @option{-v -v} (@command{gnatlink})
8908 Very verbose mode. Requests that the compiler operate in verbose mode when
8909 it compiles the binder file, and that the system linker run in verbose mode.
8911 @item -o @var{exec-name}
8912 @cindex @option{-o} (@command{gnatlink})
8913 @var{exec-name} specifies an alternate name for the generated
8914 executable program. If this switch is omitted, the executable has the same
8915 name as the main unit. For example, @code{gnatlink try.ali} creates
8916 an executable called @file{try}.
8918 @item -b @var{target}
8919 @cindex @option{-b} (@command{gnatlink})
8920 Compile your program to run on @var{target}, which is the name of a
8921 system configuration. You must have a GNAT cross-compiler built if
8922 @var{target} is not the same as your host system.
8924 @item -B@var{dir}
8925 @cindex @option{-B} (@command{gnatlink})
8926 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8927 from @var{dir} instead of the default location. Only use this switch
8928 when multiple versions of the GNAT compiler are available.
8929 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8930 for further details. You would normally use the @option{-b} or
8931 @option{-V} switch instead.
8933 @item -M
8934 When linking an executable, create a map file. The name of the map file
8935 has the same name as the executable with extension ".map".
8937 @item -M=mapfile
8938 When linking an executable, create a map file. The name of the map file is
8939 "mapfile".
8941 @item --GCC=@var{compiler_name}
8942 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8943 Program used for compiling the binder file. The default is
8944 @command{gcc}. You need to use quotes around @var{compiler_name} if
8945 @code{compiler_name} contains spaces or other separator characters.
8946 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8947 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8948 inserted after your command name. Thus in the above example the compiler
8949 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8950 A limitation of this syntax is that the name and path name of the executable
8951 itself must not include any embedded spaces. If the compiler executable is
8952 different from the default one (gcc or <prefix>-gcc), then the back-end
8953 switches in the ALI file are not used to compile the binder generated source.
8954 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8955 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8956 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8957 is taken into account. However, all the additional switches are also taken
8958 into account. Thus,
8959 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8960 @option{--GCC="bar -x -y -z -t"}.
8962 @item --LINK=@var{name}
8963 @cindex @option{--LINK=} (@command{gnatlink})
8964 @var{name} is the name of the linker to be invoked. This is especially
8965 useful in mixed language programs since languages such as C++ require
8966 their own linker to be used. When this switch is omitted, the default
8967 name for the linker is @command{gcc}. When this switch is used, the
8968 specified linker is called instead of @command{gcc} with exactly the same
8969 parameters that would have been passed to @command{gcc} so if the desired
8970 linker requires different parameters it is necessary to use a wrapper
8971 script that massages the parameters before invoking the real linker. It
8972 may be useful to control the exact invocation by using the verbose
8973 switch.
8977 @end table
8979 @node The GNAT Make Program gnatmake
8980 @chapter The GNAT Make Program @command{gnatmake}
8981 @findex gnatmake
8983 @menu
8984 * Running gnatmake::
8985 * Switches for gnatmake::
8986 * Mode Switches for gnatmake::
8987 * Notes on the Command Line::
8988 * How gnatmake Works::
8989 * Examples of gnatmake Usage::
8990 @end menu
8991 @noindent
8992 A typical development cycle when working on an Ada program consists of
8993 the following steps:
8995 @enumerate
8996 @item
8997 Edit some sources to fix bugs.
8999 @item
9000 Add enhancements.
9002 @item
9003 Compile all sources affected.
9005 @item
9006 Rebind and relink.
9008 @item
9009 Test.
9010 @end enumerate
9012 @noindent
9013 The third step can be tricky, because not only do the modified files
9014 @cindex Dependency rules
9015 have to be compiled, but any files depending on these files must also be
9016 recompiled. The dependency rules in Ada can be quite complex, especially
9017 in the presence of overloading, @code{use} clauses, generics and inlined
9018 subprograms.
9020 @command{gnatmake} automatically takes care of the third and fourth steps
9021 of this process. It determines which sources need to be compiled,
9022 compiles them, and binds and links the resulting object files.
9024 Unlike some other Ada make programs, the dependencies are always
9025 accurately recomputed from the new sources. The source based approach of
9026 the GNAT compilation model makes this possible. This means that if
9027 changes to the source program cause corresponding changes in
9028 dependencies, they will always be tracked exactly correctly by
9029 @command{gnatmake}.
9031 @node Running gnatmake
9032 @section Running @command{gnatmake}
9034 @noindent
9035 The usual form of the @command{gnatmake} command is
9037 @smallexample
9038 @c $ gnatmake @ovar{switches} @var{file_name}
9039 @c       @ovar{file_names} @ovar{mode_switches}
9040 @c Expanding @ovar macro inline (explanation in macro def comments)
9041 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9042       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9043 @end smallexample
9045 @noindent
9046 The only required argument is one @var{file_name}, which specifies
9047 a compilation unit that is a main program. Several @var{file_names} can be
9048 specified: this will result in several executables being built.
9049 If @code{switches} are present, they can be placed before the first
9050 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9051 If @var{mode_switches} are present, they must always be placed after
9052 the last @var{file_name} and all @code{switches}.
9054 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9055 extension may be omitted from the @var{file_name} arguments. However, if
9056 you are using non-standard extensions, then it is required that the
9057 extension be given. A relative or absolute directory path can be
9058 specified in a @var{file_name}, in which case, the input source file will
9059 be searched for in the specified directory only. Otherwise, the input
9060 source file will first be searched in the directory where
9061 @command{gnatmake} was invoked and if it is not found, it will be search on
9062 the source path of the compiler as described in
9063 @ref{Search Paths and the Run-Time Library (RTL)}.
9065 All @command{gnatmake} output (except when you specify
9066 @option{-M}) is to
9067 @file{stderr}. The output produced by the
9068 @option{-M} switch is send to
9069 @file{stdout}.
9071 @node Switches for gnatmake
9072 @section Switches for @command{gnatmake}
9074 @noindent
9075 You may specify any of the following switches to @command{gnatmake}:
9077 @table @option
9078 @c !sort!
9080 @item --version
9081 @cindex @option{--version} @command{gnatmake}
9082 Display Copyright and version, then exit disregarding all other options.
9084 @item --help
9085 @cindex @option{--help} @command{gnatmake}
9086 If @option{--version} was not used, display usage, then exit disregarding
9087 all other options.
9089 @item --GCC=@var{compiler_name}
9090 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9091 Program used for compiling. The default is `@command{gcc}'. You need to use
9092 quotes around @var{compiler_name} if @code{compiler_name} contains
9093 spaces or other separator characters. As an example @option{--GCC="foo -x
9094 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9095 compiler. A limitation of this syntax is that the name and path name of
9096 the executable itself must not include any embedded spaces. Note that
9097 switch @option{-c} is always inserted after your command name. Thus in the
9098 above example the compiler command that will be used by @command{gnatmake}
9099 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9100 used, only the last @var{compiler_name} is taken into account. However,
9101 all the additional switches are also taken into account. Thus,
9102 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9103 @option{--GCC="bar -x -y -z -t"}.
9105 @item --GNATBIND=@var{binder_name}
9106 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9107 Program used for binding. The default is `@code{gnatbind}'. You need to
9108 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9109 or other separator characters. As an example @option{--GNATBIND="bar -x
9110 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9111 binder. Binder switches that are normally appended by @command{gnatmake}
9112 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9113 A limitation of this syntax is that the name and path name of the executable
9114 itself must not include any embedded spaces.
9116 @item --GNATLINK=@var{linker_name}
9117 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9118 Program used for linking. The default is `@command{gnatlink}'. You need to
9119 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9120 or other separator characters. As an example @option{--GNATLINK="lan -x
9121 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9122 linker. Linker switches that are normally appended by @command{gnatmake} to
9123 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9124 A limitation of this syntax is that the name and path name of the executable
9125 itself must not include any embedded spaces.
9128 @item --subdirs=subdir
9129 Actual object directory of each project file is the subdirectory subdir of the
9130 object directory specified or defaulted in the project file.
9132 @item --single-compile-per-obj-dir
9133 Disallow simultaneous compilations in the same object directory when
9134 project files are used.
9136 @item --unchecked-shared-lib-imports
9137 By default, shared library projects are not allowed to import static library
9138 projects. When this switch is used on the command line, this restriction is
9139 relaxed.
9141 @item --source-info=<source info file>
9142 Specify a source info file. This switch is active only when project files
9143 are used. If the source info file is specified as a relative path, then it is
9144 relative to the object directory of the main project. If the source info file
9145 does not exist, then after the Project Manager has successfully parsed and
9146 processed the project files and found the sources, it creates the source info
9147 file. If the source info file already exists and can be read successfully,
9148 then the Project Manager will get all the needed information about the sources
9149 from the source info file and will not look for them. This reduces the time
9150 to process the project files, especially when looking for sources that take a
9151 long time. If the source info file exists but cannot be parsed successfully,
9152 the Project Manager will attempt to recreate it. If the Project Manager fails
9153 to create the source info file, a message is issued, but gnatmake does not
9154 fail. @command{gnatmake} "trusts" the source info file. This means that
9155 if the source files have changed (addition, deletion, moving to a different
9156 source directory), then the source info file need to be deleted and recreated.
9158 @item --create-map-file
9159 When linking an executable, create a map file. The name of the map file
9160 has the same name as the executable with extension ".map".
9162 @item --create-map-file=mapfile
9163 When linking an executable, create a map file. The name of the map file is
9164 "mapfile".
9167 @item -a
9168 @cindex @option{-a} (@command{gnatmake})
9169 Consider all files in the make process, even the GNAT internal system
9170 files (for example, the predefined Ada library files), as well as any
9171 locked files. Locked files are files whose ALI file is write-protected.
9172 By default,
9173 @command{gnatmake} does not check these files,
9174 because the assumption is that the GNAT internal files are properly up
9175 to date, and also that any write protected ALI files have been properly
9176 installed. Note that if there is an installation problem, such that one
9177 of these files is not up to date, it will be properly caught by the
9178 binder.
9179 You may have to specify this switch if you are working on GNAT
9180 itself. The switch @option{-a} is also useful
9181 in conjunction with @option{-f}
9182 if you need to recompile an entire application,
9183 including run-time files, using special configuration pragmas,
9184 such as a @code{Normalize_Scalars} pragma.
9186 By default
9187 @code{gnatmake -a} compiles all GNAT
9188 internal files with
9189 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9191 @item -b
9192 @cindex @option{-b} (@command{gnatmake})
9193 Bind only. Can be combined with @option{-c} to do
9194 compilation and binding, but no link.
9195 Can be combined with @option{-l}
9196 to do binding and linking. When not combined with
9197 @option{-c}
9198 all the units in the closure of the main program must have been previously
9199 compiled and must be up to date. The root unit specified by @var{file_name}
9200 may be given without extension, with the source extension or, if no GNAT
9201 Project File is specified, with the ALI file extension.
9203 @item -c
9204 @cindex @option{-c} (@command{gnatmake})
9205 Compile only. Do not perform binding, except when @option{-b}
9206 is also specified. Do not perform linking, except if both
9207 @option{-b} and
9208 @option{-l} are also specified.
9209 If the root unit specified by @var{file_name} is not a main unit, this is the
9210 default. Otherwise @command{gnatmake} will attempt binding and linking
9211 unless all objects are up to date and the executable is more recent than
9212 the objects.
9214 @item -C
9215 @cindex @option{-C} (@command{gnatmake})
9216 Use a temporary mapping file. A mapping file is a way to communicate
9217 to the compiler two mappings: from unit names to file names (without
9218 any directory information) and from file names to path names (with
9219 full directory information). A mapping file can make the compiler's
9220 file searches faster, especially if there are many source directories,
9221 or the sources are read over a slow network connection. If
9222 @option{-P} is used, a mapping file is always used, so
9223 @option{-C} is unnecessary; in this case the mapping file
9224 is initially populated based on the project file. If
9225 @option{-C} is used without
9226 @option{-P},
9227 the mapping file is initially empty. Each invocation of the compiler
9228 will add any newly accessed sources to the mapping file.
9230 @item -C=@var{file}
9231 @cindex @option{-C=} (@command{gnatmake})
9232 Use a specific mapping file. The file, specified as a path name (absolute or
9233 relative) by this switch, should already exist, otherwise the switch is
9234 ineffective. The specified mapping file will be communicated to the compiler.
9235 This switch is not compatible with a project file
9236 (-P@var{file}) or with multiple compiling processes
9237 (-jnnn, when nnn is greater than 1).
9239 @item -d
9240 @cindex @option{-d} (@command{gnatmake})
9241 Display progress for each source, up to date or not, as a single line
9243 @smallexample
9244 completed x out of y (zz%)
9245 @end smallexample
9247 If the file needs to be compiled this is displayed after the invocation of
9248 the compiler. These lines are displayed even in quiet output mode.
9250 @item -D @var{dir}
9251 @cindex @option{-D} (@command{gnatmake})
9252 Put all object files and ALI file in directory @var{dir}.
9253 If the @option{-D} switch is not used, all object files
9254 and ALI files go in the current working directory.
9256 This switch cannot be used when using a project file.
9258 @item -eInnn
9259 @cindex @option{-eI} (@command{gnatmake})
9260 Indicates that the main source is a multi-unit source and the rank of the unit
9261 in the source file is nnn. nnn needs to be a positive number and a valid
9262 index in the source. This switch cannot be used when @command{gnatmake} is
9263 invoked for several mains.
9265 @item -eL
9266 @cindex @option{-eL} (@command{gnatmake})
9267 @cindex symbolic links
9268 Follow all symbolic links when processing project files.
9269 This should be used if your project uses symbolic links for files or
9270 directories, but is not needed in other cases.
9272 @cindex naming scheme
9273 This also assumes that no directory matches the naming scheme for files (for
9274 instance that you do not have a directory called "sources.ads" when using the
9275 default GNAT naming scheme).
9277 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9278 save a lot of system calls (several per source file and object file), which
9279 can result in a significant speed up to load and manipulate a project file,
9280 especially when using source files from a remote system.
9283 @item -eS
9284 @cindex @option{-eS} (@command{gnatmake})
9285 Output the commands for the compiler, the binder and the linker
9286 on standard output,
9287 instead of standard error.
9289 @item -f
9290 @cindex @option{-f} (@command{gnatmake})
9291 Force recompilations. Recompile all sources, even though some object
9292 files may be up to date, but don't recompile predefined or GNAT internal
9293 files or locked files (files with a write-protected ALI file),
9294 unless the @option{-a} switch is also specified.
9296 @item -F
9297 @cindex @option{-F} (@command{gnatmake})
9298 When using project files, if some errors or warnings are detected during
9299 parsing and verbose mode is not in effect (no use of switch
9300 -v), then error lines start with the full path name of the project
9301 file, rather than its simple file name.
9303 @item -g
9304 @cindex @option{-g} (@command{gnatmake})
9305 Enable debugging. This switch is simply passed to the compiler and to the
9306 linker.
9308 @item -i
9309 @cindex @option{-i} (@command{gnatmake})
9310 In normal mode, @command{gnatmake} compiles all object files and ALI files
9311 into the current directory. If the @option{-i} switch is used,
9312 then instead object files and ALI files that already exist are overwritten
9313 in place. This means that once a large project is organized into separate
9314 directories in the desired manner, then @command{gnatmake} will automatically
9315 maintain and update this organization. If no ALI files are found on the
9316 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9317 the new object and ALI files are created in the
9318 directory containing the source being compiled. If another organization
9319 is desired, where objects and sources are kept in different directories,
9320 a useful technique is to create dummy ALI files in the desired directories.
9321 When detecting such a dummy file, @command{gnatmake} will be forced to
9322 recompile the corresponding source file, and it will be put the resulting
9323 object and ALI files in the directory where it found the dummy file.
9325 @item -j@var{n}
9326 @cindex @option{-j} (@command{gnatmake})
9327 @cindex Parallel make
9328 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9329 machine compilations will occur in parallel. If @var{n} is 0, then the
9330 maximum number of parallel compilations is the number of core processors
9331 on the platform. In the event of compilation errors, messages from various
9332 compilations might get interspersed (but @command{gnatmake} will give you the
9333 full ordered list of failing compiles at the end). If this is problematic,
9334 rerun the make process with n set to 1 to get a clean list of messages.
9336 @item -k
9337 @cindex @option{-k} (@command{gnatmake})
9338 Keep going. Continue as much as possible after a compilation error. To
9339 ease the programmer's task in case of compilation errors, the list of
9340 sources for which the compile fails is given when @command{gnatmake}
9341 terminates.
9343 If @command{gnatmake} is invoked with several @file{file_names} and with this
9344 switch, if there are compilation errors when building an executable,
9345 @command{gnatmake} will not attempt to build the following executables.
9347 @item -l
9348 @cindex @option{-l} (@command{gnatmake})
9349 Link only. Can be combined with @option{-b} to binding
9350 and linking. Linking will not be performed if combined with
9351 @option{-c}
9352 but not with @option{-b}.
9353 When not combined with @option{-b}
9354 all the units in the closure of the main program must have been previously
9355 compiled and must be up to date, and the main program needs to have been bound.
9356 The root unit specified by @var{file_name}
9357 may be given without extension, with the source extension or, if no GNAT
9358 Project File is specified, with the ALI file extension.
9360 @item -m
9361 @cindex @option{-m} (@command{gnatmake})
9362 Specify that the minimum necessary amount of recompilations
9363 be performed. In this mode @command{gnatmake} ignores time
9364 stamp differences when the only
9365 modifications to a source file consist in adding/removing comments,
9366 empty lines, spaces or tabs. This means that if you have changed the
9367 comments in a source file or have simply reformatted it, using this
9368 switch will tell @command{gnatmake} not to recompile files that depend on it
9369 (provided other sources on which these files depend have undergone no
9370 semantic modifications). Note that the debugging information may be
9371 out of date with respect to the sources if the @option{-m} switch causes
9372 a compilation to be switched, so the use of this switch represents a
9373 trade-off between compilation time and accurate debugging information.
9375 @item -M
9376 @cindex Dependencies, producing list
9377 @cindex @option{-M} (@command{gnatmake})
9378 Check if all objects are up to date. If they are, output the object
9379 dependences to @file{stdout} in a form that can be directly exploited in
9380 a @file{Makefile}. By default, each source file is prefixed with its
9381 (relative or absolute) directory name. This name is whatever you
9382 specified in the various @option{-aI}
9383 and @option{-I} switches. If you use
9384 @code{gnatmake -M}
9385 @option{-q}
9386 (see below), only the source file names,
9387 without relative paths, are output. If you just specify the
9388 @option{-M}
9389 switch, dependencies of the GNAT internal system files are omitted. This
9390 is typically what you want. If you also specify
9391 the @option{-a} switch,
9392 dependencies of the GNAT internal files are also listed. Note that
9393 dependencies of the objects in external Ada libraries (see switch
9394 @option{-aL}@var{dir} in the following list)
9395 are never reported.
9397 @item -n
9398 @cindex @option{-n} (@command{gnatmake})
9399 Don't compile, bind, or link. Checks if all objects are up to date.
9400 If they are not, the full name of the first file that needs to be
9401 recompiled is printed.
9402 Repeated use of this option, followed by compiling the indicated source
9403 file, will eventually result in recompiling all required units.
9405 @item -o @var{exec_name}
9406 @cindex @option{-o} (@command{gnatmake})
9407 Output executable name. The name of the final executable program will be
9408 @var{exec_name}. If the @option{-o} switch is omitted the default
9409 name for the executable will be the name of the input file in appropriate form
9410 for an executable file on the host system.
9412 This switch cannot be used when invoking @command{gnatmake} with several
9413 @file{file_names}.
9415 @item -p or --create-missing-dirs
9416 @cindex @option{-p} (@command{gnatmake})
9417 When using project files (-P@var{project}), create
9418 automatically missing object directories, library directories and exec
9419 directories.
9421 @item -P@var{project}
9422 @cindex @option{-P} (@command{gnatmake})
9423 Use project file @var{project}. Only one such switch can be used.
9424 @xref{gnatmake and Project Files}.
9426 @item -q
9427 @cindex @option{-q} (@command{gnatmake})
9428 Quiet. When this flag is not set, the commands carried out by
9429 @command{gnatmake} are displayed.
9431 @item -s
9432 @cindex @option{-s} (@command{gnatmake})
9433 Recompile if compiler switches have changed since last compilation.
9434 All compiler switches but -I and -o are taken into account in the
9435 following way:
9436 orders between different ``first letter'' switches are ignored, but
9437 orders between same switches are taken into account. For example,
9438 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9439 is equivalent to @option{-O -g}.
9441 This switch is recommended when Integrated Preprocessing is used.
9443 @item -u
9444 @cindex @option{-u} (@command{gnatmake})
9445 Unique. Recompile at most the main files. It implies -c. Combined with
9446 -f, it is equivalent to calling the compiler directly. Note that using
9447 -u with a project file and no main has a special meaning
9448 (@pxref{Project Files and Main Subprograms}).
9450 @item -U
9451 @cindex @option{-U} (@command{gnatmake})
9452 When used without a project file or with one or several mains on the command
9453 line, is equivalent to -u. When used with a project file and no main
9454 on the command line, all sources of all project files are checked and compiled
9455 if not up to date, and libraries are rebuilt, if necessary.
9457 @item -v
9458 @cindex @option{-v} (@command{gnatmake})
9459 Verbose. Display the reason for all recompilations @command{gnatmake}
9460 decides are necessary, with the highest verbosity level.
9462 @item -vl
9463 @cindex @option{-vl} (@command{gnatmake})
9464 Verbosity level Low. Display fewer lines than in verbosity Medium.
9466 @item -vm
9467 @cindex @option{-vm} (@command{gnatmake})
9468 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9470 @item -vh
9471 @cindex @option{-vm} (@command{gnatmake})
9472 Verbosity level High. Equivalent to -v.
9474 @item -vP@emph{x}
9475 Indicate the verbosity of the parsing of GNAT project files.
9476 @xref{Switches Related to Project Files}.
9478 @item -x
9479 @cindex @option{-x} (@command{gnatmake})
9480 Indicate that sources that are not part of any Project File may be compiled.
9481 Normally, when using Project Files, only sources that are part of a Project
9482 File may be compile. When this switch is used, a source outside of all Project
9483 Files may be compiled. The ALI file and the object file will be put in the
9484 object directory of the main Project. The compilation switches used will only
9485 be those specified on the command line. Even when
9486 @option{-x} is used, mains specified on the
9487 command line need to be sources of a project file.
9489 @item -X@var{name=value}
9490 Indicate that external variable @var{name} has the value @var{value}.
9491 The Project Manager will use this value for occurrences of
9492 @code{external(name)} when parsing the project file.
9493 @xref{Switches Related to Project Files}.
9495 @item -z
9496 @cindex @option{-z} (@command{gnatmake})
9497 No main subprogram. Bind and link the program even if the unit name
9498 given on the command line is a package name. The resulting executable
9499 will execute the elaboration routines of the package and its closure,
9500 then the finalization routines.
9502 @end table
9504 @table @asis
9505 @item @command{gcc} @asis{switches}
9506 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9507 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9508 @end table
9510 @noindent
9511 Source and library search path switches:
9513 @table @option
9514 @c !sort!
9515 @item -aI@var{dir}
9516 @cindex @option{-aI} (@command{gnatmake})
9517 When looking for source files also look in directory @var{dir}.
9518 The order in which source files search is undertaken is
9519 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9521 @item -aL@var{dir}
9522 @cindex @option{-aL} (@command{gnatmake})
9523 Consider @var{dir} as being an externally provided Ada library.
9524 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9525 files have been located in directory @var{dir}. This allows you to have
9526 missing bodies for the units in @var{dir} and to ignore out of date bodies
9527 for the same units. You still need to specify
9528 the location of the specs for these units by using the switches
9529 @option{-aI@var{dir}}
9530 or @option{-I@var{dir}}.
9531 Note: this switch is provided for compatibility with previous versions
9532 of @command{gnatmake}. The easier method of causing standard libraries
9533 to be excluded from consideration is to write-protect the corresponding
9534 ALI files.
9536 @item -aO@var{dir}
9537 @cindex @option{-aO} (@command{gnatmake})
9538 When searching for library and object files, look in directory
9539 @var{dir}. The order in which library files are searched is described in
9540 @ref{Search Paths for gnatbind}.
9542 @item -A@var{dir}
9543 @cindex Search paths, for @command{gnatmake}
9544 @cindex @option{-A} (@command{gnatmake})
9545 Equivalent to @option{-aL@var{dir}
9546 -aI@var{dir}}.
9548 @item -I@var{dir}
9549 @cindex @option{-I} (@command{gnatmake})
9550 Equivalent to @option{-aO@var{dir}
9551 -aI@var{dir}}.
9553 @item -I-
9554 @cindex @option{-I-} (@command{gnatmake})
9555 @cindex Source files, suppressing search
9556 Do not look for source files in the directory containing the source
9557 file named in the command line.
9558 Do not look for ALI or object files in the directory
9559 where @command{gnatmake} was invoked.
9561 @item -L@var{dir}
9562 @cindex @option{-L} (@command{gnatmake})
9563 @cindex Linker libraries
9564 Add directory @var{dir} to the list of directories in which the linker
9565 will search for libraries. This is equivalent to
9566 @option{-largs -L}@var{dir}.
9567 Furthermore, under Windows, the sources pointed to by the libraries path
9568 set in the registry are not searched for.
9570 @item -nostdinc
9571 @cindex @option{-nostdinc} (@command{gnatmake})
9572 Do not look for source files in the system default directory.
9574 @item -nostdlib
9575 @cindex @option{-nostdlib} (@command{gnatmake})
9576 Do not look for library files in the system default directory.
9578 @item --RTS=@var{rts-path}
9579 @cindex @option{--RTS} (@command{gnatmake})
9580 Specifies the default location of the runtime library. GNAT looks for the
9581 runtime
9582 in the following directories, and stops as soon as a valid runtime is found
9583 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9584 @file{ada_object_path} present):
9586 @itemize @bullet
9587 @item <current directory>/$rts_path
9589 @item <default-search-dir>/$rts_path
9591 @item <default-search-dir>/rts-$rts_path
9592 @end itemize
9594 @noindent
9595 The selected path is handled like a normal RTS path.
9597 @end table
9599 @node Mode Switches for gnatmake
9600 @section Mode Switches for @command{gnatmake}
9602 @noindent
9603 The mode switches (referred to as @code{mode_switches}) allow the
9604 inclusion of switches that are to be passed to the compiler itself, the
9605 binder or the linker. The effect of a mode switch is to cause all
9606 subsequent switches up to the end of the switch list, or up to the next
9607 mode switch, to be interpreted as switches to be passed on to the
9608 designated component of GNAT.
9610 @table @option
9611 @c !sort!
9612 @item -cargs @var{switches}
9613 @cindex @option{-cargs} (@command{gnatmake})
9614 Compiler switches. Here @var{switches} is a list of switches
9615 that are valid switches for @command{gcc}. They will be passed on to
9616 all compile steps performed by @command{gnatmake}.
9618 @item -bargs @var{switches}
9619 @cindex @option{-bargs} (@command{gnatmake})
9620 Binder switches. Here @var{switches} is a list of switches
9621 that are valid switches for @code{gnatbind}. They will be passed on to
9622 all bind steps performed by @command{gnatmake}.
9624 @item -largs @var{switches}
9625 @cindex @option{-largs} (@command{gnatmake})
9626 Linker switches. Here @var{switches} is a list of switches
9627 that are valid switches for @command{gnatlink}. They will be passed on to
9628 all link steps performed by @command{gnatmake}.
9630 @item -margs @var{switches}
9631 @cindex @option{-margs} (@command{gnatmake})
9632 Make switches. The switches are directly interpreted by @command{gnatmake},
9633 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9634 or @option{-largs}.
9635 @end table
9637 @node Notes on the Command Line
9638 @section Notes on the Command Line
9640 @noindent
9641 This section contains some additional useful notes on the operation
9642 of the @command{gnatmake} command.
9644 @itemize @bullet
9645 @item
9646 @cindex Recompilation, by @command{gnatmake}
9647 If @command{gnatmake} finds no ALI files, it recompiles the main program
9648 and all other units required by the main program.
9649 This means that @command{gnatmake}
9650 can be used for the initial compile, as well as during subsequent steps of
9651 the development cycle.
9653 @item
9654 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9655 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9656 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9657 warning.
9659 @item
9660 In @command{gnatmake} the switch @option{-I}
9661 is used to specify both source and
9662 library file paths. Use @option{-aI}
9663 instead if you just want to specify
9664 source paths only and @option{-aO}
9665 if you want to specify library paths
9666 only.
9668 @item
9669 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9670 This may conveniently be used to exclude standard libraries from
9671 consideration and in particular it means that the use of the
9672 @option{-f} switch will not recompile these files
9673 unless @option{-a} is also specified.
9675 @item
9676 @command{gnatmake} has been designed to make the use of Ada libraries
9677 particularly convenient. Assume you have an Ada library organized
9678 as follows: @i{obj-dir} contains the objects and ALI files for
9679 of your Ada compilation units,
9680 whereas @i{include-dir} contains the
9681 specs of these units, but no bodies. Then to compile a unit
9682 stored in @code{main.adb}, which uses this Ada library you would just type
9684 @smallexample
9685 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9686 @end smallexample
9688 @item
9689 Using @command{gnatmake} along with the
9690 @option{-m (minimal recompilation)}
9691 switch provides a mechanism for avoiding unnecessary recompilations. Using
9692 this switch,
9693 you can update the comments/format of your
9694 source files without having to recompile everything. Note, however, that
9695 adding or deleting lines in a source files may render its debugging
9696 info obsolete. If the file in question is a spec, the impact is rather
9697 limited, as that debugging info will only be useful during the
9698 elaboration phase of your program. For bodies the impact can be more
9699 significant. In all events, your debugger will warn you if a source file
9700 is more recent than the corresponding object, and alert you to the fact
9701 that the debugging information may be out of date.
9702 @end itemize
9704 @node How gnatmake Works
9705 @section How @command{gnatmake} Works
9707 @noindent
9708 Generally @command{gnatmake} automatically performs all necessary
9709 recompilations and you don't need to worry about how it works. However,
9710 it may be useful to have some basic understanding of the @command{gnatmake}
9711 approach and in particular to understand how it uses the results of
9712 previous compilations without incorrectly depending on them.
9714 First a definition: an object file is considered @dfn{up to date} if the
9715 corresponding ALI file exists and if all the source files listed in the
9716 dependency section of this ALI file have time stamps matching those in
9717 the ALI file. This means that neither the source file itself nor any
9718 files that it depends on have been modified, and hence there is no need
9719 to recompile this file.
9721 @command{gnatmake} works by first checking if the specified main unit is up
9722 to date. If so, no compilations are required for the main unit. If not,
9723 @command{gnatmake} compiles the main program to build a new ALI file that
9724 reflects the latest sources. Then the ALI file of the main unit is
9725 examined to find all the source files on which the main program depends,
9726 and @command{gnatmake} recursively applies the above procedure on all these
9727 files.
9729 This process ensures that @command{gnatmake} only trusts the dependencies
9730 in an existing ALI file if they are known to be correct. Otherwise it
9731 always recompiles to determine a new, guaranteed accurate set of
9732 dependencies. As a result the program is compiled ``upside down'' from what may
9733 be more familiar as the required order of compilation in some other Ada
9734 systems. In particular, clients are compiled before the units on which
9735 they depend. The ability of GNAT to compile in any order is critical in
9736 allowing an order of compilation to be chosen that guarantees that
9737 @command{gnatmake} will recompute a correct set of new dependencies if
9738 necessary.
9740 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9741 imported by several of the executables, it will be recompiled at most once.
9743 Note: when using non-standard naming conventions
9744 (@pxref{Using Other File Names}), changing through a configuration pragmas
9745 file the version of a source and invoking @command{gnatmake} to recompile may
9746 have no effect, if the previous version of the source is still accessible
9747 by @command{gnatmake}. It may be necessary to use the switch
9750 @node Examples of gnatmake Usage
9751 @section Examples of @command{gnatmake} Usage
9753 @table @code
9754 @item gnatmake hello.adb
9755 Compile all files necessary to bind and link the main program
9756 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9757 resulting object files to generate an executable file @file{hello}.
9759 @item gnatmake main1 main2 main3
9760 Compile all files necessary to bind and link the main programs
9761 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9762 (containing unit @code{Main2}) and @file{main3.adb}
9763 (containing unit @code{Main3}) and bind and link the resulting object files
9764 to generate three executable files @file{main1},
9765 @file{main2}
9766 and @file{main3}.
9768 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9770 Compile all files necessary to bind and link the main program unit
9771 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9772 be done with optimization level 2 and the order of elaboration will be
9773 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9774 displaying commands it is executing.
9775 @end table
9777 @c *************************
9778 @node Improving Performance
9779 @chapter Improving Performance
9780 @cindex Improving performance
9782 @noindent
9783 This chapter presents several topics related to program performance.
9784 It first describes some of the tradeoffs that need to be considered
9785 and some of the techniques for making your program run faster.
9786 It then documents
9787 @ifclear FSFEDITION
9788 the @command{gnatelim} tool and
9789 @end ifclear
9790 unused subprogram/data
9791 elimination feature, which can reduce the size of program executables.
9793 @ifnottex
9794 @menu
9795 * Performance Considerations::
9796 * Text_IO Suggestions::
9797 @ifclear FSFEDITION
9798 * Reducing Size of Ada Executables with gnatelim::
9799 @end ifclear
9800 * Reducing Size of Executables with unused subprogram/data elimination::
9801 @end menu
9802 @end ifnottex
9804 @c *****************************
9805 @node Performance Considerations
9806 @section Performance Considerations
9808 @noindent
9809 The GNAT system provides a number of options that allow a trade-off
9810 between
9812 @itemize @bullet
9813 @item
9814 performance of the generated code
9816 @item
9817 speed of compilation
9819 @item
9820 minimization of dependences and recompilation
9822 @item
9823 the degree of run-time checking.
9824 @end itemize
9826 @noindent
9827 The defaults (if no options are selected) aim at improving the speed
9828 of compilation and minimizing dependences, at the expense of performance
9829 of the generated code:
9831 @itemize @bullet
9832 @item
9833 no optimization
9835 @item
9836 no inlining of subprogram calls
9838 @item
9839 all run-time checks enabled except overflow and elaboration checks
9840 @end itemize
9842 @noindent
9843 These options are suitable for most program development purposes. This
9844 chapter describes how you can modify these choices, and also provides
9845 some guidelines on debugging optimized code.
9847 @menu
9848 * Controlling Run-Time Checks::
9849 * Use of Restrictions::
9850 * Optimization Levels::
9851 * Debugging Optimized Code::
9852 * Inlining of Subprograms::
9853 * Vectorization of loops::
9854 * Other Optimization Switches::
9855 * Optimization and Strict Aliasing::
9856 * Aliased Variables and Optimization::
9857 * Atomic Variables and Optimization::
9858 * Passive Task Optimization::
9860 @end menu
9862 @node Controlling Run-Time Checks
9863 @subsection Controlling Run-Time Checks
9865 @noindent
9866 By default, GNAT generates all run-time checks, except integer overflow
9867 checks, stack overflow checks, and checks for access before elaboration on
9868 subprogram calls. The latter are not required in default mode, because all
9869 necessary checking is done at compile time.
9870 @cindex @option{-gnatp} (@command{gcc})
9871 @cindex @option{-gnato} (@command{gcc})
9872 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9873 be modified. @xref{Run-Time Checks}.
9875 Our experience is that the default is suitable for most development
9876 purposes.
9878 We treat integer overflow specially because these
9879 are quite expensive and in our experience are not as important as other
9880 run-time checks in the development process. Note that division by zero
9881 is not considered an overflow check, and divide by zero checks are
9882 generated where required by default.
9884 Elaboration checks are off by default, and also not needed by default, since
9885 GNAT uses a static elaboration analysis approach that avoids the need for
9886 run-time checking. This manual contains a full chapter discussing the issue
9887 of elaboration checks, and if the default is not satisfactory for your use,
9888 you should read this chapter.
9890 For validity checks, the minimal checks required by the Ada Reference
9891 Manual (for case statements and assignments to array elements) are on
9892 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9893 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9894 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9895 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9896 are also suppressed entirely if @option{-gnatp} is used.
9898 @cindex Overflow checks
9899 @cindex Checks, overflow
9900 @findex Suppress
9901 @findex Unsuppress
9902 @cindex pragma Suppress
9903 @cindex pragma Unsuppress
9904 Note that the setting of the switches controls the default setting of
9905 the checks. They may be modified using either @code{pragma Suppress} (to
9906 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9907 checks) in the program source.
9909 @node Use of Restrictions
9910 @subsection Use of Restrictions
9912 @noindent
9913 The use of pragma Restrictions allows you to control which features are
9914 permitted in your program. Apart from the obvious point that if you avoid
9915 relatively expensive features like finalization (enforceable by the use
9916 of pragma Restrictions (No_Finalization), the use of this pragma does not
9917 affect the generated code in most cases.
9919 One notable exception to this rule is that the possibility of task abort
9920 results in some distributed overhead, particularly if finalization or
9921 exception handlers are used. The reason is that certain sections of code
9922 have to be marked as non-abortable.
9924 If you use neither the @code{abort} statement, nor asynchronous transfer
9925 of control (@code{select @dots{} then abort}), then this distributed overhead
9926 is removed, which may have a general positive effect in improving
9927 overall performance.  Especially code involving frequent use of tasking
9928 constructs and controlled types will show much improved performance.
9929 The relevant restrictions pragmas are
9931 @smallexample @c ada
9932    @b{pragma} Restrictions (No_Abort_Statements);
9933    @b{pragma} Restrictions (Max_Asynchronous_Select_Nesting => 0);
9934 @end smallexample
9936 @noindent
9937 It is recommended that these restriction pragmas be used if possible. Note
9938 that this also means that you can write code without worrying about the
9939 possibility of an immediate abort at any point.
9941 @node Optimization Levels
9942 @subsection Optimization Levels
9943 @cindex @option{-O} (@command{gcc})
9945 @noindent
9946 Without any optimization option,
9947 the compiler's goal is to reduce the cost of
9948 compilation and to make debugging produce the expected results.
9949 Statements are independent: if you stop the program with a breakpoint between
9950 statements, you can then assign a new value to any variable or change
9951 the program counter to any other statement in the subprogram and get exactly
9952 the results you would expect from the source code.
9954 Turning on optimization makes the compiler attempt to improve the
9955 performance and/or code size at the expense of compilation time and
9956 possibly the ability to debug the program.
9958 If you use multiple
9959 -O options, with or without level numbers,
9960 the last such option is the one that is effective.
9962 @noindent
9963 The default is optimization off. This results in the fastest compile
9964 times, but GNAT makes absolutely no attempt to optimize, and the
9965 generated programs are considerably larger and slower than when
9966 optimization is enabled. You can use the
9967 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9968 @option{-O2}, @option{-O3}, and @option{-Os})
9969 to @command{gcc} to control the optimization level:
9971 @table @option
9972 @item -O0
9973 No optimization (the default);
9974 generates unoptimized code but has
9975 the fastest compilation time.
9977 Note that many other compilers do fairly extensive optimization
9978 even if ``no optimization'' is specified. With gcc, it is
9979 very unusual to use -O0 for production if
9980 execution time is of any concern, since -O0
9981 really does mean no optimization at all. This difference between
9982 gcc and other compilers should be kept in mind when doing
9983 performance comparisons.
9985 @item -O1
9986 Moderate optimization;
9987 optimizes reasonably well but does not
9988 degrade compilation time significantly.
9990 @item -O2
9991 Full optimization;
9992 generates highly optimized code and has
9993 the slowest compilation time.
9995 @item -O3
9996 Full optimization as in @option{-O2};
9997 also uses more aggressive automatic inlining of subprograms within a unit
9998 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10000 @item -Os
10001 Optimize space usage (code and data) of resulting program.
10002 @end table
10004 @noindent
10005 Higher optimization levels perform more global transformations on the
10006 program and apply more expensive analysis algorithms in order to generate
10007 faster and more compact code. The price in compilation time, and the
10008 resulting improvement in execution time,
10009 both depend on the particular application and the hardware environment.
10010 You should experiment to find the best level for your application.
10012 Since the precise set of optimizations done at each level will vary from
10013 release to release (and sometime from target to target), it is best to think
10014 of the optimization settings in general terms.
10015 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10016 the GNU Compiler Collection (GCC)}, for details about
10017 the @option{-O} settings and a number of @option{-f} options that
10018 individually enable or disable specific optimizations.
10020 Unlike some other compilation systems, @command{gcc} has
10021 been tested extensively at all optimization levels. There are some bugs
10022 which appear only with optimization turned on, but there have also been
10023 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10024 level of optimization does not improve the reliability of the code
10025 generator, which in practice is highly reliable at all optimization
10026 levels.
10028 Note regarding the use of @option{-O3}: The use of this optimization level
10029 is generally discouraged with GNAT, since it often results in larger
10030 executables which may run more slowly. See further discussion of this point
10031 in @ref{Inlining of Subprograms}.
10033 @node Debugging Optimized Code
10034 @subsection Debugging Optimized Code
10035 @cindex Debugging optimized code
10036 @cindex Optimization and debugging
10038 @noindent
10039 Although it is possible to do a reasonable amount of debugging at
10040 nonzero optimization levels,
10041 the higher the level the more likely that
10042 source-level constructs will have been eliminated by optimization.
10043 For example, if a loop is strength-reduced, the loop
10044 control variable may be completely eliminated and thus cannot be
10045 displayed in the debugger.
10046 This can only happen at @option{-O2} or @option{-O3}.
10047 Explicit temporary variables that you code might be eliminated at
10048 level @option{-O1} or higher.
10050 The use of the @option{-g} switch,
10051 @cindex @option{-g} (@command{gcc})
10052 which is needed for source-level debugging,
10053 affects the size of the program executable on disk,
10054 and indeed the debugging information can be quite large.
10055 However, it has no effect on the generated code (and thus does not
10056 degrade performance)
10058 Since the compiler generates debugging tables for a compilation unit before
10059 it performs optimizations, the optimizing transformations may invalidate some
10060 of the debugging data.  You therefore need to anticipate certain
10061 anomalous situations that may arise while debugging optimized code.
10062 These are the most common cases:
10064 @enumerate
10065 @item
10066 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10067 commands show
10068 the PC bouncing back and forth in the code.  This may result from any of
10069 the following optimizations:
10071 @itemize @bullet
10072 @item
10073 @i{Common subexpression elimination:} using a single instance of code for a
10074 quantity that the source computes several times.  As a result you
10075 may not be able to stop on what looks like a statement.
10077 @item
10078 @i{Invariant code motion:} moving an expression that does not change within a
10079 loop, to the beginning of the loop.
10081 @item
10082 @i{Instruction scheduling:} moving instructions so as to
10083 overlap loads and stores (typically) with other code, or in
10084 general to move computations of values closer to their uses. Often
10085 this causes you to pass an assignment statement without the assignment
10086 happening and then later bounce back to the statement when the
10087 value is actually needed.  Placing a breakpoint on a line of code
10088 and then stepping over it may, therefore, not always cause all the
10089 expected side-effects.
10090 @end itemize
10092 @item
10093 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10094 two identical pieces of code are merged and the program counter suddenly
10095 jumps to a statement that is not supposed to be executed, simply because
10096 it (and the code following) translates to the same thing as the code
10097 that @emph{was} supposed to be executed.  This effect is typically seen in
10098 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10099 a @code{break} in a C @code{switch} statement.
10101 @item
10102 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10103 There are various reasons for this effect:
10105 @itemize @bullet
10106 @item
10107 In a subprogram prologue, a parameter may not yet have been moved to its
10108 ``home''.
10110 @item
10111 A variable may be dead, and its register re-used.  This is
10112 probably the most common cause.
10114 @item
10115 As mentioned above, the assignment of a value to a variable may
10116 have been moved.
10118 @item
10119 A variable may be eliminated entirely by value propagation or
10120 other means.  In this case, GCC may incorrectly generate debugging
10121 information for the variable
10122 @end itemize
10124 @noindent
10125 In general, when an unexpected value appears for a local variable or parameter
10126 you should first ascertain if that value was actually computed by
10127 your program, as opposed to being incorrectly reported by the debugger.
10128 Record fields or
10129 array elements in an object designated by an access value
10130 are generally less of a problem, once you have ascertained that the access
10131 value is sensible.
10132 Typically, this means checking variables in the preceding code and in the
10133 calling subprogram to verify that the value observed is explainable from other
10134 values (one must apply the procedure recursively to those
10135 other values); or re-running the code and stopping a little earlier
10136 (perhaps before the call) and stepping to better see how the variable obtained
10137 the value in question; or continuing to step @emph{from} the point of the
10138 strange value to see if code motion had simply moved the variable's
10139 assignments later.
10140 @end enumerate
10142 @noindent
10143 In light of such anomalies, a recommended technique is to use @option{-O0}
10144 early in the software development cycle, when extensive debugging capabilities
10145 are most needed, and then move to @option{-O1} and later @option{-O2} as
10146 the debugger becomes less critical.
10147 Whether to use the @option{-g} switch in the release version is
10148 a release management issue.
10149 Note that if you use @option{-g} you can then use the @command{strip} program
10150 on the resulting executable,
10151 which removes both debugging information and global symbols.
10153 @node Inlining of Subprograms
10154 @subsection Inlining of Subprograms
10156 @noindent
10157 A call to a subprogram in the current unit is inlined if all the
10158 following conditions are met:
10160 @itemize @bullet
10161 @item
10162 The optimization level is at least @option{-O1}.
10164 @item
10165 The called subprogram is suitable for inlining: It must be small enough
10166 and not contain something that @command{gcc} cannot support in inlined
10167 subprograms.
10169 @item
10170 @cindex pragma Inline
10171 @findex Inline
10172 Any one of the following applies: @code{pragma Inline} is applied to the
10173 subprogram and the @option{-gnatn} switch is specified; the
10174 subprogram is local to the unit and called once from within it; the
10175 subprogram is small and optimization level @option{-O2} is specified;
10176 optimization level @option{-O3} is specified.
10177 @end itemize
10179 @noindent
10180 Calls to subprograms in @code{with}'ed units are normally not inlined.
10181 To achieve actual inlining (that is, replacement of the call by the code
10182 in the body of the subprogram), the following conditions must all be true:
10184 @itemize @bullet
10185 @item
10186 The optimization level is at least @option{-O1}.
10188 @item
10189 The called subprogram is suitable for inlining: It must be small enough
10190 and not contain something that @command{gcc} cannot support in inlined
10191 subprograms.
10193 @item
10194 The call appears in a body (not in a package spec).
10196 @item
10197 There is a @code{pragma Inline} for the subprogram.
10199 @item
10200 The @option{-gnatn} switch is used on the command line.
10201 @end itemize
10203 Even if all these conditions are met, it may not be possible for
10204 the compiler to inline the call, due to the length of the body,
10205 or features in the body that make it impossible for the compiler
10206 to do the inlining.
10208 Note that specifying the @option{-gnatn} switch causes additional
10209 compilation dependencies. Consider the following:
10211 @smallexample @c ada
10212 @cartouche
10213 @b{package} R @b{is}
10214    @b{procedure} Q;
10215    @b{pragma} Inline (Q);
10216 @b{end} R;
10217 @b{package} @b{body} R @b{is}
10218    @dots{}
10219 @b{end} R;
10221 @b{with} R;
10222 @b{procedure} Main @b{is}
10223 @b{begin}
10224    @dots{}
10225    R.Q;
10226 @b{end} Main;
10227 @end cartouche
10228 @end smallexample
10230 @noindent
10231 With the default behavior (no @option{-gnatn} switch specified), the
10232 compilation of the @code{Main} procedure depends only on its own source,
10233 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10234 means that editing the body of @code{R} does not require recompiling
10235 @code{Main}.
10237 On the other hand, the call @code{R.Q} is not inlined under these
10238 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10239 is compiled, the call will be inlined if the body of @code{Q} is small
10240 enough, but now @code{Main} depends on the body of @code{R} in
10241 @file{r.adb} as well as on the spec. This means that if this body is edited,
10242 the main program must be recompiled. Note that this extra dependency
10243 occurs whether or not the call is in fact inlined by @command{gcc}.
10245 The use of front end inlining with @option{-gnatN} generates similar
10246 additional dependencies.
10248 @cindex @option{-fno-inline} (@command{gcc})
10249 Note: The @option{-fno-inline} switch
10250 can be used to prevent
10251 all inlining. This switch overrides all other conditions and ensures
10252 that no inlining occurs. The extra dependences resulting from
10253 @option{-gnatn} will still be active, even if
10254 this switch is used to suppress the resulting inlining actions.
10256 @cindex @option{-fno-inline-functions} (@command{gcc})
10257 Note: The @option{-fno-inline-functions} switch can be used to prevent
10258 automatic inlining of subprograms if @option{-O3} is used.
10260 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10261 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10262 automatic inlining of small subprograms if @option{-O2} is used.
10264 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10265 Note: The @option{-fno-inline-functions-called-once} switch
10266 can be used to prevent inlining of subprograms local to the unit
10267 and called once from within it if @option{-O1} is used.
10269 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10270 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10271 specified in lieu of it, @option{-gnatn} being translated into one of them
10272 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10273 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10274 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10275 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10276 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
10277 effect of inlining subprograms you did not think should be inlined. We have
10278 found that the use of @option{-O3} may slow down the compilation and increase
10279 the code size by performing excessive inlining, leading to increased
10280 instruction cache pressure from the increased code size and thus minor
10281 performance improvements. So the bottom line here is that you should not
10282 automatically assume that @option{-O3} is better than @option{-O2}, and
10283 indeed you should use @option{-O3} only if tests show that it actually
10284 improves performance for your program.
10286 @node Vectorization of loops
10287 @subsection Vectorization of loops
10288 @cindex Optimization Switches
10290 You can take advantage of the auto-vectorizer present in the @command{gcc}
10291 back end to vectorize loops with GNAT.  The corresponding command line switch
10292 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10293 and other aggressive optimizations helpful for vectorization also are enabled
10294 by default at this level, using @option{-O3} directly is recommended.
10296 You also need to make sure that the target architecture features a supported
10297 SIMD instruction set.  For example, for the x86 architecture, you should at
10298 least specify @option{-msse2} to get significant vectorization (but you don't
10299 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10300 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10302 The preferred loop form for vectorization is the @code{for} iteration scheme.
10303 Loops with a @code{while} iteration scheme can also be vectorized if they are
10304 very simple, but the vectorizer will quickly give up otherwise.  With either
10305 iteration scheme, the flow of control must be straight, in particular no
10306 @code{exit} statement may appear in the loop body.  The loop may however
10307 contain a single nested loop, if it can be vectorized when considered alone:
10309 @smallexample @c ada
10310 @cartouche
10311    A : @b{array} (1..4, 1..4) @b{of} Long_Float;
10312    S : @b{array} (1..4) @b{of} Long_Float;
10314    @b{procedure} Sum @b{is}
10315    @b{begin}
10316       @b{for} I @b{in} A'Range(1) @b{loop}
10317          @b{for} J @b{in} A'Range(2) @b{loop}
10318             S (I) := S (I) + A (I, J);
10319          @b{end} @b{loop};
10320       @b{end} @b{loop};
10321    @b{end} Sum;
10322 @end cartouche
10323 @end smallexample
10325 The vectorizable operations depend on the targeted SIMD instruction set, but
10326 the adding and some of the multiplying operators are generally supported, as
10327 well as the logical operators for modular types.  Note that, in the former
10328 case, enabling overflow checks, for example with @option{-gnato}, totally
10329 disables vectorization.  The other checks are not supposed to have the same
10330 definitive effect, although compiling with @option{-gnatp} might well reveal
10331 cases where some checks do thwart vectorization.
10333 Type conversions may also prevent vectorization if they involve semantics that
10334 are not directly supported by the code generator or the SIMD instruction set.
10335 A typical example is direct conversion from floating-point to integer types.
10336 The solution in this case is to use the following idiom:
10338 @smallexample @c ada
10339    Integer (S'Truncation (F))
10340 @end smallexample
10342 @noindent
10343 if @code{S} is the subtype of floating-point object @code{F}.
10345 In most cases, the vectorizable loops are loops that iterate over arrays.
10346 All kinds of array types are supported, i.e. constrained array types with
10347 static bounds:
10349 @smallexample @c ada
10350    @b{type} Array_Type @b{is} @b{array} (1 .. 4) @b{of} Long_Float;
10351 @end smallexample
10353 @noindent
10354 constrained array types with dynamic bounds:
10356 @smallexample @c ada
10357    @b{type} Array_Type @b{is} @b{array} (1 .. Q.N) @b{of} Long_Float;
10359    @b{type} Array_Type @b{is} @b{array} (Q.K .. 4) @b{of} Long_Float;
10361    @b{type} Array_Type @b{is} @b{array} (Q.K .. Q.N) @b{of} Long_Float;
10362 @end smallexample
10364 @noindent
10365 or unconstrained array types:
10367 @smallexample @c ada
10368   @b{type} Array_Type @b{is} @b{array} (Positive @b{range} <>) @b{of} Long_Float;
10369 @end smallexample
10371 @noindent
10372 The quality of the generated code decreases when the dynamic aspect of the
10373 array type increases, the worst code being generated for unconstrained array
10374 types.  This is so because, the less information the compiler has about the
10375 bounds of the array, the more fallback code it needs to generate in order to
10376 fix things up at run time.
10378 It is possible to specify that a given loop should be subject to vectorization
10379 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10381 @smallexample @c ada
10382   @b{pragma} Loop_Optimize (Vector);
10383 @end smallexample
10385 @noindent
10386 placed immediately within the loop will convey the appropriate hint to the
10387 compiler for this loop.
10389 It is also possible to help the compiler generate better vectorized code
10390 for a given loop by asserting that there are no loop-carried dependencies
10391 in the loop.  Consider for example the procedure:
10393 @smallexample @c ada
10394   @b{type} Arr @b{is} @b{array} (1 .. 4) @b{of} Long_Float;
10396   @b{procedure} Add (X, Y : @b{not} @b{null} @b{access} Arr; R : @b{not} @b{null} @b{access} Arr) @b{is}
10397   @b{begin}
10398     @b{for} I @b{in} Arr'Range @b{loop}
10399       R(I) := X(I) + Y(I);
10400     @b{end} @b{loop};
10401   @b{end};
10402 @end smallexample
10404 @noindent
10405 By default, the compiler cannot unconditionally vectorize the loop because
10406 assigning to a component of the array designated by R in one iteration could
10407 change the value read from the components of the array designated by X or Y
10408 in a later iteration.  As a result, the compiler will generate two versions
10409 of the loop in the object code, one vectorized and the other not vectorized,
10410 as well as a test to select the appropriate version at run time.  This can
10411 be overcome by another hint:
10413 @smallexample @c ada
10414   @b{pragma} Loop_Optimize (Ivdep);
10415 @end smallexample
10417 @noindent
10418 placed immediately within the loop will tell the compiler that it can safely
10419 omit the non-vectorized version of the loop as well as the run-time test.
10421 @node Other Optimization Switches
10422 @subsection Other Optimization Switches
10423 @cindex Optimization Switches
10425 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10426 @command{gcc} optimization switches are potentially usable. These switches
10427 have not been extensively tested with GNAT but can generally be expected
10428 to work. Examples of switches in this category are @option{-funroll-loops}
10429 and the various target-specific @option{-m} options (in particular, it has
10430 been observed that @option{-march=xxx} can significantly improve performance
10431 on appropriate machines). For full details of these switches, see
10432 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10433 the GNU Compiler Collection (GCC)}.
10435 @node Optimization and Strict Aliasing
10436 @subsection Optimization and Strict Aliasing
10437 @cindex Aliasing
10438 @cindex Strict Aliasing
10439 @cindex No_Strict_Aliasing
10441 @noindent
10442 The strong typing capabilities of Ada allow an optimizer to generate
10443 efficient code in situations where other languages would be forced to
10444 make worst case assumptions preventing such optimizations. Consider
10445 the following example:
10447 @smallexample @c ada
10448 @cartouche
10449 @b{procedure} R @b{is}
10450    @b{type} Int1 @b{is} @b{new} Integer;
10451    @b{type} Int2 @b{is} @b{new} Integer;
10452    @b{type} Int1A @b{is} @b{access} Int1;
10453    @b{type} Int2A @b{is} @b{access} Int2;
10454    Int1V : Int1A;
10455    Int2V : Int2A;
10456    @dots{}
10458 @b{begin}
10459    @dots{}
10460    @b{for} J @b{in} Data'Range @b{loop}
10461       @b{if} Data (J) = Int1V.@b{all} @b{then}
10462          Int2V.@b{all} := Int2V.@b{all} + 1;
10463       @b{end} @b{if};
10464    @b{end} @b{loop};
10465    @dots{}
10466 @b{end} R;
10467 @end cartouche
10468 @end smallexample
10470 @noindent
10471 In this example, since the variable @code{Int1V} can only access objects
10472 of type @code{Int1}, and @code{Int2V} can only access objects of type
10473 @code{Int2}, there is no possibility that the assignment to
10474 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10475 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10476 for all iterations of the loop and avoid the extra memory reference
10477 required to dereference it each time through the loop.
10479 This kind of optimization, called strict aliasing analysis, is
10480 triggered by specifying an optimization level of @option{-O2} or
10481 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10482 when access values are involved.
10484 However, although this optimization is always correct in terms of
10485 the formal semantics of the Ada Reference Manual, difficulties can
10486 arise if features like @code{Unchecked_Conversion} are used to break
10487 the typing system. Consider the following complete program example:
10489 @smallexample @c ada
10490 @cartouche
10491 @b{package} p1 @b{is}
10492    @b{type} int1 @b{is} @b{new} integer;
10493    @b{type} int2 @b{is} @b{new} integer;
10494    @b{type} a1 @b{is} @b{access} int1;
10495    @b{type} a2 @b{is} @b{access} int2;
10496 @b{end} p1;
10498 @b{with} p1; @b{use} p1;
10499 @b{package} p2 @b{is}
10500    @b{function} to_a2 (Input : a1) @b{return} a2;
10501 @b{end} p2;
10503 @b{with} Unchecked_Conversion;
10504 @b{package} @b{body} p2 @b{is}
10505    @b{function} to_a2 (Input : a1) @b{return} a2 @b{is}
10506       @b{function} to_a2u @b{is}
10507         @b{new} Unchecked_Conversion (a1, a2);
10508    @b{begin}
10509       @b{return} to_a2u (Input);
10510    @b{end} to_a2;
10511 @b{end} p2;
10513 @b{with} p2; @b{use} p2;
10514 @b{with} p1; @b{use} p1;
10515 @b{with} Text_IO; @b{use} Text_IO;
10516 @b{procedure} m @b{is}
10517    v1 : a1 := @b{new} int1;
10518    v2 : a2 := to_a2 (v1);
10519 @b{begin}
10520    v1.@b{all} := 1;
10521    v2.@b{all} := 0;
10522    put_line (int1'image (v1.@b{all}));
10523 @b{end};
10524 @end cartouche
10525 @end smallexample
10527 @noindent
10528 This program prints out 0 in @option{-O0} or @option{-O1}
10529 mode, but it prints out 1 in @option{-O2} mode. That's
10530 because in strict aliasing mode, the compiler can and
10531 does assume that the assignment to @code{v2.all} could not
10532 affect the value of @code{v1.all}, since different types
10533 are involved.
10535 This behavior is not a case of non-conformance with the standard, since
10536 the Ada RM specifies that an unchecked conversion where the resulting
10537 bit pattern is not a correct value of the target type can result in an
10538 abnormal value and attempting to reference an abnormal value makes the
10539 execution of a program erroneous.  That's the case here since the result
10540 does not point to an object of type @code{int2}.  This means that the
10541 effect is entirely unpredictable.
10543 However, although that explanation may satisfy a language
10544 lawyer, in practice an applications programmer expects an
10545 unchecked conversion involving pointers to create true
10546 aliases and the behavior of printing 1 seems plain wrong.
10547 In this case, the strict aliasing optimization is unwelcome.
10549 Indeed the compiler recognizes this possibility, and the
10550 unchecked conversion generates a warning:
10552 @smallexample
10553 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10554 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10555 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10556 @end smallexample
10558 @noindent
10559 Unfortunately the problem is recognized when compiling the body of
10560 package @code{p2}, but the actual "bad" code is generated while
10561 compiling the body of @code{m} and this latter compilation does not see
10562 the suspicious @code{Unchecked_Conversion}.
10564 As implied by the warning message, there are approaches you can use to
10565 avoid the unwanted strict aliasing optimization in a case like this.
10567 One possibility is to simply avoid the use of @option{-O2}, but
10568 that is a bit drastic, since it throws away a number of useful
10569 optimizations that do not involve strict aliasing assumptions.
10571 A less drastic approach is to compile the program using the
10572 option @option{-fno-strict-aliasing}. Actually it is only the
10573 unit containing the dereferencing of the suspicious pointer
10574 that needs to be compiled. So in this case, if we compile
10575 unit @code{m} with this switch, then we get the expected
10576 value of zero printed. Analyzing which units might need
10577 the switch can be painful, so a more reasonable approach
10578 is to compile the entire program with options @option{-O2}
10579 and @option{-fno-strict-aliasing}. If the performance is
10580 satisfactory with this combination of options, then the
10581 advantage is that the entire issue of possible "wrong"
10582 optimization due to strict aliasing is avoided.
10584 To avoid the use of compiler switches, the configuration
10585 pragma @code{No_Strict_Aliasing} with no parameters may be
10586 used to specify that for all access types, the strict
10587 aliasing optimization should be suppressed.
10589 However, these approaches are still overkill, in that they causes
10590 all manipulations of all access values to be deoptimized. A more
10591 refined approach is to concentrate attention on the specific
10592 access type identified as problematic.
10594 First, if a careful analysis of uses of the pointer shows
10595 that there are no possible problematic references, then
10596 the warning can be suppressed by bracketing the
10597 instantiation of @code{Unchecked_Conversion} to turn
10598 the warning off:
10600 @smallexample @c ada
10601    @b{pragma} Warnings (Off);
10602    @b{function} to_a2u @b{is}
10603      @b{new} Unchecked_Conversion (a1, a2);
10604    @b{pragma} Warnings (On);
10605 @end smallexample
10607 @noindent
10608 Of course that approach is not appropriate for this particular
10609 example, since indeed there is a problematic reference. In this
10610 case we can take one of two other approaches.
10612 The first possibility is to move the instantiation of unchecked
10613 conversion to the unit in which the type is declared. In
10614 this example, we would move the instantiation of
10615 @code{Unchecked_Conversion} from the body of package
10616 @code{p2} to the spec of package @code{p1}. Now the
10617 warning disappears. That's because any use of the
10618 access type knows there is a suspicious unchecked
10619 conversion, and the strict aliasing optimization
10620 is automatically suppressed for the type.
10622 If it is not practical to move the unchecked conversion to the same unit
10623 in which the destination access type is declared (perhaps because the
10624 source type is not visible in that unit), you may use pragma
10625 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10626 same declarative sequence as the declaration of the access type:
10628 @smallexample @c ada
10629    @b{type} a2 @b{is} @b{access} int2;
10630    @b{pragma} No_Strict_Aliasing (a2);
10631 @end smallexample
10633 @noindent
10634 Here again, the compiler now knows that the strict aliasing optimization
10635 should be suppressed for any reference to type @code{a2} and the
10636 expected behavior is obtained.
10638 Finally, note that although the compiler can generate warnings for
10639 simple cases of unchecked conversions, there are tricker and more
10640 indirect ways of creating type incorrect aliases which the compiler
10641 cannot detect. Examples are the use of address overlays and unchecked
10642 conversions involving composite types containing access types as
10643 components. In such cases, no warnings are generated, but there can
10644 still be aliasing problems. One safe coding practice is to forbid the
10645 use of address clauses for type overlaying, and to allow unchecked
10646 conversion only for primitive types. This is not really a significant
10647 restriction since any possible desired effect can be achieved by
10648 unchecked conversion of access values.
10650 The aliasing analysis done in strict aliasing mode can certainly
10651 have significant benefits. We have seen cases of large scale
10652 application code where the time is increased by up to 5% by turning
10653 this optimization off. If you have code that includes significant
10654 usage of unchecked conversion, you might want to just stick with
10655 @option{-O1} and avoid the entire issue. If you get adequate
10656 performance at this level of optimization level, that's probably
10657 the safest approach. If tests show that you really need higher
10658 levels of optimization, then you can experiment with @option{-O2}
10659 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10660 has on size and speed of the code. If you really need to use
10661 @option{-O2} with strict aliasing in effect, then you should
10662 review any uses of unchecked conversion of access types,
10663 particularly if you are getting the warnings described above.
10665 @node Aliased Variables and Optimization
10666 @subsection Aliased Variables and Optimization
10667 @cindex Aliasing
10668 There are scenarios in which programs may
10669 use low level techniques to modify variables
10670 that otherwise might be considered to be unassigned. For example,
10671 a variable can be passed to a procedure by reference, which takes
10672 the address of the parameter and uses the address to modify the
10673 variable's value, even though it is passed as an IN parameter.
10674 Consider the following example:
10676 @smallexample @c ada
10677 @b{procedure} P @b{is}
10678    Max_Length : @b{constant} Natural := 16;
10679    @b{type} Char_Ptr @b{is} @b{access} @b{all} Character;
10681    @b{procedure} Get_String(Buffer: Char_Ptr; Size : Integer);
10682    @b{pragma} Import (C, Get_String, "get_string");
10684    Name : @b{aliased} String (1 .. Max_Length) := (@b{others} => ' ');
10685    Temp : Char_Ptr;
10687    @b{function} Addr (S : String) @b{return} Char_Ptr @b{is}
10688       @b{function} To_Char_Ptr @b{is}
10689         @b{new} Ada.Unchecked_Conversion (System.Address, Char_Ptr);
10690    @b{begin}
10691       @b{return} To_Char_Ptr (S (S'First)'Address);
10692    @b{end};
10694 @b{begin}
10695    Temp := Addr (Name);
10696    Get_String (Temp, Max_Length);
10697 @b{end};
10698 @end smallexample
10700 @noindent
10701 where Get_String is a C function that uses the address in Temp to
10702 modify the variable @code{Name}. This code is dubious, and arguably
10703 erroneous, and the compiler would be entitled to assume that
10704 @code{Name} is never modified, and generate code accordingly.
10706 However, in practice, this would cause some existing code that
10707 seems to work with no optimization to start failing at high
10708 levels of optimzization.
10710 What the compiler does for such cases is to assume that marking
10711 a variable as aliased indicates that some "funny business" may
10712 be going on. The optimizer recognizes the aliased keyword and
10713 inhibits optimizations that assume the value cannot be assigned.
10714 This means that the above example will in fact "work" reliably,
10715 that is, it will produce the expected results.
10717 @node Atomic Variables and Optimization
10718 @subsection Atomic Variables and Optimization
10719 @cindex Atomic
10720 There are two considerations with regard to performance when
10721 atomic variables are used.
10723 First, the RM only guarantees that access to atomic variables
10724 be atomic, it has nothing to say about how this is achieved,
10725 though there is a strong implication that this should not be
10726 achieved by explicit locking code. Indeed GNAT will never
10727 generate any locking code for atomic variable access (it will
10728 simply reject any attempt to make a variable or type atomic
10729 if the atomic access cannot be achieved without such locking code).
10731 That being said, it is important to understand that you cannot
10732 assume that the entire variable will always be accessed. Consider
10733 this example:
10735 @smallexample @c ada
10736 @b{type} R @b{is} @b{record}
10737    A,B,C,D : Character;
10738 @b{end} @b{record};
10739 @b{for} R'Size @b{use} 32;
10740 @b{for} R'Alignment @b{use} 4;
10742 RV : R;
10743 @b{pragma} Atomic (RV);
10744 X : Character;
10746 X := RV.B;
10747 @end smallexample
10749 @noindent
10750 You cannot assume that the reference to @code{RV.B}
10751 will read the entire 32-bit
10752 variable with a single load instruction. It is perfectly legitimate if
10753 the hardware allows it to do a byte read of just the B field. This read
10754 is still atomic, which is all the RM requires. GNAT can and does take
10755 advantage of this, depending on the architecture and optimization level.
10756 Any assumption to the contrary is non-portable and risky. Even if you
10757 examine the assembly language and see a full 32-bit load, this might
10758 change in a future version of the compiler.
10760 If your application requires that all accesses to @code{RV} in this
10761 example be full 32-bit loads, you need to make a copy for the access
10762 as in:
10764 @smallexample @c ada
10765 @b{declare}
10766    RV_Copy : @b{constant} R := RV;
10767 @b{begin}
10768    X := RV_Copy.B;
10769 @b{end};
10770 @end smallexample
10773 @noindent
10774 Now the reference to RV must read the whole variable.
10775 Actually one can imagine some compiler which figures
10776 out that the whole copy is not required (because only
10777 the B field is actually accessed), but GNAT
10778 certainly won't do that, and we don't know of any
10779 compiler that would not handle this right, and the
10780 above code will in practice work portably across
10781 all architectures (that permit the Atomic declaration).
10783 The second issue with atomic variables has to do with
10784 the possible requirement of generating synchronization
10785 code. For more details on this, consult the sections on
10786 the pragmas Enable/Disable_Atomic_Synchronization in the
10787 GNAT Reference Manual. If performance is critical, and
10788 such synchronization code is not required, it may be
10789 useful to disable it.
10791 @node Passive Task Optimization
10792 @subsection Passive Task Optimization
10793 @cindex Passive Task
10795 A passive task is one which is sufficiently simple that
10796 in theory a compiler could recognize it an implement it
10797 efficiently without creating a new thread. The original design
10798 of Ada 83 had in mind this kind of passive task optimization, but
10799 only a few Ada 83 compilers attempted it. The problem was that
10800 it was difficult to determine the exact conditions under which
10801 the optimization was possible. The result is a very fragile
10802 optimization where a very minor change in the program can
10803 suddenly silently make a task non-optimizable.
10805 With the revisiting of this issue in Ada 95, there was general
10806 agreement that this approach was fundamentally flawed, and the
10807 notion of protected types was introduced. When using protected
10808 types, the restrictions are well defined, and you KNOW that the
10809 operations will be optimized, and furthermore this optimized
10810 performance is fully portable.
10812 Although it would theoretically be possible for GNAT to attempt to
10813 do this optimization, but it really doesn't make sense in the
10814 context of Ada 95, and none of the Ada 95 compilers implement
10815 this optimization as far as we know. In particular GNAT never
10816 attempts to perform this optimization.
10818 In any new Ada 95 code that is written, you should always
10819 use protected types in place of tasks that might be able to
10820 be optimized in this manner.
10821 Of course this does not help if you have legacy Ada 83 code
10822 that depends on this optimization, but it is unusual to encounter
10823 a case where the performance gains from this optimization
10824 are significant.
10826 Your program should work correctly without this optimization. If
10827 you have performance problems, then the most practical
10828 approach is to figure out exactly where these performance problems
10829 arise, and update those particular tasks to be protected types. Note
10830 that typically clients of the tasks who call entries, will not have
10831 to be modified, only the task definition itself.
10835 @node Text_IO Suggestions
10836 @section @code{Text_IO} Suggestions
10837 @cindex @code{Text_IO} and performance
10839 @noindent
10840 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10841 the requirement of maintaining page and line counts. If performance
10842 is critical, a recommendation is to use @code{Stream_IO} instead of
10843 @code{Text_IO} for volume output, since this package has less overhead.
10845 If @code{Text_IO} must be used, note that by default output to the standard
10846 output and standard error files is unbuffered (this provides better
10847 behavior when output statements are used for debugging, or if the
10848 progress of a program is observed by tracking the output, e.g. by
10849 using the Unix @command{tail -f} command to watch redirected output.
10851 If you are generating large volumes of output with @code{Text_IO} and
10852 performance is an important factor, use a designated file instead
10853 of the standard output file, or change the standard output file to
10854 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10857 @ifclear FSFEDITION
10858 @node Reducing Size of Ada Executables with gnatelim
10859 @section Reducing Size of Ada Executables with @code{gnatelim}
10860 @findex gnatelim
10862 @noindent
10863 This section describes @command{gnatelim}, a tool which detects unused
10864 subprograms and helps the compiler to create a smaller executable for your
10865 program.
10867 @menu
10868 * About gnatelim::
10869 * Running gnatelim::
10870 * Processing Precompiled Libraries::
10871 * Correcting the List of Eliminate Pragmas::
10872 * Making Your Executables Smaller::
10873 * Summary of the gnatelim Usage Cycle::
10874 @end menu
10876 @node About gnatelim
10877 @subsection About @code{gnatelim}
10879 @noindent
10880 When a program shares a set of Ada
10881 packages with other programs, it may happen that this program uses
10882 only a fraction of the subprograms defined in these packages. The code
10883 created for these unused subprograms increases the size of the executable.
10885 @code{gnatelim} tracks unused subprograms in an Ada program and
10886 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10887 subprograms that are declared but never called. By placing the list of
10888 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10889 recompiling your program, you may decrease the size of its executable,
10890 because the compiler will not generate the code for 'eliminated' subprograms.
10891 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10892 information about this pragma.
10894 @code{gnatelim} needs as its input data the name of the main subprogram.
10896 If a set of source files is specified as @code{gnatelim} arguments, it
10897 treats these files as a complete set of sources making up a program to
10898 analyse, and analyses only these sources.
10900 After a full successful build of the main subprogram @code{gnatelim} can be
10901 called without  specifying sources to analyse, in this case it computes
10902 the source closure of the main unit from the @file{ALI} files.
10904 If the set of sources to be processed by @code{gnatelim} contains sources with
10905 preprocessing directives
10906 then the needed options should be provided to run preprocessor as a part of
10907 the @command{gnatelim} call, and the generated set of pragmas @code{Eliminate}
10908 will correspond to preprocessed sources.
10910 The following command will create the set of @file{ALI} files needed for
10911 @code{gnatelim}:
10913 @smallexample
10914 $ gnatmake -c Main_Prog
10915 @end smallexample
10917 Note that @code{gnatelim} does not need object files.
10919 @node Running gnatelim
10920 @subsection Running @code{gnatelim}
10922 @noindent
10923 @code{gnatelim} has the following command-line interface:
10925 @smallexample
10926 $ gnatelim [@var{switches}] -main=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10927 @end smallexample
10929 @noindent
10930 @var{main_unit_name} should be a name of a source file that contains the main
10931 subprogram of a program (partition).
10933 Each @var{filename} is the name (including the extension) of a source
10934 file to process. ``Wildcards'' are allowed, and
10935 the file name may contain path information.
10937 @samp{@var{gcc_switches}} is a list of switches for
10938 @command{gcc}. They will be passed on to all compiler invocations made by
10939 @command{gnatelim} to generate the ASIS trees. Here you can provide
10940 @option{-I} switches to form the source search path,
10941 use the @option{-gnatec} switch to set the configuration file,
10942 use the @option{-gnat05} switch if sources should be compiled in
10943 Ada 2005 mode etc.
10945 @code{gnatelim} has the following switches:
10947 @table @option
10948 @c !sort!
10949 @item --version
10950 @cindex @option{--version} @command{gnatelim}
10951 Display Copyright and version, then exit disregarding all other options.
10953 @item --help
10954 @cindex @option{--help} @command{gnatelim}
10955 Display usage, then exit disregarding all other options.
10957 @item -P @var{file}
10958 @cindex @option{-P} @command{gnatelim}
10959 Indicates the name of the project file that describes the set of sources
10960 to be processed.
10962 @item -X@var{name}=@var{value}
10963 @cindex @option{-X} @command{gnatelim}
10964 Indicates that external variable @var{name} in the argument project
10965 has the value @var{value}. Has no effect if no project is specified as
10966 tool argument.
10968 @item --RTS=@var{rts-path}
10969 @cindex @option{--RTS} (@command{gnatelim})
10970 Specifies the default location of the runtime library. Same meaning as the
10971 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
10973 @item -files=@var{filename}
10974 @cindex @option{-files} (@code{gnatelim})
10975 Take the argument source files from the specified file. This file should be an
10976 ordinary text file containing file names separated by spaces or
10977 line breaks. You can use this switch more than once in the same call to
10978 @command{gnatelim}. You also can combine this switch with
10979 an explicit list of files.
10981 @item -log
10982 @cindex @option{-log} (@command{gnatelim})
10983 Duplicate all the output sent to @file{stderr} into a log file. The log file
10984 is named @file{gnatelim.log} and is located in the current directory.
10986 @ignore
10987 @item -log=@var{filename}
10988 @cindex @option{-log} (@command{gnatelim})
10989 Duplicate all the output sent to @file{stderr} into a specified log file.
10990 @end ignore
10992 @cindex @option{--no-elim-dispatch} (@command{gnatelim})
10993 @item --no-elim-dispatch
10994 Do not generate pragmas for dispatching operations.
10996 @item --ignore=@var{filename}
10997 @cindex @option{--ignore} (@command{gnatelim})
10998 Do not generate pragmas for subprograms declared in the sources
10999 listed in a specified file
11001 @cindex @option{-o} (@command{gnatelim})
11002 @item -o=@var{report_file}
11003 Put @command{gnatelim} output into a specified file. If this file already exists,
11004 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11005 into @file{stderr}
11007 @item -j@var{n}
11008 @cindex @option{-j} (@command{gnatelim})
11009 Use @var{n} processes to carry out the tree creations (internal representations
11010 of the argument sources). On a multiprocessor machine this speeds up processing
11011 of big sets of argument sources. If @var{n} is 0, then the maximum number of
11012 parallel tree creations is the number of core processors on the platform.
11014 @item -q
11015 @cindex @option{-q} (@command{gnatelim})
11016 Quiet mode: by default @code{gnatelim} outputs to the standard error
11017 stream the number of program units left to be processed. This option turns
11018 this trace off.
11020 @cindex @option{-t} (@command{gnatelim})
11021 @item -t
11022 Print out execution time.
11024 @item -v
11025 @cindex @option{-v} (@command{gnatelim})
11026 Verbose mode: @code{gnatelim} version information is printed as Ada
11027 comments to the standard output stream. Also, in addition to the number of
11028 program units left @code{gnatelim} will output the name of the current unit
11029 being processed.
11031 @item -wq
11032 @cindex @option{-wq} (@command{gnatelim})
11033 Quiet warning mode - some warnings are suppressed. In particular warnings that
11034 indicate that the analysed set of sources is incomplete to make up a
11035 partition and that some subprogram bodies are missing are not generated.
11036 @end table
11038 @noindent
11039 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11040 driver (see @ref{The GNAT Driver and Project Files}).
11042 @node Processing Precompiled Libraries
11043 @subsection Processing Precompiled Libraries
11045 @noindent
11046 If some program uses a precompiled Ada library, it can be processed by
11047 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11048 Eliminate pragma for a subprogram if the body of this subprogram has not
11049 been analysed, this is a typical case for subprograms from precompiled
11050 libraries. Switch @option{-wq} may be used to suppress
11051 warnings about missing source files and non-analyzed subprogram bodies
11052 that can be generated when processing precompiled Ada libraries.
11054 @node Correcting the List of Eliminate Pragmas
11055 @subsection Correcting the List of Eliminate Pragmas
11057 @noindent
11058 In some rare cases @code{gnatelim} may try to eliminate
11059 subprograms that are actually called in the program. In this case, the
11060 compiler will generate an error message of the form:
11062 @smallexample
11063 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11064 @end smallexample
11066 @noindent
11067 You will need to manually remove the wrong @code{Eliminate} pragmas from
11068 the configuration file indicated in the error message. You should recompile
11069 your program from scratch after that, because you need a consistent
11070 configuration file(s) during the entire compilation.
11072 @node Making Your Executables Smaller
11073 @subsection Making Your Executables Smaller
11075 @noindent
11076 In order to get a smaller executable for your program you now have to
11077 recompile the program completely with the configuration file containing
11078 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11079 @file{gnat.adc} file located in your current directory, just do:
11081 @smallexample
11082 $ gnatmake -f main_prog
11083 @end smallexample
11085 @noindent
11086 (Use the @option{-f} option for @command{gnatmake} to
11087 recompile everything
11088 with the set of pragmas @code{Eliminate} that you have obtained with
11089 @command{gnatelim}).
11091 Be aware that the set of @code{Eliminate} pragmas is specific to each
11092 program. It is not recommended to merge sets of @code{Eliminate}
11093 pragmas created for different programs in one configuration file.
11095 @node Summary of the gnatelim Usage Cycle
11096 @subsection Summary of the @code{gnatelim} Usage Cycle
11098 @noindent
11099 Here is a quick summary of the steps to be taken in order to reduce
11100 the size of your executables with @code{gnatelim}. You may use
11101 other GNAT options to control the optimization level,
11102 to produce the debugging information, to set search path, etc.
11104 @enumerate
11105 @item
11106 Create a complete set of @file{ALI} files (if the program has not been
11107 built already)
11109 @smallexample
11110 $ gnatmake -c main_prog
11111 @end smallexample
11113 @item
11114 Generate a list of @code{Eliminate} pragmas in default configuration file
11115 @file{gnat.adc} in the current directory
11116 @smallexample
11117 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11118 @end smallexample
11120 @item
11121 Recompile the application
11123 @smallexample
11124 $ gnatmake -f main_prog
11125 @end smallexample
11127 @end enumerate
11128 @end ifclear
11130 @node Reducing Size of Executables with unused subprogram/data elimination
11131 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11132 @findex unused subprogram/data elimination
11134 @noindent
11135 This section describes how you can eliminate unused subprograms and data from
11136 your executable just by setting options at compilation time.
11138 @menu
11139 * About unused subprogram/data elimination::
11140 * Compilation options::
11141 * Example of unused subprogram/data elimination::
11142 @end menu
11144 @node About unused subprogram/data elimination
11145 @subsection About unused subprogram/data elimination
11147 @noindent
11148 By default, an executable contains all code and data of its composing objects
11149 (directly linked or coming from statically linked libraries), even data or code
11150 never used by this executable.
11152 This feature will allow you to eliminate such unused code from your
11153 executable, making it smaller (in disk and in memory).
11155 This functionality is available on all Linux platforms except for the IA-64
11156 architecture and on all cross platforms using the ELF binary file format.
11157 In both cases GNU binutils version 2.16 or later are required to enable it.
11159 @node Compilation options
11160 @subsection Compilation options
11162 @noindent
11163 The operation of eliminating the unused code and data from the final executable
11164 is directly performed by the linker.
11166 In order to do this, it has to work with objects compiled with the
11167 following options:
11168 @option{-ffunction-sections} @option{-fdata-sections}.
11169 @cindex @option{-ffunction-sections} (@command{gcc})
11170 @cindex @option{-fdata-sections} (@command{gcc})
11171 These options are usable with C and Ada files.
11172 They will place respectively each
11173 function or data in a separate section in the resulting object file.
11175 Once the objects and static libraries are created with these options, the
11176 linker can perform the dead code elimination. You can do this by setting
11177 the @option{-Wl,--gc-sections} option to gcc command or in the
11178 @option{-largs} section of @command{gnatmake}. This will perform a
11179 garbage collection of code and data never referenced.
11181 If the linker performs a partial link (@option{-r} linker option), then you
11182 will need to provide the entry point using the @option{-e} / @option{--entry}
11183 linker option.
11185 Note that objects compiled without the @option{-ffunction-sections} and
11186 @option{-fdata-sections} options can still be linked with the executable.
11187 However, no dead code elimination will be performed on those objects (they will
11188 be linked as is).
11190 The GNAT static library is now compiled with -ffunction-sections and
11191 -fdata-sections on some platforms. This allows you to eliminate the unused code
11192 and data of the GNAT library from your executable.
11194 @node Example of unused subprogram/data elimination
11195 @subsection Example of unused subprogram/data elimination
11197 @noindent
11198 Here is a simple example:
11200 @smallexample @c ada
11201 @b{with} Aux;
11203 @b{procedure} Test @b{is}
11204 @b{begin}
11205    Aux.Used (10);
11206 @b{end} Test;
11208 @b{package} Aux @b{is}
11209    Used_Data   : Integer;
11210    Unused_Data : Integer;
11212    @b{procedure} Used   (Data : Integer);
11213    @b{procedure} Unused (Data : Integer);
11214 @b{end} Aux;
11216 @b{package} @b{body} Aux @b{is}
11217    @b{procedure} Used (Data : Integer) @b{is}
11218    @b{begin}
11219       Used_Data := Data;
11220    @b{end} Used;
11222    @b{procedure} Unused (Data : Integer) @b{is}
11223    @b{begin}
11224       Unused_Data := Data;
11225    @b{end} Unused;
11226 @b{end} Aux;
11227 @end smallexample
11229 @noindent
11230 @code{Unused} and @code{Unused_Data} are never referenced in this code
11231 excerpt, and hence they may be safely removed from the final executable.
11233 @smallexample
11234 $ gnatmake test
11236 $ nm test | grep used
11237 020015f0 T aux__unused
11238 02005d88 B aux__unused_data
11239 020015cc T aux__used
11240 02005d84 B aux__used_data
11242 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11243      -largs -Wl,--gc-sections
11245 $ nm test | grep used
11246 02005350 T aux__used
11247 0201ffe0 B aux__used_data
11248 @end smallexample
11250 @noindent
11251 It can be observed that the procedure @code{Unused} and the object
11252 @code{Unused_Data} are removed by the linker when using the
11253 appropriate options.
11255 @c ********************************
11256 @node Renaming Files with gnatchop
11257 @chapter Renaming Files with @code{gnatchop}
11258 @findex gnatchop
11260 @noindent
11261 This chapter discusses how to handle files with multiple units by using
11262 the @code{gnatchop} utility. This utility is also useful in renaming
11263 files to meet the standard GNAT default file naming conventions.
11265 @menu
11266 * Handling Files with Multiple Units::
11267 * Operating gnatchop in Compilation Mode::
11268 * Command Line for gnatchop::
11269 * Switches for gnatchop::
11270 * Examples of gnatchop Usage::
11271 @end menu
11273 @node Handling Files with Multiple Units
11274 @section Handling Files with Multiple Units
11276 @noindent
11277 The basic compilation model of GNAT requires that a file submitted to the
11278 compiler have only one unit and there be a strict correspondence
11279 between the file name and the unit name.
11281 The @code{gnatchop} utility allows both of these rules to be relaxed,
11282 allowing GNAT to process files which contain multiple compilation units
11283 and files with arbitrary file names. @code{gnatchop}
11284 reads the specified file and generates one or more output files,
11285 containing one unit per file. The unit and the file name correspond,
11286 as required by GNAT.
11288 If you want to permanently restructure a set of ``foreign'' files so that
11289 they match the GNAT rules, and do the remaining development using the
11290 GNAT structure, you can simply use @command{gnatchop} once, generate the
11291 new set of files and work with them from that point on.
11293 Alternatively, if you want to keep your files in the ``foreign'' format,
11294 perhaps to maintain compatibility with some other Ada compilation
11295 system, you can set up a procedure where you use @command{gnatchop} each
11296 time you compile, regarding the source files that it writes as temporary
11297 files that you throw away.
11299 Note that if your file containing multiple units starts with a byte order
11300 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11301 will each start with a copy of this BOM, meaning that they can be compiled
11302 automatically in UTF-8 mode without needing to specify an explicit encoding.
11304 @node Operating gnatchop in Compilation Mode
11305 @section Operating gnatchop in Compilation Mode
11307 @noindent
11308 The basic function of @code{gnatchop} is to take a file with multiple units
11309 and split it into separate files. The boundary between files is reasonably
11310 clear, except for the issue of comments and pragmas. In default mode, the
11311 rule is that any pragmas between units belong to the previous unit, except
11312 that configuration pragmas always belong to the following unit. Any comments
11313 belong to the following unit. These rules
11314 almost always result in the right choice of
11315 the split point without needing to mark it explicitly and most users will
11316 find this default to be what they want. In this default mode it is incorrect to
11317 submit a file containing only configuration pragmas, or one that ends in
11318 configuration pragmas, to @code{gnatchop}.
11320 However, using a special option to activate ``compilation mode'',
11321 @code{gnatchop}
11322 can perform another function, which is to provide exactly the semantics
11323 required by the RM for handling of configuration pragmas in a compilation.
11324 In the absence of configuration pragmas (at the main file level), this
11325 option has no effect, but it causes such configuration pragmas to be handled
11326 in a quite different manner.
11328 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11329 only configuration pragmas, then this file is appended to the
11330 @file{gnat.adc} file in the current directory. This behavior provides
11331 the required behavior described in the RM for the actions to be taken
11332 on submitting such a file to the compiler, namely that these pragmas
11333 should apply to all subsequent compilations in the same compilation
11334 environment. Using GNAT, the current directory, possibly containing a
11335 @file{gnat.adc} file is the representation
11336 of a compilation environment. For more information on the
11337 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11339 Second, in compilation mode, if @code{gnatchop}
11340 is given a file that starts with
11341 configuration pragmas, and contains one or more units, then these
11342 configuration pragmas are prepended to each of the chopped files. This
11343 behavior provides the required behavior described in the RM for the
11344 actions to be taken on compiling such a file, namely that the pragmas
11345 apply to all units in the compilation, but not to subsequently compiled
11346 units.
11348 Finally, if configuration pragmas appear between units, they are appended
11349 to the previous unit. This results in the previous unit being illegal,
11350 since the compiler does not accept configuration pragmas that follow
11351 a unit. This provides the required RM behavior that forbids configuration
11352 pragmas other than those preceding the first compilation unit of a
11353 compilation.
11355 For most purposes, @code{gnatchop} will be used in default mode. The
11356 compilation mode described above is used only if you need exactly
11357 accurate behavior with respect to compilations, and you have files
11358 that contain multiple units and configuration pragmas. In this
11359 circumstance the use of @code{gnatchop} with the compilation mode
11360 switch provides the required behavior, and is for example the mode
11361 in which GNAT processes the ACVC tests.
11363 @node Command Line for gnatchop
11364 @section Command Line for @code{gnatchop}
11366 @noindent
11367 The @code{gnatchop} command has the form:
11369 @smallexample
11370 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11371 @c      @ovar{directory}
11372 @c Expanding @ovar macro inline (explanation in macro def comments)
11373 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11374       @r{[}@var{directory}@r{]}
11375 @end smallexample
11377 @noindent
11378 The only required argument is the file name of the file to be chopped.
11379 There are no restrictions on the form of this file name. The file itself
11380 contains one or more Ada units, in normal GNAT format, concatenated
11381 together. As shown, more than one file may be presented to be chopped.
11383 When run in default mode, @code{gnatchop} generates one output file in
11384 the current directory for each unit in each of the files.
11386 @var{directory}, if specified, gives the name of the directory to which
11387 the output files will be written. If it is not specified, all files are
11388 written to the current directory.
11390 For example, given a
11391 file called @file{hellofiles} containing
11393 @smallexample @c ada
11394 @group
11395 @cartouche
11396 @b{procedure} hello;
11398 @b{with} Text_IO; @b{use} Text_IO;
11399 @b{procedure} hello @b{is}
11400 @b{begin}
11401    Put_Line ("Hello");
11402 @b{end} hello;
11403 @end cartouche
11404 @end group
11405 @end smallexample
11407 @noindent
11408 the command
11410 @smallexample
11411 $ gnatchop hellofiles
11412 @end smallexample
11414 @noindent
11415 generates two files in the current directory, one called
11416 @file{hello.ads} containing the single line that is the procedure spec,
11417 and the other called @file{hello.adb} containing the remaining text. The
11418 original file is not affected. The generated files can be compiled in
11419 the normal manner.
11421 @noindent
11422 When gnatchop is invoked on a file that is empty or that contains only empty
11423 lines and/or comments, gnatchop will not fail, but will not produce any
11424 new sources.
11426 For example, given a
11427 file called @file{toto.txt} containing
11429 @smallexample @c ada
11430 @group
11431 @cartouche
11432 --@i{  Just a comment}
11433 @end cartouche
11434 @end group
11435 @end smallexample
11437 @noindent
11438 the command
11440 @smallexample
11441 $ gnatchop toto.txt
11442 @end smallexample
11444 @noindent
11445 will not produce any new file and will result in the following warnings:
11447 @smallexample
11448 toto.txt:1:01: warning: empty file, contains no compilation units
11449 no compilation units found
11450 no source files written
11451 @end smallexample
11453 @node Switches for gnatchop
11454 @section Switches for @code{gnatchop}
11456 @noindent
11457 @command{gnatchop} recognizes the following switches:
11459 @table @option
11460 @c !sort!
11462 @item --version
11463 @cindex @option{--version} @command{gnatchop}
11464 Display Copyright and version, then exit disregarding all other options.
11466 @item --help
11467 @cindex @option{--help} @command{gnatchop}
11468 If @option{--version} was not used, display usage, then exit disregarding
11469 all other options.
11471 @item -c
11472 @cindex @option{-c} (@code{gnatchop})
11473 Causes @code{gnatchop} to operate in compilation mode, in which
11474 configuration pragmas are handled according to strict RM rules. See
11475 previous section for a full description of this mode.
11477 @item -gnat@var{xxx}
11478 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11479 used to parse the given file. Not all @var{xxx} options make sense,
11480 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11481 process a source file that uses Latin-2 coding for identifiers.
11483 @item -h
11484 Causes @code{gnatchop} to generate a brief help summary to the standard
11485 output file showing usage information.
11487 @item -k@var{mm}
11488 @cindex @option{-k} (@code{gnatchop})
11489 Limit generated file names to the specified number @code{mm}
11490 of characters.
11491 This is useful if the
11492 resulting set of files is required to be interoperable with systems
11493 which limit the length of file names.
11494 No space is allowed between the @option{-k} and the numeric value. The numeric
11495 value may be omitted in which case a default of @option{-k8},
11496 suitable for use
11497 with DOS-like file systems, is used. If no @option{-k} switch
11498 is present then
11499 there is no limit on the length of file names.
11501 @item -p
11502 @cindex @option{-p} (@code{gnatchop})
11503 Causes the file modification time stamp of the input file to be
11504 preserved and used for the time stamp of the output file(s). This may be
11505 useful for preserving coherency of time stamps in an environment where
11506 @code{gnatchop} is used as part of a standard build process.
11508 @item -q
11509 @cindex @option{-q} (@code{gnatchop})
11510 Causes output of informational messages indicating the set of generated
11511 files to be suppressed. Warnings and error messages are unaffected.
11513 @item -r
11514 @cindex @option{-r} (@code{gnatchop})
11515 @findex Source_Reference
11516 Generate @code{Source_Reference} pragmas. Use this switch if the output
11517 files are regarded as temporary and development is to be done in terms
11518 of the original unchopped file. This switch causes
11519 @code{Source_Reference} pragmas to be inserted into each of the
11520 generated files to refers back to the original file name and line number.
11521 The result is that all error messages refer back to the original
11522 unchopped file.
11523 In addition, the debugging information placed into the object file (when
11524 the @option{-g} switch of @command{gcc} or @command{gnatmake} is
11525 specified)
11526 also refers back to this original file so that tools like profilers and
11527 debuggers will give information in terms of the original unchopped file.
11529 If the original file to be chopped itself contains
11530 a @code{Source_Reference}
11531 pragma referencing a third file, then gnatchop respects
11532 this pragma, and the generated @code{Source_Reference} pragmas
11533 in the chopped file refer to the original file, with appropriate
11534 line numbers. This is particularly useful when @code{gnatchop}
11535 is used in conjunction with @code{gnatprep} to compile files that
11536 contain preprocessing statements and multiple units.
11538 @item -v
11539 @cindex @option{-v} (@code{gnatchop})
11540 Causes @code{gnatchop} to operate in verbose mode. The version
11541 number and copyright notice are output, as well as exact copies of
11542 the gnat1 commands spawned to obtain the chop control information.
11544 @item -w
11545 @cindex @option{-w} (@code{gnatchop})
11546 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11547 fatal error if there is already a file with the same name as a
11548 file it would otherwise output, in other words if the files to be
11549 chopped contain duplicated units. This switch bypasses this
11550 check, and causes all but the last instance of such duplicated
11551 units to be skipped.
11553 @item --GCC=@var{xxxx}
11554 @cindex @option{--GCC=} (@code{gnatchop})
11555 Specify the path of the GNAT parser to be used. When this switch is used,
11556 no attempt is made to add the prefix to the GNAT parser executable.
11557 @end table
11559 @node Examples of gnatchop Usage
11560 @section Examples of @code{gnatchop} Usage
11562 @table @code
11563 @item gnatchop -w hello_s.ada prerelease/files
11565 Chops the source file @file{hello_s.ada}. The output files will be
11566 placed in the directory @file{prerelease/files},
11567 overwriting any
11568 files with matching names in that directory (no files in the current
11569 directory are modified).
11571 @item gnatchop archive
11572 Chops the source file @file{archive}
11573 into the current directory. One
11574 useful application of @code{gnatchop} is in sending sets of sources
11575 around, for example in email messages. The required sources are simply
11576 concatenated (for example, using a Unix @code{cat}
11577 command), and then
11578 @command{gnatchop} is used at the other end to reconstitute the original
11579 file names.
11581 @item gnatchop file1 file2 file3 direc
11582 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11583 the resulting files in the directory @file{direc}. Note that if any units
11584 occur more than once anywhere within this set of files, an error message
11585 is generated, and no files are written. To override this check, use the
11586 @option{-w} switch,
11587 in which case the last occurrence in the last file will
11588 be the one that is output, and earlier duplicate occurrences for a given
11589 unit will be skipped.
11590 @end table
11592 @node Configuration Pragmas
11593 @chapter Configuration Pragmas
11594 @cindex Configuration pragmas
11595 @cindex Pragmas, configuration
11597 @menu
11598 * Handling of Configuration Pragmas::
11599 * The Configuration Pragmas Files::
11600 @end menu
11602 @noindent
11603 Configuration pragmas include those pragmas described as
11604 such in the Ada Reference Manual, as well as
11605 implementation-dependent pragmas that are configuration pragmas.
11606 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11607 for details on these additional GNAT-specific configuration pragmas.
11608 Most notably, the pragma @code{Source_File_Name}, which allows
11609 specifying non-default names for source files, is a configuration
11610 pragma. The following is a complete list of configuration pragmas
11611 recognized by GNAT:
11613 @smallexample
11614    Ada_83
11615    Ada_95
11616    Ada_05
11617    Ada_2005
11618    Ada_12
11619    Ada_2012
11620    Allow_Integer_Address
11621    Annotate
11622    Assertion_Policy
11623    Assume_No_Invalid_Values
11624    C_Pass_By_Copy
11625    Check_Name
11626    Check_Policy
11627    Compile_Time_Error
11628    Compile_Time_Warning
11629    Compiler_Unit
11630    Component_Alignment
11631    Convention_Identifier
11632    Debug_Policy
11633    Detect_Blocking
11634    Default_Storage_Pool
11635    Discard_Names
11636    Elaboration_Checks
11637    Eliminate
11638    Extend_System
11639    Extensions_Allowed
11640    External_Name_Casing
11641    Fast_Math
11642    Favor_Top_Level
11643    Float_Representation
11644    Implicit_Packing
11645    Initialize_Scalars
11646    Interrupt_State
11647    License
11648    Locking_Policy
11649    Long_Float
11650    No_Run_Time
11651    No_Strict_Aliasing
11652    Normalize_Scalars
11653    Optimize_Alignment
11654    Persistent_BSS
11655    Polling
11656    Priority_Specific_Dispatching
11657    Profile
11658    Profile_Warnings
11659    Propagate_Exceptions
11660    Queuing_Policy
11661    Ravenscar
11662    Restricted_Run_Time
11663    Restrictions
11664    Restrictions_Warnings
11665    Reviewable
11666    Short_Circuit_And_Or
11667    Source_File_Name
11668    Source_File_Name_Project
11669    SPARK_Mode
11670    Style_Checks
11671    Suppress
11672    Suppress_Exception_Locations
11673    Task_Dispatching_Policy
11674    Universal_Data
11675    Unsuppress
11676    Use_VADS_Size
11677    Validity_Checks
11678    Warnings
11679    Wide_Character_Encoding
11680 @end smallexample
11682 @node Handling of Configuration Pragmas
11683 @section Handling of Configuration Pragmas
11685 Configuration pragmas may either appear at the start of a compilation
11686 unit, or they can appear in a configuration pragma file to apply to
11687 all compilations performed in a given compilation environment.
11689 GNAT also provides the @code{gnatchop} utility to provide an automatic
11690 way to handle configuration pragmas following the semantics for
11691 compilations (that is, files with multiple units), described in the RM.
11692 See @ref{Operating gnatchop in Compilation Mode} for details.
11693 However, for most purposes, it will be more convenient to edit the
11694 @file{gnat.adc} file that contains configuration pragmas directly,
11695 as described in the following section.
11697 In the case of @code{Restrictions} pragmas appearing as configuration
11698 pragmas in individual compilation units, the exact handling depends on
11699 the type of restriction.
11701 Restrictions that require partition-wide consistency (like
11702 @code{No_Tasking}) are
11703 recognized wherever they appear
11704 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11705 unit. This makes sense since the binder will in any case insist on seeing
11706 consistent use, so any unit not conforming to any restrictions that are
11707 anywhere in the partition will be rejected, and you might as well find
11708 that out at compile time rather than at bind time.
11710 For restrictions that do not require partition-wide consistency, e.g.
11711 SPARK or No_Implementation_Attributes, in general the restriction applies
11712 only to the unit in which the pragma appears, and not to any other units.
11714 The exception is No_Elaboration_Code which always applies to the entire
11715 object file from a compilation, i.e. to the body, spec, and all subunits.
11716 This restriction can be specified in a configuration pragma file, or it
11717 can be on the body and/or the spec (in eithe case it applies to all the
11718 relevant units). It can appear on a subunit only if it has previously
11719 appeared in the body of spec.
11721 @node The Configuration Pragmas Files
11722 @section The Configuration Pragmas Files
11723 @cindex @file{gnat.adc}
11725 @noindent
11726 In GNAT a compilation environment is defined by the current
11727 directory at the time that a compile command is given. This current
11728 directory is searched for a file whose name is @file{gnat.adc}. If
11729 this file is present, it is expected to contain one or more
11730 configuration pragmas that will be applied to the current compilation.
11731 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11732 considered. When taken into account, @file{gnat.adc} is added to the
11733 dependencies, so that if @file{gnat.adc} is modified later, an invocation of
11734 @command{gnatmake} will recompile the source.
11736 Configuration pragmas may be entered into the @file{gnat.adc} file
11737 either by running @code{gnatchop} on a source file that consists only of
11738 configuration pragmas, or more conveniently by direct editing of the
11739 @file{gnat.adc} file, which is a standard format source file.
11741 In addition to @file{gnat.adc}, additional files containing configuration
11742 pragmas may be applied to the current compilation using the switch
11743 @option{-gnatec=}@var{path}. @var{path} must designate an existing file that
11744 contains only configuration pragmas. These configuration pragmas are
11745 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11746 is present and switch @option{-gnatA} is not used).
11748 It is allowable to specify several switches @option{-gnatec=}, all of which
11749 will be taken into account.
11751 Files containing configuration pragmas specified with switches
11752 @option{-gnatec=} are added to the dependencies, unless they are
11753 temporary files. A file is considered temporary if its name ends in
11754 @file{.tmp} or @file{.TMP}. Certain tools follow this naming
11755 convention because they pass information to @command{gcc} via
11756 temporary files that are immediately deleted; it doesn't make sense to
11757 depend on a file that no longer exists. Such tools include
11758 @command{gprbuild}, @command{gnatmake}, and @command{gnatcheck}.
11760 If you are using project file, a separate mechanism is provided using
11761 project attributes, see @ref{Specifying Configuration Pragmas} for more
11762 details.
11765 @node Handling Arbitrary File Naming Conventions with gnatname
11766 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
11767 @cindex Arbitrary File Naming Conventions
11769 @menu
11770 * Arbitrary File Naming Conventions::
11771 * Running gnatname::
11772 * Switches for gnatname::
11773 * Examples of gnatname Usage::
11774 @end menu
11776 @node Arbitrary File Naming Conventions
11777 @section Arbitrary File Naming Conventions
11779 @noindent
11780 The GNAT compiler must be able to know the source file name of a compilation
11781 unit.  When using the standard GNAT default file naming conventions
11782 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11783 does not need additional information.
11785 @noindent
11786 When the source file names do not follow the standard GNAT default file naming
11787 conventions, the GNAT compiler must be given additional information through
11788 a configuration pragmas file (@pxref{Configuration Pragmas})
11789 or a project file.
11790 When the non-standard file naming conventions are well-defined,
11791 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11792 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11793 if the file naming conventions are irregular or arbitrary, a number
11794 of pragma @code{Source_File_Name} for individual compilation units
11795 must be defined.
11796 To help maintain the correspondence between compilation unit names and
11797 source file names within the compiler,
11798 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11799 set of files.
11801 @node Running gnatname
11802 @section Running @code{gnatname}
11804 @noindent
11805 The usual form of the @code{gnatname} command is
11807 @smallexample
11808 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11809 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11810 @c Expanding @ovar macro inline (explanation in macro def comments)
11811 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11812       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11813 @end smallexample
11815 @noindent
11816 All of the arguments are optional. If invoked without any argument,
11817 @code{gnatname} will display its usage.
11819 @noindent
11820 When used with at least one naming pattern, @code{gnatname} will attempt to
11821 find all the compilation units in files that follow at least one of the
11822 naming patterns. To find these compilation units,
11823 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11824 regular files.
11826 @noindent
11827 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11828 Each Naming Pattern is enclosed between double quotes (or single
11829 quotes on Windows).
11830 A Naming Pattern is a regular expression similar to the wildcard patterns
11831 used in file names by the Unix shells or the DOS prompt.
11833 @noindent
11834 @code{gnatname} may be called with several sections of directories/patterns.
11835 Sections are separated by switch @code{--and}. In each section, there must be
11836 at least one pattern. If no directory is specified in a section, the current
11837 directory (or the project directory is @code{-P} is used) is implied.
11838 The options other that the directory switches and the patterns apply globally
11839 even if they are in different sections.
11841 @noindent
11842 Examples of Naming Patterns are
11844 @smallexample
11845    "*.[12].ada"
11846    "*.ad[sb]*"
11847    "body_*"    "spec_*"
11848 @end smallexample
11850 @noindent
11851 For a more complete description of the syntax of Naming Patterns,
11852 see the second kind of regular expressions described in @file{g-regexp.ads}
11853 (the ``Glob'' regular expressions).
11855 @noindent
11856 When invoked with no switch @code{-P}, @code{gnatname} will create a
11857 configuration pragmas file @file{gnat.adc} in the current working directory,
11858 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11859 unit.
11861 @node Switches for gnatname
11862 @section Switches for @code{gnatname}
11864 @noindent
11865 Switches for @code{gnatname} must precede any specified Naming Pattern.
11867 @noindent
11868 You may specify any of the following switches to @code{gnatname}:
11870 @table @option
11871 @c !sort!
11873 @item --version
11874 @cindex @option{--version} @command{gnatname}
11875 Display Copyright and version, then exit disregarding all other options.
11877 @item --help
11878 @cindex @option{--help} @command{gnatname}
11879 If @option{--version} was not used, display usage, then exit disregarding
11880 all other options.
11882 @item --subdirs=<dir>
11883 Real object, library or exec directories are subdirectories <dir> of the
11884 specified ones.
11886 @item --no-backup
11887 Do not create a backup copy of an existing project file.
11889 @item --and
11890 Start another section of directories/patterns.
11892 @item -c@file{file}
11893 @cindex @option{-c} (@code{gnatname})
11894 Create a configuration pragmas file @file{file} (instead of the default
11895 @file{gnat.adc}).
11896 There may be zero, one or more space between @option{-c} and
11897 @file{file}.
11898 @file{file} may include directory information. @file{file} must be
11899 writable. There may be only one switch @option{-c}.
11900 When a switch @option{-c} is
11901 specified, no switch @option{-P} may be specified (see below).
11903 @item -d@file{dir}
11904 @cindex @option{-d} (@code{gnatname})
11905 Look for source files in directory @file{dir}. There may be zero, one or more
11906 spaces between @option{-d} and @file{dir}.
11907 @file{dir} may end with @code{/**}, that is it may be of the form
11908 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
11909 subdirectories, recursively, have to be searched for sources.
11910 When a switch @option{-d}
11911 is specified, the current working directory will not be searched for source
11912 files, unless it is explicitly specified with a @option{-d}
11913 or @option{-D} switch.
11914 Several switches @option{-d} may be specified.
11915 If @file{dir} is a relative path, it is relative to the directory of
11916 the configuration pragmas file specified with switch
11917 @option{-c},
11918 or to the directory of the project file specified with switch
11919 @option{-P} or,
11920 if neither switch @option{-c}
11921 nor switch @option{-P} are specified, it is relative to the
11922 current working directory. The directory
11923 specified with switch @option{-d} must exist and be readable.
11925 @item -D@file{file}
11926 @cindex @option{-D} (@code{gnatname})
11927 Look for source files in all directories listed in text file @file{file}.
11928 There may be zero, one or more spaces between @option{-D}
11929 and @file{file}.
11930 @file{file} must be an existing, readable text file.
11931 Each nonempty line in @file{file} must be a directory.
11932 Specifying switch @option{-D} is equivalent to specifying as many
11933 switches @option{-d} as there are nonempty lines in
11934 @file{file}.
11936 @item -eL
11937 Follow symbolic links when processing project files.
11939 @item -f@file{pattern}
11940 @cindex @option{-f} (@code{gnatname})
11941 Foreign patterns. Using this switch, it is possible to add sources of languages
11942 other than Ada to the list of sources of a project file.
11943 It is only useful if a -P switch is used.
11944 For example,
11945 @smallexample
11946 gnatname -Pprj -f"*.c" "*.ada"
11947 @end smallexample
11948 @noindent
11949 will look for Ada units in all files with the @file{.ada} extension,
11950 and will add to the list of file for project @file{prj.gpr} the C files
11951 with extension @file{.c}.
11953 @item -h
11954 @cindex @option{-h} (@code{gnatname})
11955 Output usage (help) information. The output is written to @file{stdout}.
11957 @item -P@file{proj}
11958 @cindex @option{-P} (@code{gnatname})
11959 Create or update project file @file{proj}. There may be zero, one or more space
11960 between @option{-P} and @file{proj}. @file{proj} may include directory
11961 information. @file{proj} must be writable.
11962 There may be only one switch @option{-P}.
11963 When a switch @option{-P} is specified,
11964 no switch @option{-c} may be specified.
11965 On all platforms, except on VMS, when @code{gnatname} is invoked for an
11966 existing project file <proj>.gpr, a backup copy of the project file is created
11967 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
11968 non negative number that makes this backup copy a new file.
11970 @item -v
11971 @cindex @option{-v} (@code{gnatname})
11972 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11973 This includes name of the file written, the name of the directories to search
11974 and, for each file in those directories whose name matches at least one of
11975 the Naming Patterns, an indication of whether the file contains a unit,
11976 and if so the name of the unit.
11978 @item -v -v
11979 @cindex @option{-v -v} (@code{gnatname})
11980 Very Verbose mode. In addition to the output produced in verbose mode,
11981 for each file in the searched directories whose name matches none of
11982 the Naming Patterns, an indication is given that there is no match.
11984 @item -x@file{pattern}
11985 @cindex @option{-x} (@code{gnatname})
11986 Excluded patterns. Using this switch, it is possible to exclude some files
11987 that would match the name patterns. For example,
11988 @smallexample
11989 gnatname -x "*_nt.ada" "*.ada"
11990 @end smallexample
11991 @noindent
11992 will look for Ada units in all files with the @file{.ada} extension,
11993 except those whose names end with @file{_nt.ada}.
11995 @end table
11997 @node Examples of gnatname Usage
11998 @section Examples of @code{gnatname} Usage
12001 @smallexample
12002 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12003 @end smallexample
12005 @noindent
12006 In this example, the directory @file{/home/me} must already exist
12007 and be writable. In addition, the directory
12008 @file{/home/me/sources} (specified by
12009 @option{-d sources}) must exist and be readable.
12011 Note the optional spaces after @option{-c} and @option{-d}.
12013 @smallexample
12014 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12015   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12016 @end smallexample
12018 Note that several switches @option{-d} may be used,
12019 even in conjunction with one or several switches
12020 @option{-D}. Several Naming Patterns and one excluded pattern
12021 are used in this example.
12023 @c *****************************************
12024 @c * G N A T  P r o j e c t  M a n a g e r *
12025 @c *****************************************
12027 @c ------ macros for projects.texi
12028 @c These macros are needed when building the gprbuild documentation, but
12029 @c should have no effect in the gnat user's guide
12031 @macro CODESAMPLE{TXT}
12032 @smallexample
12033 @group
12034 \TXT\
12035 @end group
12036 @end smallexample
12037 @end macro
12039 @macro PROJECTFILE{TXT}
12040 @CODESAMPLE{\TXT\}
12041 @end macro
12043 @c simulates a newline when in a @CODESAMPLE
12044 @macro NL{}
12045 @end macro
12047 @macro TIP{TXT}
12048 @quotation
12049 @noindent
12050 \TXT\
12051 @end quotation
12052 @end macro
12054 @macro TIPHTML{TXT}
12055 \TXT\
12056 @end macro
12058 @macro IMPORTANT{TXT}
12059 @quotation
12060 @noindent
12061 \TXT\
12062 @end quotation
12064 @end macro
12066 @macro NOTE{TXT}
12067 @quotation
12068 @noindent
12069 \TXT\
12070 @end quotation
12071 @end macro
12073 @include projects.texi
12075 @c ---------------------------------------------
12076 @c Tools Supporting Project Files
12077 @c ---------------------------------------------
12079 @node Tools Supporting Project Files
12080 @chapter Tools Supporting Project Files
12082 @noindent
12084 @menu
12085 * gnatmake and Project Files::
12086 * The GNAT Driver and Project Files::
12087 @end menu
12089 @c ---------------------------------------------
12090 @node gnatmake and Project Files
12091 @section gnatmake and Project Files
12092 @c ---------------------------------------------
12094 @noindent
12095 This section covers several topics related to @command{gnatmake} and
12096 project files: defining switches for @command{gnatmake}
12097 and for the tools that it invokes; specifying configuration pragmas;
12098 the use of the @code{Main} attribute; building and rebuilding library project
12099 files.
12101 @menu
12102 * Switches Related to Project Files::
12103 * Switches and Project Files::
12104 * Specifying Configuration Pragmas::
12105 * Project Files and Main Subprograms::
12106 * Library Project Files::
12107 @end menu
12109 @c ---------------------------------------------
12110 @node Switches Related to Project Files
12111 @subsection Switches Related to Project Files
12112 @c ---------------------------------------------
12114 @noindent
12115 The following switches are used by GNAT tools that support project files:
12117 @table @option
12119 @item -P@var{project}
12120 @cindex @option{-P} (any project-aware tool)
12121 Indicates the name of a project file. This project file will be parsed with
12122 the verbosity indicated by @option{-vP@emph{x}},
12123 if any, and using the external references indicated
12124 by @option{-X} switches, if any.
12125 There may zero, one or more spaces between @option{-P} and @var{project}.
12127 There must be only one @option{-P} switch on the command line.
12129 Since the Project Manager parses the project file only after all the switches
12130 on the command line are checked, the order of the switches
12131 @option{-P},
12132 @option{-vP@emph{x}}
12133 or @option{-X} is not significant.
12135 @item -X@var{name=value}
12136 @cindex @option{-X} (any project-aware tool)
12137 Indicates that external variable @var{name} has the value @var{value}.
12138 The Project Manager will use this value for occurrences of
12139 @code{external(name)} when parsing the project file.
12141 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12142 put between quotes.
12143 @smallexample
12144   -XOS=NT
12145   -X"user=John Doe"
12146 @end smallexample
12148 Several @option{-X} switches can be used simultaneously.
12149 If several @option{-X} switches specify the same
12150 @var{name}, only the last one is used.
12152 An external variable specified with a @option{-X} switch
12153 takes precedence over the value of the same name in the environment.
12155 @item -vP@emph{x}
12156 @cindex @option{-vP} (any project-aware tool)
12157 Indicates the verbosity of the parsing of GNAT project files.
12159 @option{-vP0} means Default;
12160 @option{-vP1} means Medium;
12161 @option{-vP2} means High.
12164 The default is Default: no output for syntactically correct
12165 project files.
12166 If several @option{-vP@emph{x}} switches are present,
12167 only the last one is used.
12169 @item -aP<dir>
12170 @cindex @option{-aP} (any project-aware tool)
12171 Add directory <dir> at the beginning of the project search path, in order,
12172 after the current working directory.
12174 @item -eL
12175 @cindex @option{-eL} (any project-aware tool)
12176 Follow all symbolic links when processing project files.
12178 @item --subdirs=<subdir>
12179 @cindex @option{--subdirs=} (gnatmake and gnatclean)
12180 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12181 indicate that the real directories (except the source directories) are the
12182 subdirectories <subdir> of the directories specified in the project files.
12183 This applies in particular to object directories, library directories and
12184 exec directories. If the subdirectories do not exist, they are created
12185 automatically.
12187 @end table
12189 @c ---------------------------------------------
12190 @node Switches and Project Files
12191 @subsection Switches and Project Files
12192 @c ---------------------------------------------
12194 @noindent
12196 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12197 @code{Linker}, you can specify a @code{Default_Switches}
12198 attribute, a @code{Switches} attribute, or both;
12199 as their names imply, these switch-related
12200 attributes affect the switches that are used for each of these GNAT
12201 components when
12202 @command{gnatmake} is invoked.  As will be explained below, these
12203 component-specific switches precede
12204 the switches provided on the @command{gnatmake} command line.
12206 The @code{Default_Switches} attribute is an attribute
12207 indexed by language name (case insensitive) whose value is a string list.
12208 For example:
12210 @smallexample @c projectfile
12211 @group
12212 @b{package} Compiler @b{is}
12213   @b{for} Default_Switches ("Ada")
12214       @b{use} ("-gnaty",
12215            "-v");
12216 @b{end} Compiler;
12217 @end group
12218 @end smallexample
12220 @noindent
12221 The @code{Switches} attribute is indexed on a file name (which may or may
12222 not be case sensitive, depending
12223 on the operating system) whose value is a string list.  For example:
12225 @smallexample @c projectfile
12226 @group
12227 @b{package} Builder @b{is}
12228    @b{for} Switches ("main1.adb")
12229        @b{use} ("-O2");
12230    @b{for} Switches ("main2.adb")
12231        @b{use} ("-g");
12232 @b{end} Builder;
12233 @end group
12234 @end smallexample
12236 @noindent
12237 For the @code{Builder} package, the file names must designate source files
12238 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12239 file names must designate @file{ALI} or source files for main subprograms.
12240 In each case just the file name without an explicit extension is acceptable.
12242 For each tool used in a program build (@command{gnatmake}, the compiler, the
12243 binder, and the linker), the corresponding package @dfn{contributes} a set of
12244 switches for each file on which the tool is invoked, based on the
12245 switch-related attributes defined in the package.
12246 In particular, the switches
12247 that each of these packages contributes for a given file @var{f} comprise:
12249 @itemize @bullet
12250 @item the value of attribute @code{Switches (@var{f})},
12251   if it is specified in the package for the given file,
12252 @item otherwise, the value of @code{Default_Switches ("Ada")},
12253   if it is specified in the package.
12255 @end itemize
12257 @noindent
12258 If neither of these attributes is defined in the package, then the package does
12259 not contribute any switches for the given file.
12261 When @command{gnatmake} is invoked on a file, the switches comprise
12262 two sets, in the following order: those contributed for the file
12263 by the @code{Builder} package;
12264 and the switches passed on the command line.
12266 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12267 the switches passed to the tool comprise three sets,
12268 in the following order:
12270 @enumerate
12271 @item
12272 the applicable switches contributed for the file
12273 by the @code{Builder} package in the project file supplied on the command line;
12275 @item
12276 those contributed for the file by the package (in the relevant project file --
12277 see below) corresponding to the tool; and
12279 @item
12280 the applicable switches passed on the command line.
12281 @end enumerate
12283 The term @emph{applicable switches} reflects the fact that
12284 @command{gnatmake} switches may or may not be passed to individual
12285 tools, depending on the individual switch.
12287 @command{gnatmake} may invoke the compiler on source files from different
12288 projects. The Project Manager will use the appropriate project file to
12289 determine the @code{Compiler} package for each source file being compiled.
12290 Likewise for the @code{Binder} and @code{Linker} packages.
12292 As an example, consider the following package in a project file:
12294 @smallexample @c projectfile
12295 @group
12296 @b{project} Proj1 @b{is}
12297    @b{package} Compiler @b{is}
12298       @b{for} Default_Switches ("Ada")
12299           @b{use} ("-g");
12300       @b{for} Switches ("a.adb")
12301           @b{use} ("-O1");
12302       @b{for} Switches ("b.adb")
12303           @b{use} ("-O2",
12304                "-gnaty");
12305    @b{end} Compiler;
12306 @b{end} Proj1;
12307 @end group
12308 @end smallexample
12310 @noindent
12311 If @command{gnatmake} is invoked with this project file, and it needs to
12312 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12313 @file{a.adb} will be compiled with the switch
12314 @option{-O1},
12315 @file{b.adb} with switches
12316 @option{-O2}
12317 and @option{-gnaty},
12318 and @file{c.adb} with @option{-g}.
12320 The following example illustrates the ordering of the switches
12321 contributed by different packages:
12323 @smallexample @c projectfile
12324 @group
12325 @b{project} Proj2 @b{is}
12326    @b{package} Builder @b{is}
12327       @b{for} Switches ("main.adb")
12328           @b{use} ("-g",
12329                "-O1",
12330                "-f");
12331    @b{end} Builder;
12332 @end group
12334 @group
12335    @b{package} Compiler @b{is}
12336       @b{for} Switches ("main.adb")
12337           @b{use} ("-O2");
12338    @b{end} Compiler;
12339 @b{end} Proj2;
12340 @end group
12341 @end smallexample
12343 @noindent
12344 If you issue the command:
12346 @smallexample
12347     gnatmake -Pproj2 -O0 main
12348 @end smallexample
12350 @noindent
12351 then the compiler will be invoked on @file{main.adb} with the following
12352 sequence of switches
12354 @smallexample
12355    -g -O1 -O2 -O0
12356 @end smallexample
12358 @noindent
12359 with the last @option{-O}
12360 switch having precedence over the earlier ones;
12361 several other switches
12362 (such as @option{-c}) are added implicitly.
12364 The switches
12365 @option{-g}
12366 and @option{-O1} are contributed by package
12367 @code{Builder},  @option{-O2} is contributed
12368 by the package @code{Compiler}
12369 and @option{-O0} comes from the command line.
12371 The @option{-g}
12372 switch will also be passed in the invocation of
12373 @command{Gnatlink.}
12375 A final example illustrates switch contributions from packages in different
12376 project files:
12378 @smallexample @c projectfile
12379 @group
12380 @b{project} Proj3 @b{is}
12381    @b{for} Source_Files @b{use} ("pack.ads", "pack.adb");
12382    @b{package} Compiler @b{is}
12383       @b{for} Default_Switches ("Ada")
12384           @b{use} ("-gnata");
12385    @b{end} Compiler;
12386 @b{end} Proj3;
12387 @end group
12389 @group
12390 @b{with} "Proj3";
12391 @b{project} Proj4 @b{is}
12392    @b{for} Source_Files @b{use} ("foo_main.adb", "bar_main.adb");
12393    @b{package} Builder @b{is}
12394       @b{for} Switches ("foo_main.adb")
12395           @b{use} ("-s",
12396                "-g");
12397    @b{end} Builder;
12398 @b{end} Proj4;
12399 @end group
12401 @group
12402 --@i{ Ada source file:}
12403 @b{with} Pack;
12404 @b{procedure} Foo_Main @b{is}
12405    @dots{}
12406 @b{end} Foo_Main;
12407 @end group
12408 @end smallexample
12410 @noindent
12411 If the command is
12412 @smallexample
12413 gnatmake -PProj4 foo_main.adb -cargs -gnato
12414 @end smallexample
12416 @noindent
12417 then the switches passed to the compiler for @file{foo_main.adb} are
12418 @option{-g} (contributed by the package @code{Proj4.Builder}) and
12419 @option{-gnato} (passed on the command line).
12420 When the imported package @code{Pack} is compiled, the switches used
12421 are @option{-g} from @code{Proj4.Builder},
12422 @option{-gnata} (contributed from package @code{Proj3.Compiler},
12423 and @option{-gnato} from the command line.
12425 When using @command{gnatmake} with project files, some switches or
12426 arguments may be expressed as relative paths. As the working directory where
12427 compilation occurs may change, these relative paths are converted to absolute
12428 paths. For the switches found in a project file, the relative paths
12429 are relative to the project file directory, for the switches on the command
12430 line, they are relative to the directory where @command{gnatmake} is invoked.
12431 The switches for which this occurs are:
12435 -aO,
12436 -aL,
12437 -aI, as well as all arguments that are not switches (arguments to
12438 switch
12439 -o, object files specified in package @code{Linker} or after
12440 -largs on the command line). The exception to this rule is the switch
12441 --RTS= for which a relative path argument is never converted.
12443 @c ---------------------------------------------
12444 @node Specifying Configuration Pragmas
12445 @subsection Specifying Configuration Pragmas
12446 @c ---------------------------------------------
12448 @noindent
12449 When using @command{gnatmake} with project files, if there exists a file
12450 @file{gnat.adc} that contains configuration pragmas, this file will be
12451 ignored.
12453 Configuration pragmas can be defined by means of the following attributes in
12454 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12455 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12457 Both these attributes are single string attributes. Their values is the path
12458 name of a file containing configuration pragmas. If a path name is relative,
12459 then it is relative to the project directory of the project file where the
12460 attribute is defined.
12462 When compiling a source, the configuration pragmas used are, in order,
12463 those listed in the file designated by attribute
12464 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12465 project file, if it is specified, and those listed in the file designated by
12466 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12467 the project file of the source, if it exists.
12469 @c ---------------------------------------------
12470 @node Project Files and Main Subprograms
12471 @subsection Project Files and Main Subprograms
12472 @c ---------------------------------------------
12474 @noindent
12475 When using a project file, you can invoke @command{gnatmake}
12476 with one or several main subprograms, by specifying their source files on the
12477 command line.
12479 @smallexample
12480     gnatmake -Pprj main1.adb main2.adb main3.adb
12481 @end smallexample
12483 @noindent
12484 Each of these needs to be a source file of the same project, except
12485 when the switch -u is used.
12487 When -u is not used, all the mains need to be sources of the
12488 same project, one of the project in the tree rooted at the project specified
12489 on the command line. The package @code{Builder} of this common project, the
12490 "main project" is the one that is considered by @command{gnatmake}.
12492 When -u is used, the specified source files may be in projects
12493 imported directly or indirectly by the project specified on the command line.
12494 Note that if such a source file is not part of the project specified on the
12495 command line, the switches found in package @code{Builder} of the
12496 project specified on the command line, if any, that are transmitted
12497 to the compiler will still be used, not those found in the project file of
12498 the source file.
12500 When using a project file, you can also invoke @command{gnatmake} without
12501 explicitly specifying any main, and the effect depends on whether you have
12502 defined the @code{Main} attribute.  This attribute has a string list value,
12503 where each element in the list is the name of a source file (the file
12504 extension is optional) that contains a unit that can be a main subprogram.
12506 If the @code{Main} attribute is defined in a project file as a non-empty
12507 string list and the switch @option{-u} is not used on the command
12508 line, then invoking @command{gnatmake} with this project file but without any
12509 main on the command line is equivalent to invoking @command{gnatmake} with all
12510 the file names in the @code{Main} attribute on the command line.
12512 Example:
12513 @smallexample @c projectfile
12514 @group
12515    @b{project} Prj @b{is}
12516       @b{for} Main @b{use} ("main1.adb", "main2.adb", "main3.adb");
12517    @b{end} Prj;
12518 @end group
12519 @end smallexample
12521 @noindent
12522 With this project file, @code{"gnatmake -Pprj"}
12523 is equivalent to
12524 @code{"gnatmake -Pprj main1.adb main2.adb main3.adb"}.
12526 When the project attribute @code{Main} is not specified, or is specified
12527 as an empty string list, or when the switch @option{-u} is used on the command
12528 line, then invoking @command{gnatmake} with no main on the command line will
12529 result in all immediate sources of the project file being checked, and
12530 potentially recompiled. Depending on the presence of the switch @option{-u},
12531 sources from other project files on which the immediate sources of the main
12532 project file depend are also checked and potentially recompiled. In other
12533 words, the @option{-u} switch is applied to all of the immediate sources of the
12534 main project file.
12536 When no main is specified on the command line and attribute @code{Main} exists
12537 and includes several mains, or when several mains are specified on the
12538 command line, the default switches in package @code{Builder} will
12539 be used for all mains, even if there are specific switches
12540 specified for one or several mains.
12542 But the switches from package @code{Binder} or @code{Linker} will be
12543 the specific switches for each main, if they are specified.
12545 @c ---------------------------------------------
12546 @node Library Project Files
12547 @subsection Library Project Files
12548 @c ---------------------------------------------
12550 @noindent
12551 When @command{gnatmake} is invoked with a main project file that is a library
12552 project file, it is not allowed to specify one or more mains on the command
12553 line.
12555 When a library project file is specified, switches -b and
12556 -l have special meanings.
12558 @itemize @bullet
12559 @item -b is only allowed for stand-alone libraries. It indicates
12560   to @command{gnatmake} that @command{gnatbind} should be invoked for the
12561   library.
12563 @item -l may be used for all library projects. It indicates
12564   to @command{gnatmake} that the binder generated file should be compiled
12565   (in the case of a stand-alone library) and that the library should be built.
12566 @end itemize
12568 @c ---------------------------------------------
12569 @node The GNAT Driver and Project Files
12570 @section The GNAT Driver and Project Files
12571 @c ---------------------------------------------
12573 @noindent
12574 A number of GNAT tools, other than @command{gnatmake}
12575 can benefit from project files:
12576 (@command{gnatbind},
12577 @ifclear FSFEDITION
12578 @command{gnatcheck},
12579 @end ifclear
12580 @command{gnatclean},
12581 @ifclear FSFEDITION
12582 @command{gnatelim},
12583 @end ifclear
12584 @command{gnatfind},
12585 @command{gnatlink},
12586 @command{gnatls},
12587 @ifclear FSFEDITION
12588 @command{gnatmetric},
12589 @command{gnatpp},
12590 @command{gnatstub},
12591 @end ifclear
12592 and @command{gnatxref}). However, none of these tools can be invoked
12593 directly with a project file switch (@option{-P}).
12594 They must be invoked through the @command{gnat} driver.
12596 The @command{gnat} driver is a wrapper that accepts a number of commands and
12597 calls the corresponding tool. It was designed initially for VMS platforms (to
12598 convert VMS qualifiers to Unix-style switches), but it is now available on all
12599 GNAT platforms.
12601 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12602 (case insensitive):
12604 @itemize @bullet
12605 @item BIND to invoke @command{gnatbind}
12606 @item CHOP to invoke @command{gnatchop}
12607 @item CLEAN to invoke @command{gnatclean}
12608 @item COMP or COMPILE to invoke the compiler
12609 @ifclear FSFEDITION
12610 @item ELIM to invoke @command{gnatelim}
12611 @end ifclear
12612 @item FIND to invoke @command{gnatfind}
12613 @item KR or KRUNCH to invoke @command{gnatkr}
12614 @item LINK to invoke @command{gnatlink}
12615 @item LS or LIST to invoke @command{gnatls}
12616 @item MAKE to invoke @command{gnatmake}
12617 @item NAME to invoke @command{gnatname}
12618 @item PREP or PREPROCESS to invoke @command{gnatprep}
12619 @ifclear FSFEDITION
12620 @item PP or PRETTY to invoke @command{gnatpp}
12621 @item METRIC to invoke @command{gnatmetric}
12622 @item STUB to invoke @command{gnatstub}
12623 @end ifclear
12624 @item XREF to invoke @command{gnatxref}
12626 @end itemize
12628 @noindent
12629 (note that the compiler is invoked using the command
12630 @command{gnatmake -f -u -c}).
12632 On non-VMS platforms, between @command{gnat} and the command, two
12633 special switches may be used:
12635 @itemize @bullet
12636 @item @command{-v} to display the invocation of the tool.
12637 @item @command{-dn} to prevent the @command{gnat} driver from removing
12638   the temporary files it has created. These temporary files are
12639   configuration files and temporary file list files.
12641 @end itemize
12643 @noindent
12644 The command may be followed by switches and arguments for the invoked
12645 tool.
12647 @smallexample
12648   gnat bind -C main.ali
12649   gnat ls -a main
12650   gnat chop foo.txt
12651 @end smallexample
12653 @noindent
12654 Switches may also be put in text files, one switch per line, and the text
12655 files may be specified with their path name preceded by '@@'.
12657 @smallexample
12658    gnat bind @@args.txt main.ali
12659 @end smallexample
12661 @noindent
12662 In addition, for commands BIND, COMP or COMPILE, FIND,
12663 @ifclear FSFEDITION
12664 ELIM,
12665 @end ifclear
12666 LS or LIST, LINK,
12667 @ifclear FSFEDITION
12668 METRIC,
12669 PP or PRETTY,
12670 STUB,
12671 @end ifclear
12672 and XREF, the project file related switches
12673 (@option{-P},
12674 @option{-X} and
12675 @option{-vPx}) may be used in addition to
12676 the switches of the invoking tool.
12678 @ifclear FSFEDITION
12679 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12680 specified on the command line, it invokes @command{gnatpp} with all
12681 the immediate sources of the specified project file.
12682 @end ifclear
12684 @ifclear FSFEDITION
12685 When GNAT METRIC is used with a project file, but with no source
12686 specified on the command line, it invokes @command{gnatmetric}
12687 with all the immediate sources of the specified project file and with
12688 @option{-d} with the parameter pointing to the object directory
12689 of the project.
12690 @end ifclear
12692 @ifclear FSFEDITION
12693 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12694 a project file, no source is specified on the command line and
12695 switch -U is specified on the command line, then
12696 the underlying tool (gnatpp or
12697 gnatmetric) is invoked for all sources of all projects,
12698 not only for the immediate sources of the main project.
12699 (-U stands for Universal or Union of the project files of the project tree)
12700 @end ifclear
12702 For each of the following commands, there is optionally a corresponding
12703 package in the main project.
12705 @itemize @bullet
12706 @item package @code{Binder} for command BIND (invoking @code{gnatbind})
12708 @ifclear FSFEDITION
12709 @item package @code{Check} for command CHECK (invoking
12710   @code{gnatcheck})
12711 @end ifclear
12713 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12715 @item package @code{Cross_Reference} for command XREF (invoking
12716   @code{gnatxref})
12718 @ifclear FSFEDITION
12719 @item package @code{Eliminate} for command ELIM (invoking
12720   @code{gnatelim})
12721 @end ifclear
12723 @item package @code{Finder} for command FIND (invoking @code{gnatfind})
12725 @item package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
12727 @ifclear FSFEDITION
12728 @item package @code{Gnatstub} for command STUB
12729   (invoking @code{gnatstub})
12730 @end ifclear
12732 @item package @code{Linker} for command LINK (invoking @code{gnatlink})
12734 @ifclear FSFEDITION
12735 @item package @code{Check} for command CHECK
12736   (invoking @code{gnatcheck})
12737 @end ifclear
12739 @ifclear FSFEDITION
12740 @item package @code{Metrics} for command METRIC
12741   (invoking @code{gnatmetric})
12742 @end ifclear
12744 @ifclear FSFEDITION
12745 @item package @code{Pretty_Printer} for command PP or PRETTY
12746   (invoking @code{gnatpp})
12747 @end ifclear
12749 @end itemize
12751 @noindent
12752 Package @code{Gnatls} has a unique attribute @code{Switches},
12753 a simple variable with a string list value. It contains switches
12754 for the invocation of @code{gnatls}.
12756 @smallexample @c projectfile
12757 @group
12758 @b{project} Proj1 @b{is}
12759    @b{package} gnatls @b{is}
12760       @b{for} Switches
12761           @b{use} ("-a",
12762                "-v");
12763    @b{end} gnatls;
12764 @b{end} Proj1;
12765 @end group
12766 @end smallexample
12768 @noindent
12769 All other packages have two attribute @code{Switches} and
12770 @code{Default_Switches}.
12772 @code{Switches} is an indexed attribute, indexed by the
12773 source file name, that has a string list value: the switches to be
12774 used when the tool corresponding to the package is invoked for the specific
12775 source file.
12777 @code{Default_Switches} is an attribute,
12778 indexed by  the programming language that has a string list value.
12779 @code{Default_Switches ("Ada")} contains the
12780 switches for the invocation of the tool corresponding
12781 to the package, except if a specific @code{Switches} attribute
12782 is specified for the source file.
12784 @smallexample @c projectfile
12785 @group
12786 @b{project} Proj @b{is}
12788    @b{for} Source_Dirs @b{use} ("**");
12790    @b{package} gnatls @b{is}
12791       @b{for} Switches @b{use}
12792           ("-a",
12793            "-v");
12794    @b{end} gnatls;
12795 @end group
12796 @group
12798    @b{package} Compiler @b{is}
12799       @b{for} Default_Switches ("Ada")
12800           @b{use} ("-gnatv",
12801                "-gnatwa");
12802    @b{end} Binder;
12803 @end group
12804 @group
12806    @b{package} Binder @b{is}
12807       @b{for} Default_Switches ("Ada")
12808           @b{use} ("-C",
12809                "-e");
12810    @b{end} Binder;
12811 @end group
12812 @group
12814    @b{package} Linker @b{is}
12815       @b{for} Default_Switches ("Ada")
12816           @b{use} ("-C");
12817       @b{for} Switches ("main.adb")
12818           @b{use} ("-C",
12819                "-v",
12820                "-v");
12821    @b{end} Linker;
12822 @end group
12823 @group
12825    @b{package} Finder @b{is}
12826       @b{for} Default_Switches ("Ada")
12827            @b{use} ("-a",
12828                 "-f");
12829    @b{end} Finder;
12830 @end group
12831 @group
12833    @b{package} Cross_Reference @b{is}
12834       @b{for} Default_Switches ("Ada")
12835           @b{use} ("-a",
12836                "-f",
12837                "-d",
12838                "-u");
12839    @b{end} Cross_Reference;
12840 @b{end} Proj;
12841 @end group
12842 @end smallexample
12844 @noindent
12845 With the above project file, commands such as
12847 @smallexample
12848    gnat comp -Pproj main
12849    gnat ls -Pproj main
12850    gnat xref -Pproj main
12851    gnat bind -Pproj main.ali
12852    gnat link -Pproj main.ali
12853 @end smallexample
12855 @noindent
12856 will set up the environment properly and invoke the tool with the switches
12857 found in the package corresponding to the tool:
12858 @code{Default_Switches ("Ada")} for all tools,
12859 except @code{Switches ("main.adb")}
12860 for @code{gnatlink}.
12861 @ifclear FSFEDITION
12862 It is also possible to invoke some of the tools,
12863 (@code{gnatcheck},
12864 @code{gnatmetric},
12865 and @code{gnatpp})
12866 on a set of project units thanks to the combination of the switches
12867 @option{-P}, @option{-U} and possibly the main unit when one is interested
12868 in its closure. For instance,
12869 @smallexample
12870 gnat metric -Pproj
12871 @end smallexample
12873 @noindent
12874 will compute the metrics for all the immediate units of project
12875 @code{proj}.
12876 @smallexample
12877 gnat metric -Pproj -U
12878 @end smallexample
12880 @noindent
12881 will compute the metrics for all the units of the closure of projects
12882 rooted at @code{proj}.
12883 @smallexample
12884 gnat metric -Pproj -U main_unit
12885 @end smallexample
12887 @noindent
12888 will compute the metrics for the closure of units rooted at
12889 @code{main_unit}. This last possibility relies implicitly
12890 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
12891 tool invoked by the @command{gnat} driver are explicitly  specified
12892 either directly or through the tool @option{-files} option, then the tool
12893 is called only for these explicitly specified files.
12894 @end ifclear
12896 @c *****************************************
12897 @c * Cross-referencing tools
12898 @c *****************************************
12900 @node The Cross-Referencing Tools gnatxref and gnatfind
12901 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12902 @findex gnatxref
12903 @findex gnatfind
12905 @noindent
12906 The compiler generates cross-referencing information (unless
12907 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12908 This information indicates where in the source each entity is declared and
12909 referenced. Note that entities in package Standard are not included, but
12910 entities in all other predefined units are included in the output.
12912 Before using any of these two tools, you need to compile successfully your
12913 application, so that GNAT gets a chance to generate the cross-referencing
12914 information.
12916 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12917 information to provide the user with the capability to easily locate the
12918 declaration and references to an entity. These tools are quite similar,
12919 the difference being that @code{gnatfind} is intended for locating
12920 definitions and/or references to a specified entity or entities, whereas
12921 @code{gnatxref} is oriented to generating a full report of all
12922 cross-references.
12924 To use these tools, you must not compile your application using the
12925 @option{-gnatx} switch on the @command{gnatmake} command line
12926 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12927 information will not be generated.
12929 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12930 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12932 @menu
12933 * Switches for gnatxref::
12934 * Switches for gnatfind::
12935 * Project Files for gnatxref and gnatfind::
12936 * Regular Expressions in gnatfind and gnatxref::
12937 * Examples of gnatxref Usage::
12938 * Examples of gnatfind Usage::
12939 @end menu
12941 @node Switches for gnatxref
12942 @section @code{gnatxref} Switches
12944 @noindent
12945 The command invocation for @code{gnatxref} is:
12946 @smallexample
12947 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12948 @c Expanding @ovar macro inline (explanation in macro def comments)
12949 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12950 @end smallexample
12952 @noindent
12953 where
12955 @table @var
12956 @item sourcefile1
12957 @itemx sourcefile2
12958 identifies the source files for which a report is to be generated. The
12959 ``with''ed units will be processed too. You must provide at least one file.
12961 These file names are considered to be regular expressions, so for instance
12962 specifying @file{source*.adb} is the same as giving every file in the current
12963 directory whose name starts with @file{source} and whose extension is
12964 @file{adb}.
12966 You shouldn't specify any directory name, just base names. @command{gnatxref}
12967 and @command{gnatfind} will be able to locate these files by themselves using
12968 the source path. If you specify directories, no result is produced.
12970 @end table
12972 @noindent
12973 The switches can be:
12974 @table @option
12975 @c !sort!
12976 @item --version
12977 @cindex @option{--version} @command{gnatxref}
12978 Display Copyright and version, then exit disregarding all other options.
12980 @item --help
12981 @cindex @option{--help} @command{gnatxref}
12982 If @option{--version} was not used, display usage, then exit disregarding
12983 all other options.
12985 @item -a
12986 @cindex @option{-a} (@command{gnatxref})
12987 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12988 the read-only files found in the library search path. Otherwise, these files
12989 will be ignored. This option can be used to protect Gnat sources or your own
12990 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12991 much faster, and their output much smaller. Read-only here refers to access
12992 or permissions status in the file system for the current user.
12994 @item -aIDIR
12995 @cindex @option{-aIDIR} (@command{gnatxref})
12996 When looking for source files also look in directory DIR. The order in which
12997 source file search is undertaken is the same as for @command{gnatmake}.
12999 @item -aODIR
13000 @cindex @option{-aODIR} (@command{gnatxref})
13001 When searching for library and object files, look in directory
13002 DIR. The order in which library files are searched is the same as for
13003 @command{gnatmake}.
13005 @item -nostdinc
13006 @cindex @option{-nostdinc} (@command{gnatxref})
13007 Do not look for sources in the system default directory.
13009 @item -nostdlib
13010 @cindex @option{-nostdlib} (@command{gnatxref})
13011 Do not look for library files in the system default directory.
13013 @item --ext=@var{extension}
13014 @cindex @option{--ext} (@command{gnatxref})
13015 Specify an alternate ali file extension. The default is @code{ali} and other
13016 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13017 may be specified via this switch. Note that if this switch overrides the
13018 default, which means that only the new extension will be considered.
13020 @item --RTS=@var{rts-path}
13021 @cindex @option{--RTS} (@command{gnatxref})
13022 Specifies the default location of the runtime library. Same meaning as the
13023 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13025 @item -d
13026 @cindex @option{-d} (@command{gnatxref})
13027 If this switch is set @code{gnatxref} will output the parent type
13028 reference for each matching derived types.
13030 @item -f
13031 @cindex @option{-f} (@command{gnatxref})
13032 If this switch is set, the output file names will be preceded by their
13033 directory (if the file was found in the search path). If this switch is
13034 not set, the directory will not be printed.
13036 @item -g
13037 @cindex @option{-g} (@command{gnatxref})
13038 If this switch is set, information is output only for library-level
13039 entities, ignoring local entities. The use of this switch may accelerate
13040 @code{gnatfind} and @code{gnatxref}.
13042 @item -IDIR
13043 @cindex @option{-IDIR} (@command{gnatxref})
13044 Equivalent to @samp{-aODIR -aIDIR}.
13046 @item -pFILE
13047 @cindex @option{-pFILE} (@command{gnatxref})
13048 Specify a project file to use @xref{GNAT Project Manager}.
13049 If you need to use the @file{.gpr}
13050 project files, you should use gnatxref through the GNAT driver
13051 (@command{gnat xref -Pproject}).
13053 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13054 project file in the current directory.
13056 If a project file is either specified or found by the tools, then the content
13057 of the source directory and object directory lines are added as if they
13058 had been specified respectively by @samp{-aI}
13059 and @samp{-aO}.
13060 @item -u
13061 Output only unused symbols. This may be really useful if you give your
13062 main compilation unit on the command line, as @code{gnatxref} will then
13063 display every unused entity and 'with'ed package.
13065 @item -v
13066 Instead of producing the default output, @code{gnatxref} will generate a
13067 @file{tags} file that can be used by vi. For examples how to use this
13068 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13069 to the standard output, thus you will have to redirect it to a file.
13071 @end table
13073 @noindent
13074 All these switches may be in any order on the command line, and may even
13075 appear after the file names. They need not be separated by spaces, thus
13076 you can say @samp{gnatxref -ag} instead of
13077 @samp{gnatxref -a -g}.
13079 @node Switches for gnatfind
13080 @section @code{gnatfind} Switches
13082 @noindent
13083 The command line for @code{gnatfind} is:
13085 @smallexample
13086 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13087 @c       @r{[}@var{file1} @var{file2} @dots{}]
13088 @c Expanding @ovar macro inline (explanation in macro def comments)
13089 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13090       @r{[}@var{file1} @var{file2} @dots{}@r{]}
13091 @end smallexample
13093 @noindent
13094 where
13096 @table @var
13097 @item pattern
13098 An entity will be output only if it matches the regular expression found
13099 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13101 Omitting the pattern is equivalent to specifying @samp{*}, which
13102 will match any entity. Note that if you do not provide a pattern, you
13103 have to provide both a sourcefile and a line.
13105 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13106 for matching purposes. At the current time there is no support for
13107 8-bit codes other than Latin-1, or for wide characters in identifiers.
13109 @item sourcefile
13110 @code{gnatfind} will look for references, bodies or declarations
13111 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13112 and column @var{column}. See @ref{Examples of gnatfind Usage}
13113 for syntax examples.
13115 @item line
13116 is a decimal integer identifying the line number containing
13117 the reference to the entity (or entities) to be located.
13119 @item column
13120 is a decimal integer identifying the exact location on the
13121 line of the first character of the identifier for the
13122 entity reference. Columns are numbered from 1.
13124 @item file1 file2 @dots{}
13125 The search will be restricted to these source files. If none are given, then
13126 the search will be done for every library file in the search path.
13127 These file must appear only after the pattern or sourcefile.
13129 These file names are considered to be regular expressions, so for instance
13130 specifying @file{source*.adb} is the same as giving every file in the current
13131 directory whose name starts with @file{source} and whose extension is
13132 @file{adb}.
13134 The location of the spec of the entity will always be displayed, even if it
13135 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
13136 occurrences of the entity in the separate units of the ones given on the
13137 command line will also be displayed.
13139 Note that if you specify at least one file in this part, @code{gnatfind} may
13140 sometimes not be able to find the body of the subprograms.
13142 @end table
13144 @noindent
13145 At least one of 'sourcefile' or 'pattern' has to be present on
13146 the command line.
13148 The following switches are available:
13149 @table @option
13150 @c !sort!
13152 @cindex @option{--version} @command{gnatfind}
13153 Display Copyright and version, then exit disregarding all other options.
13155 @item --help
13156 @cindex @option{--help} @command{gnatfind}
13157 If @option{--version} was not used, display usage, then exit disregarding
13158 all other options.
13160 @item -a
13161 @cindex @option{-a} (@command{gnatfind})
13162 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13163 the read-only files found in the library search path. Otherwise, these files
13164 will be ignored. This option can be used to protect Gnat sources or your own
13165 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13166 much faster, and their output much smaller. Read-only here refers to access
13167 or permission status in the file system for the current user.
13169 @item -aIDIR
13170 @cindex @option{-aIDIR} (@command{gnatfind})
13171 When looking for source files also look in directory DIR. The order in which
13172 source file search is undertaken is the same as for @command{gnatmake}.
13174 @item -aODIR
13175 @cindex @option{-aODIR} (@command{gnatfind})
13176 When searching for library and object files, look in directory
13177 DIR. The order in which library files are searched is the same as for
13178 @command{gnatmake}.
13180 @item -nostdinc
13181 @cindex @option{-nostdinc} (@command{gnatfind})
13182 Do not look for sources in the system default directory.
13184 @item -nostdlib
13185 @cindex @option{-nostdlib} (@command{gnatfind})
13186 Do not look for library files in the system default directory.
13188 @item --ext=@var{extension}
13189 @cindex @option{--ext} (@command{gnatfind})
13190 Specify an alternate ali file extension. The default is @code{ali} and other
13191 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13192 may be specified via this switch. Note that if this switch overrides the
13193 default, which means that only the new extension will be considered.
13195 @item --RTS=@var{rts-path}
13196 @cindex @option{--RTS} (@command{gnatfind})
13197 Specifies the default location of the runtime library. Same meaning as the
13198 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13200 @item -d
13201 @cindex @option{-d} (@code{gnatfind})
13202 If this switch is set, then @code{gnatfind} will output the parent type
13203 reference for each matching derived types.
13205 @item -e
13206 @cindex @option{-e} (@command{gnatfind})
13207 By default, @code{gnatfind} accept the simple regular expression set for
13208 @samp{pattern}. If this switch is set, then the pattern will be
13209 considered as full Unix-style regular expression.
13211 @item -f
13212 @cindex @option{-f} (@command{gnatfind})
13213 If this switch is set, the output file names will be preceded by their
13214 directory (if the file was found in the search path). If this switch is
13215 not set, the directory will not be printed.
13217 @item -g
13218 @cindex @option{-g} (@command{gnatfind})
13219 If this switch is set, information is output only for library-level
13220 entities, ignoring local entities. The use of this switch may accelerate
13221 @code{gnatfind} and @code{gnatxref}.
13223 @item -IDIR
13224 @cindex @option{-IDIR} (@command{gnatfind})
13225 Equivalent to @samp{-aODIR -aIDIR}.
13227 @item -pFILE
13228 @cindex @option{-pFILE} (@command{gnatfind})
13229 Specify a project file (@pxref{GNAT Project Manager}) to use.
13230 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13231 project file in the current directory.
13233 If a project file is either specified or found by the tools, then the content
13234 of the source directory and object directory lines are added as if they
13235 had been specified respectively by @samp{-aI} and
13236 @samp{-aO}.
13238 @item -r
13239 @cindex @option{-r} (@command{gnatfind})
13240 By default, @code{gnatfind} will output only the information about the
13241 declaration, body or type completion of the entities. If this switch is
13242 set, the @code{gnatfind} will locate every reference to the entities in
13243 the files specified on the command line (or in every file in the search
13244 path if no file is given on the command line).
13246 @item -s
13247 @cindex @option{-s} (@command{gnatfind})
13248 If this switch is set, then @code{gnatfind} will output the content
13249 of the Ada source file lines were the entity was found.
13251 @item -t
13252 @cindex @option{-t} (@command{gnatfind})
13253 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13254 the specified type. It act like -d option but recursively from parent
13255 type to parent type. When this switch is set it is not possible to
13256 specify more than one file.
13258 @end table
13260 @noindent
13261 All these switches may be in any order on the command line, and may even
13262 appear after the file names. They need not be separated by spaces, thus
13263 you can say @samp{gnatxref -ag} instead of
13264 @samp{gnatxref -a -g}.
13266 As stated previously, gnatfind will search in every directory in the
13267 search path. You can force it to look only in the current directory if
13268 you specify @code{*} at the end of the command line.
13270 @node Project Files for gnatxref and gnatfind
13271 @section Project Files for @command{gnatxref} and @command{gnatfind}
13273 @noindent
13274 Project files allow a programmer to specify how to compile its
13275 application, where to find sources, etc.  These files are used
13276 primarily by GPS, but they can also be used
13277 by the two tools
13278 @code{gnatxref} and @code{gnatfind}.
13280 A project file name must end with @file{.gpr}. If a single one is
13281 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13282 extract the information from it. If multiple project files are found, none of
13283 them is read, and you have to use the @samp{-p} switch to specify the one
13284 you want to use.
13286 The following lines can be included, even though most of them have default
13287 values which can be used in most cases.
13288 The lines can be entered in any order in the file.
13289 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13290 each line. If you have multiple instances, only the last one is taken into
13291 account.
13293 @table @code
13294 @item src_dir=DIR
13295 [default: @code{"./"}]
13296 specifies a directory where to look for source files. Multiple @code{src_dir}
13297 lines can be specified and they will be searched in the order they
13298 are specified.
13300 @item obj_dir=DIR
13301 [default: @code{"./"}]
13302 specifies a directory where to look for object and library files. Multiple
13303 @code{obj_dir} lines can be specified, and they will be searched in the order
13304 they are specified
13306 @item comp_opt=SWITCHES
13307 [default: @code{""}]
13308 creates a variable which can be referred to subsequently by using
13309 the @code{$@{comp_opt@}} notation. This is intended to store the default
13310 switches given to @command{gnatmake} and @command{gcc}.
13312 @item bind_opt=SWITCHES
13313 [default: @code{""}]
13314 creates a variable which can be referred to subsequently by using
13315 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13316 switches given to @command{gnatbind}.
13318 @item link_opt=SWITCHES
13319 [default: @code{""}]
13320 creates a variable which can be referred to subsequently by using
13321 the @samp{$@{link_opt@}} notation. This is intended to store the default
13322 switches given to @command{gnatlink}.
13324 @item main=EXECUTABLE
13325 [default: @code{""}]
13326 specifies the name of the executable for the application. This variable can
13327 be referred to in the following lines by using the @samp{$@{main@}} notation.
13329 @item comp_cmd=COMMAND
13330 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13331 specifies the command used to compile a single file in the application.
13333 @item make_cmd=COMMAND
13334 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13335 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13336 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13337 specifies the command used to recompile the whole application.
13339 @item run_cmd=COMMAND
13340 [default: @code{"$@{main@}"}]
13341 specifies the command used to run the application.
13343 @item debug_cmd=COMMAND
13344 [default: @code{"gdb $@{main@}"}]
13345 specifies the command used to debug the application
13347 @end table
13349 @noindent
13350 @command{gnatxref} and @command{gnatfind} only take into account the
13351 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13353 @node Regular Expressions in gnatfind and gnatxref
13354 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13356 @noindent
13357 As specified in the section about @command{gnatfind}, the pattern can be a
13358 regular expression. Actually, there are to set of regular expressions
13359 which are recognized by the program:
13361 @table @code
13362 @item globbing patterns
13363 These are the most usual regular expression. They are the same that you
13364 generally used in a Unix shell command line, or in a DOS session.
13366 Here is a more formal grammar:
13367 @smallexample
13368 @group
13369 @iftex
13370 @leftskip=.5cm
13371 @end iftex
13372 regexp ::= term
13373 term   ::= elmt            -- matches elmt
13374 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13375 term   ::= *               -- any string of 0 or more characters
13376 term   ::= ?               -- matches any character
13377 term   ::= [char @{char@}]   -- matches any character listed
13378 term   ::= [char - char]   -- matches any character in range
13379 @end group
13380 @end smallexample
13382 @item full regular expression
13383 The second set of regular expressions is much more powerful. This is the
13384 type of regular expressions recognized by utilities such a @file{grep}.
13386 The following is the form of a regular expression, expressed in Ada
13387 reference manual style BNF is as follows
13389 @smallexample
13390 @iftex
13391 @leftskip=.5cm
13392 @end iftex
13393 @group
13394 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
13396 term ::= item @{item@}       -- concatenation (item then item)
13398 item ::= elmt              -- match elmt
13399 item ::= elmt *            -- zero or more elmt's
13400 item ::= elmt +            -- one or more elmt's
13401 item ::= elmt ?            -- matches elmt or nothing
13402 @end group
13403 @group
13404 elmt ::= nschar            -- matches given character
13405 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13406 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
13407 elmt ::= [char - char]     -- matches chars in given range
13408 elmt ::= \ char            -- matches given character
13409 elmt ::= .                 -- matches any single character
13410 elmt ::= ( regexp )        -- parens used for grouping
13412 char ::= any character, including special characters
13413 nschar ::= any character except ()[].*+?^
13414 @end group
13415 @end smallexample
13417 Following are a few examples:
13419 @table @samp
13420 @item abcde|fghi
13421 will match any of the two strings @samp{abcde} and @samp{fghi},
13423 @item abc*d
13424 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13425 @samp{abcccd}, and so on,
13427 @item [a-z]+
13428 will match any string which has only lowercase characters in it (and at
13429 least one character.
13431 @end table
13432 @end table
13434 @node Examples of gnatxref Usage
13435 @section Examples of @code{gnatxref} Usage
13437 @subsection General Usage
13439 @noindent
13440 For the following examples, we will consider the following units:
13442 @smallexample @c ada
13443 @group
13444 @cartouche
13445 main.ads:
13446 1: @b{with} Bar;
13447 2: @b{package} Main @b{is}
13448 3:     @b{procedure} Foo (B : @b{in} Integer);
13449 4:     C : Integer;
13450 5: @b{private}
13451 6:     D : Integer;
13452 7: @b{end} Main;
13454 main.adb:
13455 1: @b{package} @b{body} Main @b{is}
13456 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13457 3:     @b{begin}
13458 4:        C := B;
13459 5:        D := B;
13460 6:        Bar.Print (B);
13461 7:        Bar.Print (C);
13462 8:     @b{end} Foo;
13463 9: @b{end} Main;
13465 bar.ads:
13466 1: @b{package} Bar @b{is}
13467 2:     @b{procedure} Print (B : Integer);
13468 3: @b{end} bar;
13469 @end cartouche
13470 @end group
13471 @end smallexample
13473 @table @code
13475 @noindent
13476 The first thing to do is to recompile your application (for instance, in
13477 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13478 the cross-referencing information.
13479 You can then issue any of the following commands:
13481 @item gnatxref main.adb
13482 @code{gnatxref} generates cross-reference information for main.adb
13483 and every unit 'with'ed by main.adb.
13485 The output would be:
13486 @smallexample
13487 @iftex
13488 @leftskip=0cm
13489 @end iftex
13490 B                                                      Type: Integer
13491   Decl: bar.ads           2:22
13492 B                                                      Type: Integer
13493   Decl: main.ads          3:20
13494   Body: main.adb          2:20
13495   Ref:  main.adb          4:13     5:13     6:19
13496 Bar                                                    Type: Unit
13497   Decl: bar.ads           1:9
13498   Ref:  main.adb          6:8      7:8
13499        main.ads           1:6
13500 C                                                      Type: Integer
13501   Decl: main.ads          4:5
13502   Modi: main.adb          4:8
13503   Ref:  main.adb          7:19
13504 D                                                      Type: Integer
13505   Decl: main.ads          6:5
13506   Modi: main.adb          5:8
13507 Foo                                                    Type: Unit
13508   Decl: main.ads          3:15
13509   Body: main.adb          2:15
13510 Main                                                    Type: Unit
13511   Decl: main.ads          2:9
13512   Body: main.adb          1:14
13513 Print                                                   Type: Unit
13514   Decl: bar.ads           2:15
13515   Ref:  main.adb          6:12     7:12
13516 @end smallexample
13518 @noindent
13519 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13520 its body is in main.adb, line 1, column 14 and is not referenced any where.
13522 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13523 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13525 @item gnatxref package1.adb package2.ads
13526 @code{gnatxref} will generates cross-reference information for
13527 package1.adb, package2.ads and any other package 'with'ed by any
13528 of these.
13530 @end table
13532 @subsection Using gnatxref with vi
13534 @code{gnatxref} can generate a tags file output, which can be used
13535 directly from @command{vi}. Note that the standard version of @command{vi}
13536 will not work properly with overloaded symbols. Consider using another
13537 free implementation of @command{vi}, such as @command{vim}.
13539 @smallexample
13540 $ gnatxref -v gnatfind.adb > tags
13541 @end smallexample
13543 @noindent
13544 will generate the tags file for @code{gnatfind} itself (if the sources
13545 are in the search path!).
13547 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13548 (replacing @var{entity} by whatever you are looking for), and vi will
13549 display a new file with the corresponding declaration of entity.
13551 @node Examples of gnatfind Usage
13552 @section Examples of @code{gnatfind} Usage
13554 @table @code
13556 @item gnatfind -f xyz:main.adb
13557 Find declarations for all entities xyz referenced at least once in
13558 main.adb. The references are search in every library file in the search
13559 path.
13561 The directories will be printed as well (as the @samp{-f}
13562 switch is set)
13564 The output will look like:
13565 @smallexample
13566 directory/main.ads:106:14: xyz <= declaration
13567 directory/main.adb:24:10: xyz <= body
13568 directory/foo.ads:45:23: xyz <= declaration
13569 @end smallexample
13571 @noindent
13572 that is to say, one of the entities xyz found in main.adb is declared at
13573 line 12 of main.ads (and its body is in main.adb), and another one is
13574 declared at line 45 of foo.ads
13576 @item gnatfind -fs xyz:main.adb
13577 This is the same command as the previous one, instead @code{gnatfind} will
13578 display the content of the Ada source file lines.
13580 The output will look like:
13582 @smallexample
13583 directory/main.ads:106:14: xyz <= declaration
13584    procedure xyz;
13585 directory/main.adb:24:10: xyz <= body
13586    procedure xyz is
13587 directory/foo.ads:45:23: xyz <= declaration
13588    xyz : Integer;
13589 @end smallexample
13591 @noindent
13592 This can make it easier to find exactly the location your are looking
13593 for.
13595 @item gnatfind -r "*x*":main.ads:123 foo.adb
13596 Find references to all entities containing an x that are
13597 referenced on line 123 of main.ads.
13598 The references will be searched only in main.ads and foo.adb.
13600 @item gnatfind main.ads:123
13601 Find declarations and bodies for all entities that are referenced on
13602 line 123 of main.ads.
13604 This is the same as @code{gnatfind "*":main.adb:123}.
13606 @item gnatfind mydir/main.adb:123:45
13607 Find the declaration for the entity referenced at column 45 in
13608 line 123 of file main.adb in directory mydir. Note that it
13609 is usual to omit the identifier name when the column is given,
13610 since the column position identifies a unique reference.
13612 The column has to be the beginning of the identifier, and should not
13613 point to any character in the middle of the identifier.
13615 @end table
13617 @ifclear FSFEDITION
13618 @c *********************************
13619 @node The GNAT Pretty-Printer gnatpp
13620 @chapter The GNAT Pretty-Printer @command{gnatpp}
13621 @findex gnatpp
13622 @cindex Pretty-Printer
13624 @menu
13625 * Switches for gnatpp::
13626 * Formatting Rules::
13627 @end menu
13629 @noindent
13630 The @command{gnatpp} tool is an ASIS-based utility
13631 for source reformatting / pretty-printing.
13632 It takes an Ada source file as input and generates a reformatted
13633 version as output.
13634 You can specify various style directives via switches; e.g.,
13635 identifier case conventions, rules of indentation, and comment layout.
13637 Note: A newly-redesigned set of formatting algorithms used by gnatpp
13638 is now available.
13639 To invoke the old formatting algorithms, use the @option{--pp-old} switch.
13640 Support for @option{--pp-old} will be removed in some future version.
13642 To produce a reformatted file, @command{gnatpp} invokes the Ada
13643 compiler and generates and uses the ASIS tree for the input source;
13644 thus the input must be legal Ada code, and the tool should have all the
13645 information needed to compile the input source. To provide this information,
13646 you may specify as a tool parameter the project file the input source belongs to
13647 (or you may call @command{gnatpp}
13648 through the @command{gnat} driver (see @ref{The GNAT Driver and
13649 Project Files}). Another possibility is to specify the source search
13650 path and needed configuration files in @option{-cargs} section of @command{gnatpp}
13651 call, see the description of the @command{gnatpp} switches below.
13653 @command{gnatpp} cannot process sources that contain
13654 preprocessing directives.
13656 The @command{gnatpp} command has the form
13658 @smallexample
13659 @c $ gnatpp @ovar{switches} @var{filename}
13660 @c Expanding @ovar macro inline (explanation in macro def comments)
13661 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13662 @end smallexample
13664 @noindent
13665 where
13666 @itemize @bullet
13667 @item
13668 @var{switches} is an optional sequence of switches defining such properties as
13669 the formatting rules, the source search path, and the destination for the
13670 output source file
13672 @item
13673 @var{filename} is the name (including the extension) of the source file to
13674 reformat; wildcards or several file names on the same gnatpp command are
13675 allowed. The file name may contain path information; it does not have to
13676 follow the GNAT file naming rules
13678 @item
13679 @samp{@var{gcc_switches}} is a list of switches for
13680 @command{gcc}. They will be passed on to all compiler invocations made by
13681 @command{gnatpp} to generate the ASIS trees. Here you can provide
13682 @option{-I} switches to form the source search path,
13683 use the @option{-gnatec} switch to set the configuration file, etc.
13684 @end itemize
13686 @node Switches for gnatpp
13687 @section Switches for @command{gnatpp}
13689 @noindent
13690 The following subsections describe the various switches accepted by
13691 @command{gnatpp}, organized by category.
13693 You specify a switch by supplying a name and generally also a value.
13694 In many cases the values for a switch with a given name are incompatible with
13695 each other
13696 (for example the switch that controls the casing of a reserved word may have
13697 exactly one value: upper case, lower case, or
13698 mixed case) and thus exactly one such switch can be in effect for an
13699 invocation of @command{gnatpp}.
13700 If more than one is supplied, the last one is used.
13701 However, some values for the same switch are mutually compatible.
13702 You may supply several such switches to @command{gnatpp}, but then
13703 each must be specified in full, with both the name and the value.
13704 Abbreviated forms (the name appearing once, followed by each value) are
13705 not permitted.
13708 @menu
13709 * Alignment Control::
13710 * Casing Control::
13711 * General Text Layout Control::
13712 * Other Formatting Options::
13713 * Setting the Source Search Path::
13714 * Output File Control::
13715 * Other gnatpp Switches::
13716 @end menu
13718 @node Alignment Control
13719 @subsection Alignment Control
13720 @cindex Alignment control in @command{gnatpp}
13722 @noindent
13723 Programs can be easier to read if certain constructs are vertically aligned.
13724 By default alignment of the following constructs is set ON:
13725 @code{:} in declarations, @code{:=} in initializations in declarations
13726 @code{:=} in assignment statements, @code{=>} in associations, and
13727 @code{at} keywords in the component clauses in record
13728 representation clauses.
13730 @table @option
13731 @cindex @option{-A@var{n}} (@command{gnatpp})
13733 @item -A0
13734 Set alignment to OFF
13736 @item -A1
13737 Set alignment to ON
13738 @end table
13740 @node Casing Control
13741 @subsection Casing Control
13742 @cindex Casing control in @command{gnatpp}
13744 @noindent
13745 @command{gnatpp} allows you to specify the casing for reserved words,
13746 pragma names, attribute designators and identifiers.
13747 For identifiers you may define a
13748 general rule for name casing but also override this rule
13749 via a set of dictionary files.
13751 Three types of casing are supported: lower case, upper case, and mixed case.
13752 ``Mixed case'' means that the first letter, and also each letter immediately
13753 following an underscore, are converted to their uppercase forms;
13754 all the other letters are converted to their lowercase forms.
13756 @table @option
13757 @cindex @option{-a@var{x}} (@command{gnatpp})
13758 @item -aL
13759 Attribute designators are lower case
13761 @item -aU
13762 Attribute designators are upper case
13764 @item -aM
13765 Attribute designators are mixed case (this is the default)
13767 @cindex @option{-k@var{x}} (@command{gnatpp})
13768 @item -kL
13769 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13770 lower case (this is the default)
13772 @item -kU
13773 Keywords are upper case
13775 @cindex @option{-n@var{x}} (@command{gnatpp})
13776 @item -nD
13777 Name casing for defining occurrences are as they appear in the source file
13778 (this is the default)
13780 @item -nU
13781 Names are in upper case
13783 @item -nL
13784 Names are in lower case
13786 @item -nM
13787 Names are in mixed case
13789 @cindex @option{-ne@var{x}} (@command{gnatpp})
13790 @item -neD
13791 Enumeration literal casing for defining occurrences are as they appear in the
13792 source file. Overrides -n casing setting.
13794 @item -neU
13795 Enumeration literals are in upper case.  Overrides -n casing
13796 setting.
13798 @item -neL
13799 Enumeration literals are in lower case. Overrides -n casing
13800 setting.
13802 @item -neM
13803 Enumeration literals are in mixed case. Overrides -n casing
13804 setting.
13806 @cindex @option{-nt@var{x}} (@command{gnatpp})
13807 @item -neD
13808 Names introduced by type and subtype declarations are always
13809 cased as they appear in the declaration in the source file.
13810 Overrides -n casing setting.
13812 @item -ntU
13813 Names introduced by type and subtype declarations are always in
13814 upper case. Overrides -n casing setting.
13816 @item -ntL
13817 Names introduced by type and subtype declarations are always in
13818 lower case. Overrides -n casing setting.
13820 @item -ntM
13821 Names introduced by type and subtype declarations are always in
13822 mixed case. Overrides -n casing setting.
13824 @item -nnU
13825 Names introduced by number declarations are always in
13826 upper case. Overrides -n casing setting.
13828 @item -nnL
13829 Names introduced by number declarations are always in
13830 lower case. Overrides -n casing setting.
13832 @item -nnM
13833 Names introduced by number declarations are always in
13834 mixed case. Overrides -n casing setting.
13836 @cindex @option{-p@var{x}} (@command{gnatpp})
13837 @item -pL
13838 Pragma names are lower case
13840 @item -pU
13841 Pragma names are upper case
13843 @item -pM
13844 Pragma names are mixed case (this is the default)
13846 @item -D@var{file}
13847 @cindex @option{-D} (@command{gnatpp})
13848 Use @var{file} as a @emph{dictionary file} that defines
13849 the casing for a set of specified names,
13850 thereby overriding the effect on these names by
13851 any explicit or implicit
13852 -n switch.
13853 To supply more than one dictionary file,
13854 use several @option{-D} switches.
13856 @noindent
13857 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13858 to define the casing for the Ada predefined names and
13859 the names declared in the GNAT libraries.
13861 @item -D-
13862 @cindex @option{-D-} (@command{gnatpp})
13863 Do not use the default dictionary file;
13864 instead, use the casing
13865 defined by a @option{-n} switch and any explicit
13866 dictionary file(s)
13867 @end table
13869 @noindent
13870 The structure of a dictionary file, and details on the conventions
13871 used in the default dictionary file, are defined in @ref{Name Casing}.
13873 The @option{-D-} and
13874 @option{-D@var{file}} switches are mutually
13875 compatible.
13877 @noindent
13878 This group of @command{gnatpp} switches controls the layout of comments and
13879 complex syntactic constructs.  See @ref{Formatting Comments} for details
13880 on their effect.
13882 @table @option
13883 @cindex @option{-c@var{n}} (@command{gnatpp})
13884 @item -c0
13885 All comments remain unchanged.
13887 @item -c1
13888 GNAT-style comment line indentation.
13889 This is the default.
13891 @item -c3
13892 GNAT-style comment beginning.
13894 @item -c4
13895 Fill comment blocks.
13897 @item -c5
13898 Keep unchanged special form comments.
13899 This is the default.
13901 @item --comments-only
13902 @cindex @option{--comments-only} @command{gnatpp}
13903 Format just the comments.
13905 @cindex @option{--no-separate-is} (@command{gnatpp})
13906 @item --no-separate-is
13907 Do not place the keyword @code{is} on a separate line in a subprogram body in
13908 case if the spec occupies more than one line.
13910 @cindex @option{--separate-loop-then} (@command{gnatpp})
13911 @item --separate-loop-then
13912 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13913 keyword @code{then} in IF statements on a separate line.
13915 @cindex @option{--no-separate-loop-then} (@command{gnatpp})
13916 @item --no-separate-loop-then
13917 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13918 keyword @code{then} in IF statements on a separate line. This option is
13919 incompatible with @option{--separate-loop-then} option.
13921 @cindex @option{--use-on-new-line} (@command{gnatpp})
13922 @item --use-on-new-line
13923 Start each USE clause in a context clause from a separate line.
13925 @cindex @option{--insert-blank-lines} (@command{gnatpp})
13926 @item --insert-blank-lines
13927 Insert blank lines where appropriate (between bodies and other large
13928 constructs).
13930 @cindex @option{--preserve-blank-lines} (@command{gnatpp})
13931 @item --preserve-blank-lines
13932 Preserve blank lines in the input. By default, gnatpp will squeeze
13933 multiple blank lines down to one.
13935 @end table
13937 @noindent
13938 The @option{-c} switches are compatible with one another, except that
13939 the @option{-c0} switch disables all other comment formatting
13940 switches.
13943 @node General Text Layout Control
13944 @subsection General Text Layout Control
13946 @noindent
13947 These switches allow control over line length and indentation.
13949 @table @option
13950 @item -M@var{nnn}
13951 @cindex @option{-M} (@command{gnatpp})
13952 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13954 @item -i@var{nnn}
13955 @cindex @option{-i} (@command{gnatpp})
13956 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13958 @item -cl@var{nnn}
13959 @cindex @option{-cl} (@command{gnatpp})
13960 Indentation level for continuation lines (relative to the line being
13961 continued), @var{nnn} from 1@dots{}9.
13962 The default
13963 value is one less than the (normal) indentation level, unless the
13964 indentation is set to 1 (in which case the default value for continuation
13965 line indentation is also 1)
13966 @end table
13968 @node Other Formatting Options
13969 @subsection Other Formatting Options
13971 @noindent
13972 These switches control other formatting not listed above.
13974 @table @option
13975 @item --decimal-grouping=@var{n}
13976 @cindex @option{--decimal-grouping} @command{gnatpp}
13977 Put underscores in decimal literals (numeric literals without a base)
13978 every @var{n} characters. If a literal already has one or more
13979 underscores, it is not modified. For example, with
13980 @code{--decimal-grouping=3}, @code{1000000} will be changed to
13981 @code{1_000_000}.
13983 @item --based-grouping=@var{n}
13984 @cindex @option{--based-grouping} @command{gnatpp}
13985 Same as @code{--decimal-grouping}, but for based literals. For
13986 example, with @code{--based-grouping=4}, @code{16#0001FFFE#} will be
13987 changed to @code{16#0001_FFFE#}.
13989 @item --split-line-before-op
13990 @cindex @option{--split-line-before-op} (@command{gnatpp})
13991 If it is necessary to split a line at a binary operator, by default
13992 the line is split after the operator. With this option, it is split
13993 before the operator.
13995 @item --RM-style-spacing
13996 @cindex @option{--RM-style-spacing} (@command{gnatpp})
13997 Do not insert an extra blank before various occurrences of
13998 `(' and `:'. This also turns off alignment.
14000 @item -ff
14001 @cindex @option{-ff} (@command{gnatpp})
14002 Insert a Form Feed character after a pragma Page.
14004 @item --call_threshold=@var{nnn}
14005 @cindex @option{--call_threshold} (@command{gnatpp})
14006 If the number of parameter associations is greater than @var{nnn} and if at
14007 least one association uses named notation, start each association from
14008 a new line. If @var{nnn} is 0, no check for the number of associations
14009 is made; this is the default.
14011 @item --par_threshold=@var{nnn}
14012 @cindex @option{--par_threshold} (@command{gnatpp})
14013 If the number of parameter specifications is greater than @var{nnn}
14014 (or equal to @var{nnn} in case of a function), start each specification from
14015 a new line. This feature is disabled by default.
14016 @end table
14018 @node Setting the Source Search Path
14019 @subsection Setting the Source Search Path
14021 @noindent
14022 To define the search path for the input source file, @command{gnatpp}
14023 uses the same switches as the GNAT compiler, with the same effects:
14025 @table @option
14026 @item -I@var{dir}
14027 @cindex @option{-I} (@command{gnatpp})
14029 @item -I-
14030 @cindex @option{-I-} (@command{gnatpp})
14032 @item -gnatec=@var{path}
14033 @cindex @option{-gnatec} (@command{gnatpp})
14035 @end table
14037 @node Output File Control
14038 @subsection Output File Control
14040 @noindent
14041 By default the output is sent to a file whose name is obtained by appending
14042 the @file{.pp} suffix to the name of the input file.
14043 If the file with this name already exists, it is overwritten.
14044 Thus if the input file is @file{my_ada_proc.adb} then
14045 @command{gnatpp} will produce @file{my_ada_proc.adb.pp}
14046 as output file.
14047 The output may be redirected by the following switches:
14049 @table @option
14050 @item --output-dir=@var{dir}
14051 @cindex @option{--output-dir} (@command{gnatpp})
14052 Generate output file in directory @file{dir} with the same name as the input
14053 file. If @file{dir} is the same as the directory containing the input file,
14054 the input file is not processed; use @option{-rnb}
14055 if you want to update the input file in place.
14057 @item -pipe
14058 @cindex @option{-pipe} (@command{gnatpp})
14059 Send the output to @code{Standard_Output}
14061 @item -o @var{output_file}
14062 @cindex @option{-o} (@code{gnatpp})
14063 Write the output into @var{output_file}.
14064 If @var{output_file} already exists, @command{gnatpp} terminates without
14065 reading or processing the input file.
14067 @item -of @var{output_file}
14068 @cindex @option{-of} (@command{gnatpp})
14069 Write the output into @var{output_file}, overwriting the existing file
14070 (if one is present).
14072 @item -r
14073 @cindex @option{-r} (@command{gnatpp})
14074 Replace the input source file with the reformatted output, and copy the
14075 original input source into the file whose name is obtained by appending the
14076 @file{.npp} suffix to the name of the input file.
14077 If a file with this name already exists, @command{gnatpp} terminates without
14078 reading or processing the input file.
14080 @item -rf
14081 @cindex @option{-rf} (@code{gnatpp})
14082 Like @option{-r} except that if the file with the specified name
14083 already exists, it is overwritten.
14085 @item -rnb
14086 @cindex @option{-rnb} (@command{gnatpp})
14087 Replace the input source file with the reformatted output without
14088 creating any backup copy of the input source.
14090 @item --eol=@var{xxx}
14091 @cindex @option{--eol} (@code{gnatpp})
14092 Specifies the line-ending style of the reformatted output file. The @var{xxx}
14093 string specified with the switch may be:
14094 @itemize @bullet
14095 @item ``@option{dos}'' MS DOS style, lines end with CR LF characters
14096 @item ``@option{crlf}''
14097 the same as @option{dos}
14098 @item ``@option{unix}'' UNIX style, lines end with LF character
14099 @item ``@option{lf}''
14100 the same as @option{unix}
14101 @end itemize
14103 @item -W@var{e}
14104 @cindex @option{-W} (@command{gnatpp})
14105 Specify the wide character encoding method for the input and output files.
14106 @var{e} is one of the following:
14108 @itemize @bullet
14110 @item h
14111 Hex encoding
14113 @item u
14114 Upper half encoding
14116 @item s
14117 Shift/JIS encoding
14119 @item e
14120 EUC encoding
14122 @item 8
14123 UTF-8 encoding
14125 @item b
14126 Brackets encoding (default value)
14127 @end itemize
14129 @end table
14131 @noindent
14132 Options @option{-o} and
14133 @option{-of} are allowed only if the call to gnatpp
14134 contains only one file to reformat.
14135 Option
14136 @option{--eol}
14138 @option{-W}
14139 cannot be used together
14140 with @option{-pipe} option.
14142 @node Other gnatpp Switches
14143 @subsection Other @code{gnatpp} Switches
14145 @noindent
14146 The additional @command{gnatpp} switches are defined in this subsection.
14148 @table @option
14149 @item --version
14150 @cindex @option{--version} @command{gnatpp}
14151 Display copyright and version, then exit disregarding all other options.
14153 @item --help
14154 @cindex @option{--help} @command{gnatpp}
14155 Display usage, then exit disregarding all other options.
14157 @item -P @var{file}
14158 @cindex @option{-P} @command{gnatpp}
14159 Indicates the name of the project file that describes the set of sources
14160 to be processed. The exact set of argument sources depends on other options
14161 specified; see below.
14163 @item -U
14164 @cindex @option{-U} @command{gnatpp}
14165 If a project file is specified and no argument source is explicitly
14166 specified (either directly or by means of @option{-files} option), process
14167 all the units of the closure of the argument project. Otherwise this option
14168 has no effect.
14170 @item -U @var{main_unit}
14171 If a project file is specified and no argument source is explicitly
14172 specified (either directly or by means of @option{-files} option), process
14173 the closure of units rooted at @var{main_unit}. Otherwise this option
14174 has no effect.
14176 @item -X@var{name}=@var{value}
14177 @cindex @option{-X} @command{gnatpp}
14178 Indicates that external variable @var{name} in the argument project
14179 has the value @var{value}. Has no effect if no project is specified as
14180 tool argument.
14182 @item --RTS=@var{rts-path}
14183 @cindex @option{--RTS} (@command{gnatpp})
14184 Specifies the default location of the runtime library. Same meaning as the
14185 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14187 @item --incremental
14188 @cindex @option{--incremental} @command{gnatpp}
14189 Incremental processing on a per-file basis. Source files are only
14190 processed if they have been modified, or if files they depend on have
14191 been modified. This is similar to the way gnatmake/gprbuild only
14192 compiles files that need to be recompiled. A project file is required
14193 in this mode, and the gnat driver (as in @command{gnat pretty}) is not
14194 supported.
14196 @item --pp-off=@var{xxx}
14197 @cindex @option{--pp-off} @command{gnatpp}
14198 Use @code{--xxx} as the command to turn off pretty printing, instead
14199 of the default @code{--!pp off}.
14201 @item --pp-on=@var{xxx}
14202 @cindex @option{--pp-on} @command{gnatpp}
14203 Use @code{--xxx} as the command to turn pretty printing back on, instead
14204 of the default @code{--!pp on}.
14206 @item --pp-old
14207 @cindex @option{--pp-old} @command{gnatpp}
14208 Use the old formatting algorithms.
14210 @item -files @var{filename}
14211 @cindex @option{-files} (@code{gnatpp})
14212 Take the argument source files from the specified file. This file should be an
14213 ordinary text file containing file names separated by spaces or
14214 line breaks. You can use this switch more than once in the same call to
14215 @command{gnatpp}. You also can combine this switch with an explicit list of
14216 files.
14218 @item -j@var{n}
14219 @cindex @option{-j} (@command{gnatpp})
14220 Without @option{--incremental}, use @var{n} processes to carry out the
14221 tree creations (internal representations of the argument sources). On
14222 a multiprocessor machine this speeds up processing of big sets of
14223 argument sources. If @var{n} is 0, then the maximum number of parallel
14224 tree creations is the number of core processors on the platform. This
14225 option cannot be used together with @option{-r},
14226 @option{-rf} or
14227 @option{-rnb} option.
14229 With @option{--incremental}, use @var{n} @command{gnatpp} processes to
14230 perform pretty-printing in parallel. @var{n} = 0 means the same as
14231 above. In this case, @option{-r},
14232 @option{-rf} or
14233 @option{-rnb} options are allowed.
14235 @cindex @option{-t} (@command{gnatpp})
14236 @item -t
14237 Print out execution time.
14239 @item -v
14240 @cindex @option{-v} (@command{gnatpp})
14241 Verbose mode
14243 @item -q
14244 @cindex @option{-q} (@command{gnatpp})
14245 Quiet mode
14246 @end table
14248 @noindent
14249 If a project file is specified and no argument source is explicitly
14250 specified (either directly or by means of @option{-files} option), and no
14251 @option{-U} is specified, then the set of processed sources is
14252 all the immediate units of the argument project.
14255 @node Formatting Rules
14256 @section Formatting Rules
14258 @noindent
14259 The following subsections show how @command{gnatpp} treats white space,
14260 comments, program layout, and name casing.
14261 They provide detailed descriptions of the switches shown above.
14263 @menu
14264 * Disabling Pretty Printing::
14265 * White Space and Empty Lines::
14266 * Formatting Comments::
14267 * Name Casing::
14268 @end menu
14270 @node Disabling Pretty Printing
14271 @subsection Disabling Pretty Printing
14273 @noindent
14274 Pretty printing is highly heuristic in nature, and sometimes doesn't
14275 do exactly what you want. If you wish to format a certain region of
14276 code by hand, you can turn off pretty printing in that region by
14277 surrounding it with special comments that start with @code{--!pp off}
14278 and @code{--!pp on}. The text in that region will then be reproduced
14279 verbatim in the output with no formatting.
14281 To disable pretty printing for the whole file, put @code{--!pp off} at
14282 the top, with no following @code{--!pp on}.
14284 The comments must appear on a line by themselves, with nothing
14285 preceding except spaces. The initial text of the comment must be
14286 exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14287 be followed by arbitrary additional text. For example:
14289 @smallexample @c ada
14290 @cartouche
14291 @b{package} Interrupts @b{is}
14292    --@i{!pp off -- turn off pretty printing so "Interrupt_Kind" lines up}
14293    @b{type}            Interrupt_Kind @b{is}
14294      (Asynchronous_Interrupt_Kind,
14295        Synchronous_Interrupt_Kind,
14296              Green_Interrupt_Kind);
14297    --@i{!pp on -- reenable pretty printing}
14299    ...
14300 @end cartouche
14301 @end smallexample
14303 You can specify different comment strings using the @code{--pp-off}
14304 and @code{--pp-on} switches. For example, if you say @code{gnatpp
14305 --pp-off=' pp-' *.ad?} then gnatpp will recognize comments of the form
14306 @code{-- pp-} instead of @code{--!pp off} for disabling pretty
14307 printing. Note that the leading @code{--} of the comment is not
14308 included in the argument to these switches.
14310 @node White Space and Empty Lines
14311 @subsection White Space and Empty Lines
14313 @noindent
14314 @command{gnatpp} does not have an option to control space characters.
14315 It will add or remove spaces according to the style illustrated by the
14316 examples in the @cite{Ada Reference Manual}.
14317 The output file will contain no lines with trailing white space.
14319 By default, a sequence of one or more blank lines in the input is
14320 converted to a single blank line in the output; multiple blank lines
14321 are squeezed down to one.
14322 The @option{--preserve-blank-lines} option
14323 turns off the squeezing; each blank line in the input is copied
14324 to the output.
14325 The @option{--insert-blank-lines} option
14326 causes additional blank lines to be inserted if not already
14327 present in the input (e.g. between bodies).
14329 @node Formatting Comments
14330 @subsection Formatting Comments
14332 @noindent
14333 Comments in Ada code are of two kinds:
14334 @itemize @bullet
14335 @item
14336 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14337 white space) on a line
14339 @item
14340 an @emph{end-of-line comment}, which follows some other Ada code on
14341 the same line.
14342 @end itemize
14344 @noindent
14345 A whole-line comment is indented according to the surrounding code,
14346 with some exceptions.
14347 Comments that start in column 1 are kept there.
14348 If possible, comments are not moved so far to the right that the maximum
14349 line length is exceeded.
14350 The @option{-c0} option
14351 turns off comment formatting.
14352 Special-form comments such as SPARK-style @code{--#...} are left alone.
14354 For an end-of-line comment, @command{gnatpp} tries to leave the same
14355 number of spaces between the end of the preceding Ada code and the
14356 beginning of the comment as appear in the original source.
14358 @noindent
14359 The @option{-c3} switch
14360 (GNAT style comment beginning) has the following
14361 effect:
14363 @itemize @bullet
14364 @item
14365 For each whole-line comment that does not end with two hyphens,
14366 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14367 to ensure that there are at least two spaces between these hyphens and the
14368 first non-blank character of the comment.
14369 @end itemize
14371 @noindent
14372 The @option{-c4} switch specifies that
14373 whole-line comments that form a paragraph will be filled in typical
14374 word processor style (that is, moving words between lines to make the
14375 lines other than the last similar in length ).
14377 @noindent
14378 The @option{--comments-only} switch specifies that only the comments
14379 are formatted; the rest of the program text is left alone. The
14380 comments are formatted according to the -c3 and -c4 switches; other
14381 formatting switches are ignored. For example, @option{--comments-only
14382 -c4} means to fill comment paragraphs, and do nothing else. Likewise,
14383 @option{--comments-only -c3} ensures comments start with at least two
14384 spaces after @code{--}, and @option{--comments-only -c3 -c4} does
14385 both. If @option{--comments-only} is given without @option{-c3} or
14386 @option{-c4}, then gnatpp doesn't format anything.
14388 @node Name Casing
14389 @subsection Name Casing
14391 @noindent
14392 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14393 the same casing as the corresponding defining identifier.
14395 You control the casing for defining occurrences via the
14396 @option{-n} switch.
14397 With @option{-nD} (``as declared'', which is the default),
14398 defining occurrences appear exactly as in the source file
14399 where they are declared.
14400 The other values for this switch ---
14401 @option{-nU},
14402 @option{-nL},
14403 @option{-nM} ---
14404 result in
14405 upper, lower, or mixed case, respectively.
14406 If @command{gnatpp} changes the casing of a defining
14407 occurrence, it analogously changes the casing of all the
14408 usage occurrences of this name.
14410 If the defining occurrence of a name is not in the source compilation unit
14411 currently being processed by @command{gnatpp}, the casing of each reference to
14412 this name is changed according to the value of the @option{-n}
14413 switch (subject to the dictionary file mechanism described below).
14414 Thus @command{gnatpp} acts as though the @option{-n} switch
14415 had affected the
14416 casing for the defining occurrence of the name.
14418 The options
14419 @option{-a@var{x}},
14420 @option{-k@var{x}},
14421 @option{-ne@var{x}},
14422 @option{-nt@var{x}},
14423 @option{-nn@var{x}}, and
14424 @option{-p@var{x}}
14425 allow finer-grained control over casing for
14426 attributes, keywords, enumeration literals,
14427 types, named numbers and pragmas, respectively.
14428 @option{-nt@var{x}} covers subtypes and
14429 task and protected bodies as well.
14431 Some names may need to be spelled with casing conventions that are not
14432 covered by the upper-, lower-, and mixed-case transformations.
14433 You can arrange correct casing by placing such names in a
14434 @emph{dictionary file},
14435 and then supplying a @option{-D} switch.
14436 The casing of names from dictionary files overrides
14437 any @option{-n} switch.
14439 To handle the casing of Ada predefined names and the names from GNAT libraries,
14440 @command{gnatpp} assumes a default dictionary file.
14441 The name of each predefined entity is spelled with the same casing as is used
14442 for the entity in the @cite{Ada Reference Manual} (usually mixed case).
14443 The name of each entity in the GNAT libraries is spelled with the same casing
14444 as is used in the declaration of that entity.
14446 The @w{@option{-D-}} switch suppresses the use of
14447 the default dictionary file. Instead, the casing for predefined and
14448 GNAT-defined names will be established by the
14449 @option{-n} switch or explicit dictionary files. For
14450 example, by default the names @code{Ada.Text_IO} and
14451 @code{GNAT.OS_Lib} will appear as just shown, even in the presence of
14452 a @option{-nU} switch.  To ensure that even
14453 such names are rendered in uppercase, additionally supply the
14454 @w{@option{-D-}} switch (or else place these names
14455 in upper case in a dictionary file).
14457 A dictionary file is a plain text file; each line in this file can be
14458 either a blank line (containing only space characters), an Ada comment
14459 line, or the specification of exactly one @emph{casing schema}.
14461 A casing schema is a string that has the following syntax:
14463 @smallexample
14464 @cartouche
14465   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14467   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14468 @end cartouche
14469 @end smallexample
14471 @noindent
14472 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14473 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14475 The casing schema string can be followed by white space and/or an Ada-style
14476 comment; any amount of white space is allowed before the string.
14478 If a dictionary file is passed as
14479 the value of a @option{-D@var{file}} switch
14480 then for every
14481 simple name and every identifier, @command{gnatpp} checks if the dictionary
14482 defines the casing for the name or for some of its parts (the term ``subword''
14483 is used below to denote the part of a name which is delimited by ``_'' or by
14484 the beginning or end of the word and which does not contain any ``_'' inside):
14486 @itemize @bullet
14487 @item
14488 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14489 the casing defined by the dictionary; no subwords are checked for this word
14491 @item
14492 for every subword @command{gnatpp} checks if the dictionary contains the
14493 corresponding string of the form @code{*@var{simple_identifier}*},
14494 and if it does, the casing of this @var{simple_identifier} is used
14495 for this subword
14497 @item
14498 if the whole name does not contain any ``_'' inside, and if for this name
14499 the dictionary contains two entries - one of the form @var{identifier},
14500 and another - of the form *@var{simple_identifier}*, then the first one
14501 is applied to define the casing of this name
14503 @item
14504 if more than one dictionary file is passed as @command{gnatpp} switches, each
14505 dictionary adds new casing exceptions and overrides all the existing casing
14506 exceptions set by the previous dictionaries
14508 @item
14509 when @command{gnatpp} checks if the word or subword is in the dictionary,
14510 this check is not case sensitive
14511 @end itemize
14513 @noindent
14514 For example, suppose we have the following source to reformat:
14516 @smallexample @c ada
14517 @cartouche
14518 @b{procedure} test @b{is}
14519    name1 : integer := 1;
14520    name4_name3_name2 : integer := 2;
14521    name2_name3_name4 : Boolean;
14522    name1_var : Float;
14523 @b{begin}
14524    name2_name3_name4 := name4_name3_name2 > name1;
14525 @b{end};
14526 @end cartouche
14527 @end smallexample
14529 @noindent
14530 And suppose we have two dictionaries:
14532 @smallexample
14533 @cartouche
14534 @i{dict1:}
14535    NAME1
14536    *NaMe3*
14537    *Name1*
14538 @end cartouche
14540 @cartouche
14541 @i{dict2:}
14542   *NAME3*
14543 @end cartouche
14544 @end smallexample
14546 @noindent
14547 If @command{gnatpp} is called with the following switches:
14549 @smallexample
14550 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14551 @end smallexample
14553 @noindent
14554 then we will get the following name casing in the @command{gnatpp} output:
14556 @smallexample @c ada
14557 @cartouche
14558 @b{procedure} Test @b{is}
14559    NAME1             : Integer := 1;
14560    Name4_NAME3_Name2 : Integer := 2;
14561    Name2_NAME3_Name4 : Boolean;
14562    Name1_Var         : Float;
14563 @b{begin}
14564    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14565 @b{end} Test;
14566 @end cartouche
14567 @end smallexample
14568 @end ifclear
14570 @ifclear FSFEDITION
14571 @c *********************************
14572 @node The Ada-to-XML converter gnat2xml
14573 @chapter The Ada-to-XML converter @command{gnat2xml}
14574 @findex gnat2xml
14575 @cindex XML generation
14577 @noindent
14578 The @command{gnat2xml} tool is an ASIS-based utility that converts
14579 Ada source code into XML.
14581 @menu
14582 * Switches for gnat2xml::
14583 * Other Programs::
14584 * Structure of the XML::
14585 * Generating Representation Clauses::
14586 @end menu
14588 @node Switches for gnat2xml
14589 @section Switches for @command{gnat2xml}
14591 @noindent
14592 @command{gnat2xml} takes Ada source code as input, and produces XML
14593 that conforms to the schema.
14595 Usage:
14597 @smallexample
14598 gnat2xml [options] filenames [-files filename] [-cargs gcc_switches]
14599 @end smallexample
14601 @noindent
14602 options:
14603 @smallexample
14605 --help -- generate usage information and quit, ignoring all other options
14606 --version -- print version and quit, ignoring all other options
14608 -P @file{file} -- indicates the name of the project file that describes
14609       the set of sources to be processed. The exact set of argument
14610       sources depends on other options specified, see below.
14612 -U -- if a project file is specified and no argument source is explicitly
14613       specified, process all the units of the closure of the argument project.
14614       Otherwise this option has no effect.
14616 -U @var{main_unit} -- if a project file is specified and no argument source
14617       is explicitly specified (either directly or by means of @option{-files}
14618       option), process the closure of units rooted at @var{main_unit}.
14619       Otherwise this option has no effect.
14621 -X@var{name}=@var{value} -- indicates that external variable @var{name} in
14622       the argument project has the value @var{value}. Has no effect if no
14623       project is specified as tool argument.
14625 --RTS=@var{rts-path}  -- Specifies the default location of the runtime
14626       library. Same meaning as the equivalent @command{gnatmake} flag
14627       (@pxref{Switches for gnatmake}).
14629 --incremental -- incremental processing on a per-file basis. Source files are
14630       only processed if they have been modified, or if files they depend
14631       on have been modified. This is similar to the way gnatmake/gprbuild
14632       only compiles files that need to be recompiled. A project file
14633       is required in this mode.
14635 -j@var{n} -- In @option{--incremental} mode, use @var{n} @command{gnat2xml}
14636       processes to perform XML generation in parallel. If @var{n} is 0, then
14637       the maximum number of parallel tree creations is the number of core
14638       processors on the platform.
14640 --output-dir=@var{dir} -- generate one .xml file for each Ada source file, in
14641       directory @file{dir}. (Default is to generate the XML to standard
14642       output.)
14644 -I <include-dir>
14645       directories to search for dependencies
14646       You can also set the ADA_INCLUDE_PATH environment variable for this.
14648 --compact -- debugging version, with interspersed source, and a more
14649       compact representation of "sloc". This version does not conform
14650       to any schema.
14652 --rep-clauses -- generate representation clauses (see ``Generating
14653       Representation Clauses'' below).
14655 -files=filename - the name of a text file containing a list
14656                   of Ada source files to process
14658 -q -- quiet
14659 -v -- verbose
14661 -cargs ... -- options to pass to gcc
14662 @end smallexample
14664 @noindent
14665 If a project file is specified and no argument source is explicitly
14666 specified, and no @option{-U} is specified, then the set of processed
14667 sources is all the immediate units of the argument project.
14669 Example:
14671 @smallexample
14672 gnat2xml -v -output-dir=xml-files *.ad[sb]
14673 @end smallexample
14675 @noindent
14676 The above will create *.xml files in the @file{xml-files} subdirectory.
14677 For example, if there is an Ada package Mumble.Dumble, whose spec and
14678 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
14679 the above will produce xml-files/mumble-dumble.ads.xml and
14680 xml-files/mumble-dumble.adb.xml.
14682 @node Other Programs
14683 @section Other Programs
14685 @noindent
14686 The distribution includes two other programs that are related to
14687 @command{gnat2xml}:
14689 @command{gnat2xsd} is the schema generator, which generates the schema
14690 to standard output, based on the structure of Ada as encoded by
14691 ASIS. You don't need to run @command{gnat2xsd} in order to use
14692 @command{gnat2xml}. To generate the schema, type:
14694 @smallexample
14695 gnat2xsd > ada-schema.xsd
14696 @end smallexample
14698 @noindent
14699 @command{gnat2xml} generates XML files that will validate against
14700 @file{ada-schema.xsd}.
14702 @command{xml2gnat} is a back-translator that translates the XML back
14703 into Ada source code. The Ada generated by @command{xml2gnat} has
14704 identical semantics to the original Ada code passed to
14705 @command{gnat2xml}. It is not textually identical, however --- for
14706 example, no attempt is made to preserve the original indentation.
14708 @node Structure of the XML
14709 @section Structure of the XML
14711 @noindent
14712 The primary documentation for the structure of the XML generated by
14713 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
14714 following documentation gives additional details needed to understand
14715 the schema and therefore the XML.
14717 The elements listed under Defining Occurrences, Usage Occurrences, and
14718 Other Elements represent the syntactic structure of the Ada program.
14719 Element names are given in lower case, with the corresponding element
14720 type Capitalized_Like_This. The element and element type names are
14721 derived directly from the ASIS enumeration type Flat_Element_Kinds,
14722 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
14723 removed. For example, the ASIS enumeration literal
14724 An_Assignment_Statement corresponds to the XML element
14725 assignment_statement of XML type Assignment_Statement.
14727 To understand the details of the schema and the corresponding XML, it is
14728 necessary to understand the ASIS standard, as well as the GNAT-specific
14729 extension to ASIS.
14731 A defining occurrence is an identifier (or character literal or operator
14732 symbol) declared by a declaration. A usage occurrence is an identifier
14733 (or ...) that references such a declared entity. For example, in:
14735 @smallexample
14736 type T is range 1..10;
14737 X, Y : constant T := 1;
14738 @end smallexample
14740 @noindent
14741 The first ``T'' is the defining occurrence of a type. The ``X'' is the
14742 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
14743 a usage occurrence referring to the defining occurrence of T.
14745 Each element has a 'sloc' (source location), and subelements for each
14746 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
14747 The types of subelements are as defined in the ASIS standard. For
14748 example, for the right-hand side of an assignment_statement we have
14749 the following comment in asis-statements.ads:
14751 @smallexample
14752 ------------------------------------------------------------------------------
14753 --  18.3  function Assignment_Expression
14754 ------------------------------------------------------------------------------
14756    function Assignment_Expression
14757      (Statement : Asis.Statement)
14758       return      Asis.Expression;
14760 ------------------------------------------------------------------------------
14762 --  Returns the expression from the right hand side of the assignment.
14764 --  Returns Element_Kinds:
14765 --       An_Expression
14766 @end smallexample
14768 @noindent
14769 The corresponding sub-element of type Assignment_Statement is:
14771 @smallexample
14772 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
14773 @end smallexample
14775 @noindent
14776 where Expression_Class is defined by an xsd:choice of all the
14777 various kinds of expression.
14779 The 'sloc' of each element indicates the starting and ending line and
14780 column numbers. Column numbers are character counts; that is, a tab
14781 counts as 1, not as however many spaces it might expand to.
14783 Subelements of type Element have names ending in ``_q'' (for ASIS
14784 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
14785 List'').
14787 Some subelements are ``Boolean''. For example, Private_Type_Definition
14788 has has_abstract_q and has_limited_q, to indicate whether those
14789 keywords are present, as in @code{type T is abstract limited
14790 private;}. False is represented by a Nil_Element. True is represented
14791 by an element type specific to that query (for example, Abstract and
14792 Limited).
14794 The root of the tree is a Compilation_Unit, with attributes:
14796 @itemize @bullet
14797 @item
14798 unit_kind, unit_class, and unit_origin. These are strings that match the
14799 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
14800 in package Asis.
14802 @item
14803 unit_full_name is the full expanded name of the unit, starting from a
14804 root library unit. So for @code{package P.Q.R is ...},
14805 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
14807 @item
14808 def_name is the same as unit_full_name for library units; for subunits,
14809 it is just the simple name.
14811 @item
14812 source_file is the name of the Ada source file. For example, for
14813 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
14814 interpret the source locations --- the ``sloc'' of all elements
14815 within this Compilation_Unit refers to line and column numbers
14816 within the named file.
14817 @end itemize
14819 @noindent
14820 Defining occurrences have these attributes:
14822 @itemize @bullet
14823 @item
14824 def_name is the simple name of the declared entity, as written in the Ada
14825 source code.
14827 @item
14828 def is a unique URI of the form:
14830  ada://kind/fully/qualified/name
14832 where:
14834  kind indicates the kind of Ada entity being declared (see below), and
14836  fully/qualified/name, is the fully qualified name of the Ada
14837  entity, with each of ``fully'', ``qualified'', and ``name'' being
14838  mangled for uniqueness. We do not document the mangling
14839  algorithm, which is subject to change; we just guarantee that the
14840  names are unique in the face of overloading.
14842 @item
14843 type is the type of the declared object, or @code{null} for
14844 declarations of things other than objects.
14845 @end itemize
14847 @noindent
14848 Usage occurrences have these attributes:
14850 @itemize @bullet
14851 @item
14852 ref_name is the same as the def_name of the corresponding defining
14853 occurrence. This attribute is not of much use, because of
14854 overloading; use ref for lookups, instead.
14856 @item
14857 ref is the same as the def of the corresponding defining
14858 occurrence.
14859 @end itemize
14861 @noindent
14862 In summary, @code{def_name} and @code{ref_name} are as in the source
14863 code of the declaration, possibly overloaded, whereas @code{def} and
14864 @code{ref} are unique-ified.
14866 Literal elements have this attribute:
14868 @itemize @bullet
14869 @item
14870 lit_val is the value of the literal as written in the source text,
14871 appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
14872 only to numeric and string literals. Enumeration literals in Ada are
14873 not really "literals" in the usual sense; they are usage occurrences,
14874 and have ref_name and ref as described above. Note also that string
14875 literals used as operator symbols are treated as defining or usage
14876 occurrences, not as literals.
14877 @end itemize
14879 @noindent
14880 Elements that can syntactically represent names and expressions (which
14881 includes usage occurrences, plus function calls and so forth) have this
14882 attribute:
14884 @itemize @bullet
14885 @item
14886 type. If the element represents an expression or the name of an object,
14887 'type' is the 'def' for the defining occurrence of the type of that
14888 expression or name. Names of other kinds of entities, such as package
14889 names and type names, do not have a type in Ada; these have type="null"
14890 in the XML.
14891 @end itemize
14893 @noindent
14894 Pragma elements have this attribute:
14896 @itemize @bullet
14897 @item
14898 pragma_name is the name of the pragma. For language-defined pragmas, the
14899 pragma name is redundant with the element kind (for example, an
14900 assert_pragma element necessarily has pragma_name="Assert"). However, all
14901 implementation-defined pragmas are lumped together in ASIS as a single
14902 element kind (for example, the GNAT-specific pragma Unreferenced is
14903 represented by an implementation_defined_pragma element with
14904 pragma_name="Unreferenced").
14905 @end itemize
14907 @noindent
14908 Defining occurrences of formal parameters and generic formal objects have this
14909 attribute:
14911 @itemize @bullet
14912 @item
14913 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
14914 @end itemize
14916 @noindent
14917 All elements other than Not_An_Element have this attribute:
14919 @itemize @bullet
14920 @item
14921 checks is a comma-separated list of run-time checks that are needed
14922 for that element. The possible checks are: do_accessibility_check,
14923 do_discriminant_check,do_division_check,do_length_check,
14924 do_overflow_check,do_range_check,do_storage_check,do_tag_check.
14925 @end itemize
14927 @noindent
14928 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
14929 enumeration type Flat_Declaration_Kinds, declared in
14930 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
14931 any trailing "_Declaration" or "_Specification" removed. Thus, the
14932 possible kinds are as follows:
14934 @smallexample
14935 ordinary_type
14936 task_type
14937 protected_type
14938 incomplete_type
14939 tagged_incomplete_type
14940 private_type
14941 private_extension
14942 subtype
14943 variable
14944 constant
14945 deferred_constant
14946 single_task
14947 single_protected
14948 integer_number
14949 real_number
14950 enumeration_literal
14951 discriminant
14952 component
14953 loop_parameter
14954 generalized_iterator
14955 element_iterator
14956 procedure
14957 function
14958 parameter
14959 procedure_body
14960 function_body
14961 return_variable
14962 return_constant
14963 null_procedure
14964 expression_function
14965 package
14966 package_body
14967 object_renaming
14968 exception_renaming
14969 package_renaming
14970 procedure_renaming
14971 function_renaming
14972 generic_package_renaming
14973 generic_procedure_renaming
14974 generic_function_renaming
14975 task_body
14976 protected_body
14977 entry
14978 entry_body
14979 entry_index
14980 procedure_body_stub
14981 function_body_stub
14982 package_body_stub
14983 task_body_stub
14984 protected_body_stub
14985 exception
14986 choice_parameter
14987 generic_procedure
14988 generic_function
14989 generic_package
14990 package_instantiation
14991 procedure_instantiation
14992 function_instantiation
14993 formal_object
14994 formal_type
14995 formal_incomplete_type
14996 formal_procedure
14997 formal_function
14998 formal_package
14999 formal_package_declaration_with_box
15000 @end smallexample
15002 @node Generating Representation Clauses
15003 @section Generating Representation Clauses
15005 @noindent
15006 If the @option{--rep-clauses} switch is given, @command{gnat2xml} will
15007 generate representation clauses for certain types showing the
15008 representation chosen by the compiler. The information is produced by
15009 the ASIS ``Data Decomposition'' facility --- see the
15010 @code{Asis.Data_Decomposition} package for details.
15012 Not all types are supported. For example, @code{Type_Model_Kind} must
15013 be @code{A_Simple_Static_Model}. Types declared within generic units
15014 have no representation. The clauses that are generated include
15015 @code{attribute_definition_clauses} for @code{Size} and
15016 @code{Component_Size}, as well as
15017 @code{record_representation_clauses}.
15019 There is no guarantee that the generated representation clauses could
15020 have actually come from legal Ada code; Ada has some restrictions that
15021 are not necessarily obeyed by the generated clauses.
15023 The representation clauses are surrounded by comment elements to
15024 indicate that they are automatically generated, something like this:
15026 @smallexample
15027 <comment text="--gen+">
15029 <attribute_definition_clause>
15031 <comment text="--gen-">
15033 @end smallexample
15035 @end ifclear
15037 @ifclear FSFEDITION
15038 @c *********************************
15039 @node The GNAT Metrics Tool gnatmetric
15040 @chapter The GNAT Metrics Tool @command{gnatmetric}
15041 @findex gnatmetric
15042 @cindex Metric tool
15044 @noindent
15045 The @command{gnatmetric} tool is an ASIS-based utility
15046 for computing various program metrics.
15047 It takes an Ada source file as input and generates a file containing the
15048 metrics data as output. Various switches control which
15049 metrics are computed and output.
15051 @menu
15052 * Switches for gnatmetric::
15053 @end menu
15055 To compute program metrics, @command{gnatmetric} invokes the Ada
15056 compiler and generates and uses the ASIS tree for the input source;
15057 thus the input must be legal Ada code, and the tool should have all the
15058 information needed to compile the input source. To provide this information,
15059 you may specify as a tool parameter the project file the input source belongs to
15060 (or you may call @command{gnatmetric}
15061 through the @command{gnat} driver (see @ref{The GNAT Driver and
15062 Project Files}). Another possibility is to specify the source search
15063 path and needed configuration files in @option{-cargs} section of @command{gnatmetric}
15064 call, see the description of the @command{gnatmetric} switches below.
15066 If the set of sources to be processed by @code{gnatmetric} contains sources with
15067 preprocessing directives
15068 then the needed options should be provided to run preprocessor as a part of
15069 the @command{gnatmetric} call, and the computed metrics
15070 will correspond to preprocessed sources.
15073 The @command{gnatmetric} command has the form
15075 @smallexample
15076 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15077 @c Expanding @ovar macro inline (explanation in macro def comments)
15078 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15079 @end smallexample
15081 @noindent
15082 where
15083 @itemize @bullet
15084 @item
15085 @var{switches} specify the metrics to compute and define the destination for
15086 the output
15088 @item
15089 Each @var{filename} is the name (including the extension) of a source
15090 file to process. ``Wildcards'' are allowed, and
15091 the file name may contain path information.
15092 If no @var{filename} is supplied, then the @var{switches} list must contain
15093 at least one
15094 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15095 Including both a @option{-files} switch and one or more
15096 @var{filename} arguments is permitted.
15098 @item
15099 @samp{@var{gcc_switches}} is a list of switches for
15100 @command{gcc}. They will be passed on to all compiler invocations made by
15101 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15102 @option{-I} switches to form the source search path,
15103 and use the @option{-gnatec} switch to set the configuration file,
15104 use the @option{-gnat05} switch if sources should be compiled in
15105 Ada 2005 mode etc.
15106 @end itemize
15108 @node Switches for gnatmetric
15109 @section Switches for @command{gnatmetric}
15111 @noindent
15112 The following subsections describe the various switches accepted by
15113 @command{gnatmetric}, organized by category.
15115 @menu
15116 * Output Files Control::
15117 * Disable Metrics For Local Units::
15118 * Specifying a set of metrics to compute::
15119 * Other gnatmetric Switches::
15120 @ignore
15121 * Generate project-wide metrics::
15122 @end ignore
15123 @end menu
15125 @node Output Files Control
15126 @subsection Output File Control
15127 @cindex Output file control in @command{gnatmetric}
15129 @noindent
15130 @command{gnatmetric} has two output formats. It can generate a
15131 textual (human-readable) form, and also XML. By default only textual
15132 output is generated.
15134 When generating the output in textual form, @command{gnatmetric} creates
15135 for each Ada source file a corresponding text file
15136 containing the computed metrics, except for the case when the set of metrics
15137 specified by gnatmetric parameters consists only of metrics that are computed
15138 for the whole set of analyzed sources, but not for each Ada source.
15139 By default, the name of the file containing metric information for a source
15140 is obtained by appending the @file{.metrix} suffix to the
15141 name of the input source file. If not otherwise specified and no project file
15142 is specified as @command{gnatmetric} option this file is placed in the same
15143 directory as where the source file is located. If @command{gnatmetric} has a
15144 project  file as its parameter, it places all the generated files in the
15145 object directory of the project (or in the project source directory if the
15146 project does not define an objects directory), if @option{--subdirs} option
15147 is specified, the files are placed in the subrirectory of this directory
15148 specified by this option.
15150 All the output information generated in XML format is placed in a single
15151 file. By default the name of this file is @file{metrix.xml}.
15152 If not otherwise specified and if no project file is specified
15153 as @command{gnatmetric} option  this file is placed in the
15154 current directory.
15156 Some of the computed metrics are summed over the units passed to
15157 @command{gnatmetric}; for example, the total number of lines of code.
15158 By default this information is sent to @file{stdout}, but a file
15159 can be specified with the @option{-og} switch.
15161 The following switches control the @command{gnatmetric} output:
15163 @table @option
15164 @cindex @option{-x} (@command{gnatmetric})
15165 @item -x
15166 Generate the XML output
15168 @cindex @option{-xs} (@command{gnatmetric})
15169 @item -xs
15170 Generate the XML output and the XML schema file that describes the structure
15171 of the XML metric report, this schema is assigned to the XML file. The schema
15172 file has the same name as the XML output file with @file{.xml} suffix replaced
15173 with @file{.xsd}
15175 @cindex @option{-nt} (@command{gnatmetric})
15176 @item -nt
15177 Do not generate the output in text form (implies @option{-x})
15179 @cindex @option{-d} (@command{gnatmetric})
15180 @item -d @var{output_dir}
15181 Put text files with detailed metrics into @var{output_dir}
15183 @cindex @option{-o} (@command{gnatmetric})
15184 @item -o @var{file_suffix}
15185 Use @var{file_suffix}, instead of @file{.metrix}
15186 in the name of the output file.
15188 @cindex @option{-og} (@command{gnatmetric})
15189 @item -og @var{file_name}
15190 Put global metrics into @var{file_name}
15192 @cindex @option{-ox} (@command{gnatmetric})
15193 @item -ox @var{file_name}
15194 Put the XML output into @var{file_name} (also implies @option{-x})
15196 @cindex @option{-sfn} (@command{gnatmetric})
15197 @item -sfn
15198 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15199 output includes the name(s) of the Ada source file(s) from which the metrics
15200 are computed.  By default each name includes the absolute path. The
15201 @option{-sfn} switch causes @command{gnatmetric}
15202 to exclude all directory information from the file names that are output.)
15204 @end table
15206 @node Disable Metrics For Local Units
15207 @subsection Disable Metrics For Local Units
15208 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15210 @noindent
15211 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15212 one compilation
15213 unit per one source file. It computes line metrics for the whole source
15214 file, and it also computes syntax
15215 and complexity metrics for the file's outermost unit.
15217 By default, @command{gnatmetric} will also compute all metrics for certain
15218 kinds of locally declared program units:
15220 @itemize @bullet
15221 @item
15222 subprogram (and generic subprogram) bodies;
15224 @item
15225 package (and generic package) specs and bodies;
15227 @item
15228 task object and type specifications and bodies;
15230 @item
15231 protected object and type specifications and bodies.
15232 @end itemize
15234 @noindent
15235 These kinds of entities will be referred to as
15236 @emph{eligible local program units}, or simply @emph{eligible local units},
15237 @cindex Eligible local unit (for @command{gnatmetric})
15238 in the discussion below.
15240 Note that a subprogram declaration, generic instantiation,
15241 or renaming declaration only receives metrics
15242 computation when it appear as the outermost entity
15243 in a source file.
15245 Suppression of metrics computation for eligible local units can be
15246 obtained via the following switch:
15248 @table @option
15249 @cindex @option{-nolocal} (@command{gnatmetric})
15250 @item -nolocal
15251 Do not compute detailed metrics for eligible local program units
15253 @end table
15255 @node Specifying a set of metrics to compute
15256 @subsection Specifying a set of metrics to compute
15258 @noindent
15259 By default all the metrics are computed and reported. The switches
15260 described in this subsection allow you to control, on an individual
15261 basis, whether metrics are computed and
15262 reported. If at least one positive metric
15263 switch is specified (that is, a switch that defines that a given
15264 metric or set of metrics is to be computed), then only
15265 explicitly specified metrics are reported.
15267 @menu
15268 * Line Metrics Control::
15269 * Syntax Metrics Control::
15270 * Complexity Metrics Control::
15271 * Coupling Metrics Control::
15272 @end menu
15274 @node Line Metrics Control
15275 @subsubsection Line Metrics Control
15276 @cindex Line metrics control in @command{gnatmetric}
15278 @noindent
15279 For any (legal) source file, and for each of its
15280 eligible local program units, @command{gnatmetric} computes the following
15281 metrics:
15283 @itemize @bullet
15284 @item
15285 the total number of lines;
15287 @item
15288 the total number of code lines (i.e., non-blank lines that are not comments)
15290 @item
15291 the number of comment lines
15293 @item
15294 the number of code lines containing end-of-line comments;
15296 @item
15297 the comment percentage: the ratio between the number of lines that contain
15298 comments and the number of all non-blank lines, expressed as a percentage;
15300 @item
15301 the number of empty lines and lines containing only space characters and/or
15302 format effectors (blank lines)
15304 @item
15305 the average number of code lines in subprogram bodies, task bodies, entry
15306 bodies and statement sequences in package bodies (this metric is only computed
15307 across the whole set of the analyzed units)
15309 @end itemize
15311 @noindent
15312 @command{gnatmetric} sums the values of the line metrics for all the
15313 files being processed and then generates the cumulative results. The tool
15314 also computes for all the files being processed the average number of code
15315 lines in bodies.
15317 You can use the following switches to select the specific line metrics
15318 to be computed and reported.
15320 @table @option
15321 @cindex @option{--lines@var{x}} (@command{gnatmetric})
15323 @cindex @option{--no-lines@var{x}}
15325 @item --lines-all
15326 Report all the line metrics
15328 @item --no-lines-all
15329 Do not report any of line metrics
15331 @item --lines
15332 Report the number of all lines
15334 @item --no-lines
15335 Do not report the number of all lines
15337 @item --lines-code
15338 Report the number of code lines
15340 @item --no-lines-code
15341 Do not report the number of code lines
15343 @item --lines-comment
15344 Report the number of comment lines
15346 @item --no-lines-comment
15347 Do not report the number of comment lines
15349 @item --lines-eol-comment
15350 Report the number of code lines containing
15351 end-of-line comments
15353 @item --no-lines-eol-comment
15354 Do not report the number of code lines containing
15355 end-of-line comments
15357 @item --lines-ratio
15358 Report the comment percentage in the program text
15360 @item --no-lines-ratio
15361 Do not report the comment percentage in the program text
15363 @item --lines-blank
15364 Report the number of blank lines
15366 @item --no-lines-blank
15367 Do not report the number of blank lines
15369 @item --lines-average
15370 Report the average number of code lines in subprogram bodies, task bodies,
15371 entry bodies and statement sequences in package bodies. The metric is computed
15372 and reported for the whole set of processed Ada sources only.
15374 @item --no-lines-average
15375 Do not report the average number of code lines in subprogram bodies,
15376 task bodies, entry bodies and statement sequences in package bodies.
15378 @end table
15380 @node Syntax Metrics Control
15381 @subsubsection Syntax Metrics Control
15382 @cindex Syntax metrics control in @command{gnatmetric}
15384 @noindent
15385 @command{gnatmetric} computes various syntactic metrics for the
15386 outermost unit and for each eligible local unit:
15388 @table @emph
15389 @item LSLOC (``Logical Source Lines Of Code'')
15390 The total number of declarations and the total number of statements. Note
15391 that the definition of declarations is the one given in the reference
15392 manual:
15394 @noindent
15395 ``Each of the following is defined to be a declaration: any basic_declaration;
15396 an enumeration_literal_specification; a discriminant_specification;
15397 a component_declaration; a loop_parameter_specification; a
15398 parameter_specification; a subprogram_body; an entry_declaration;
15399 an entry_index_specification; a choice_parameter_specification;
15400 a generic_formal_parameter_declaration.''
15402 This means for example that each enumeration literal adds one to the count,
15403 as well as each subprogram parameter.
15405 Thus the results from this metric will be significantly greater than might
15406 be expected from a naive view of counting semicolons.
15408 @item Maximal static nesting level of inner program units
15409 According to
15410 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15411 package, a task unit, a protected unit, a
15412 protected entry, a generic unit, or an explicitly declared subprogram other
15413 than an enumeration literal.''
15415 @item Maximal nesting level of composite syntactic constructs
15416 This corresponds to the notion of the
15417 maximum nesting level in the GNAT built-in style checks
15418 (@pxref{Style Checking})
15419 @end table
15421 @noindent
15422 For the outermost unit in the file, @command{gnatmetric} additionally computes
15423 the following metrics:
15425 @table @emph
15426 @item Public subprograms
15427 This metric is computed for package specs. It is the
15428 number of subprograms and generic subprograms declared in the visible
15429 part (including the visible part of nested packages, protected objects, and
15430 protected types).
15432 @item All subprograms
15433 This metric is computed for bodies and subunits. The
15434 metric is equal to a total number of subprogram bodies in the compilation
15435 unit.
15436 Neither generic instantiations nor renamings-as-a-body nor body stubs
15437 are counted. Any subprogram body is counted, independently of its nesting
15438 level and enclosing constructs. Generic bodies and bodies of protected
15439 subprograms are counted in the same way as ``usual'' subprogram bodies.
15441 @item Public types
15442 This metric is computed for package specs and
15443 generic package declarations. It is the total number of types
15444 that can be referenced from outside this compilation unit, plus the
15445 number of types from all the visible parts of all the visible generic
15446 packages. Generic formal types are not counted.  Only types, not subtypes,
15447 are included.
15449 @noindent
15450 Along with the total number of public types, the following
15451 types are counted and reported separately:
15453 @itemize @bullet
15454 @item
15455 Abstract types
15457 @item
15458 Root tagged types (abstract, non-abstract, private, non-private). Type
15459 extensions are @emph{not} counted
15461 @item
15462 Private types (including private extensions)
15464 @item
15465 Task types
15467 @item
15468 Protected types
15470 @end itemize
15472 @item All types
15473 This metric is computed for any compilation unit. It is equal to the total
15474 number of the declarations of different types given in the compilation unit.
15475 The private and the corresponding full type declaration are counted as one
15476 type declaration. Incomplete type declarations and generic formal types
15477 are not counted.
15478 No distinction is made among different kinds of types (abstract,
15479 private etc.); the total number of types is computed and reported.
15481 @end table
15483 @noindent
15484 By default, all the syntax metrics are computed and reported. You can use the
15485 following switches to select specific syntax metrics.
15487 @table @option
15489 @cindex @option{--syntax@var{x}} (@command{gnatmetric})
15491 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15493 @item --syntax-all
15494 Report all the syntax metrics
15496 @item --no-syntax-all
15497 Do not report any of syntax metrics
15499 @item --declarations
15500 Report the total number of declarations
15502 @item --no-declarations
15503 Do not report the total number of declarations
15505 @item --statements
15506 Report the total number of statements
15508 @item --no-statements
15509 Do not report the total number of statements
15511 @item --public-subprograms
15512 Report the number of public subprograms in a compilation unit
15514 @item --no-public-subprograms
15515 Do not report the number of public subprograms in a compilation unit
15517 @item --all-subprograms
15518 Report the number of all the subprograms in a compilation unit
15520 @item --no-all-subprograms
15521 Do not report the number of all the subprograms in a compilation unit
15523 @item --public-types
15524 Report the number of public types in a compilation unit
15526 @item --no-public-types
15527 Do not report the number of public types in a compilation unit
15529 @item --all-types
15530 Report the number of all the types in a compilation unit
15532 @item --no-all-types
15533 Do not report the number of all the types in a compilation unit
15535 @item --unit-nesting
15536 Report the maximal program unit nesting level
15538 @item --no-unit-nesting
15539 Do not report the maximal program unit nesting level
15541 @item --construct-nesting
15542 Report the maximal construct nesting level
15544 @item --no-construct-nesting
15545 Do not report the maximal construct nesting level
15547 @end table
15549 @node Complexity Metrics Control
15550 @subsubsection Complexity Metrics Control
15551 @cindex Complexity metrics control in @command{gnatmetric}
15553 @noindent
15554 For a program unit that is an executable body (a subprogram body (including
15555 generic bodies), task body, entry body or a package body containing
15556 its own statement sequence) @command{gnatmetric} computes the following
15557 complexity metrics:
15559 @itemize @bullet
15560 @item
15561 McCabe cyclomatic complexity;
15563 @item
15564 McCabe essential complexity;
15566 @item
15567 maximal loop nesting level;
15569 @item
15570 extra exit points (for subprograms);
15571 @end itemize
15573 @noindent
15574 The McCabe cyclomatic complexity metric is defined
15575 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15577 According to McCabe, both control statements and short-circuit control forms
15578 should be taken into account when computing cyclomatic complexity.
15579 For Ada 2012 we have also take into account conditional expressions
15580 and quantified expressions. For each body, we compute three metric values:
15582 @itemize @bullet
15583 @item
15584 the complexity introduced by control
15585 statements only, without taking into account short-circuit forms
15586 (referred as @code{statement complexity} in @command{gnatmetric} output),
15588 @item
15589 the complexity introduced by short-circuit control forms only
15590 (referred as @code{expression complexity} in @command{gnatmetric} output), and
15592 @item
15593 the total
15594 cyclomatic complexity, which is the sum of these two values
15595 (referred as @code{cyclomatic complexity} in @command{gnatmetric} output).
15596 @end itemize
15598 @noindent
15600 The cyclomatic complexity is also computed for Ada 2012 expression functions.
15601 An expression function cannot have statements as its components, so only one
15602 metric value is computed as a cyclomatic complexity of an expression function.
15604 The origin of cyclomatic complexity metric is the need to estimate the number
15605 of independent paths in the control flow graph that in turn gives the number
15606 of tests needed to satisfy paths coverage testing completeness criterion.
15607 Considered from the testing point of view, a static Ada @code{loop} (that is,
15608 the @code{loop} statement having static subtype in loop parameter
15609 specification) does not add to cyclomatic complexity. By providing
15610 @option{--no-static-loop} option a user
15611 may specify that such loops should not be counted when computing the
15612 cyclomatic complexity metric
15614 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
15615 counted for the code that is reduced by excluding all the pure structural Ada
15616 control statements. An compound statement is considered as a non-structural
15617 if it contains a @code{raise} or @code{return} statement as it subcomponent,
15618 or if it contains a @code{goto} statement that transfers the control outside
15619 the operator. A selective accept statement with @code{terminate} alternative
15620 is considered as non-structural statement. When computing this metric,
15621 @code{exit} statements are treated in the same way as @code{goto}
15622 statements unless @option{-ne} option is specified.
15624 The Ada essential complexity metric defined here is intended to quantify
15625 the extent to which the software is unstructured. It is adapted from
15626 the McCabe essential complexity metric defined in
15627 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
15628 suitable for typical Ada usage. For example, short circuit forms
15629 are not penalized as unstructured in the Ada essential complexity metric.
15631 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15632 the code in the exception handlers and in all the nested program units. The
15633 code of assertions and predicates (that is, subprogram preconditions and
15634 postconditions, subtype predicates and type invariants) is also skipped.
15636 By default, all the complexity metrics are computed and reported.
15637 For more fine-grained control you can use
15638 the following switches:
15640 @table @option
15641 @cindex @option{-complexity@var{x}} (@command{gnatmetric})
15643 @cindex @option{--no-complexity@var{x}}
15645 @item --complexity-all
15646 Report all the complexity metrics
15648 @item --no-complexity-all
15649 Do not report any of complexity metrics
15651 @item --complexity-cyclomatic
15652 Report the McCabe Cyclomatic Complexity
15654 @item --no-complexity-cyclomatic
15655 Do not report the McCabe Cyclomatic Complexity
15657 @item --complexity-essential
15658 Report the Essential Complexity
15660 @item --no-complexity-essential
15661 Do not report the Essential Complexity
15663 @item --loop-nesting
15664 Report maximal loop nesting level
15666 @item --no-loop-nesting
15667 Do not report maximal loop nesting level
15669 @item --complexity-average
15670 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15671 task bodies, entry bodies and statement sequences in package bodies.
15672 The metric is computed and reported for whole set of processed Ada sources
15673 only.
15675 @item --no-complexity-average
15676 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15677 bodies, task bodies, entry bodies and statement sequences in package bodies
15679 @cindex @option{-ne} (@command{gnatmetric})
15680 @item -ne
15681 Do not consider @code{exit} statements as @code{goto}s when
15682 computing Essential Complexity
15684 @cindex @option{--no-static-loop} (@command{gnatmetric})
15685 @item --no-static-loop
15686 Do not consider static loops when computing cyclomatic complexity
15688 @item --extra-exit-points
15689 Report the extra exit points for subprogram bodies. As an exit point, this
15690 metric counts @code{return} statements and raise statements in case when the
15691 raised exception is not handled in the same body. In case of a function this
15692 metric subtracts 1 from the number of exit points, because a function body
15693 must contain at least one @code{return} statement.
15695 @item --no-extra-exit-points
15696 Do not report the extra exit points for subprogram bodies
15697 @end table
15700 @node Coupling Metrics Control
15701 @subsubsection Coupling Metrics Control
15702 @cindex Coupling metrics control in @command{gnatmetric}
15704 @noindent
15705 @cindex Coupling metrics (in @command{gnatmetric})
15706 Coupling metrics measure the dependencies between a given entity and other
15707 entities in the program. This information is useful since high coupling
15708 may signal potential issues with maintainability as the program evolves.
15710 @command{gnatmetric} computes the following coupling metrics:
15712 @itemize @bullet
15714 @item
15715 @emph{object-oriented coupling}, for classes in traditional object-oriented
15716 sense;
15718 @item
15719 @emph{unit coupling}, for all the program units making up a program;
15721 @item
15722 @emph{control coupling}, reflecting dependencies between a unit and
15723 other units that contain subprograms.
15724 @end itemize
15726 @noindent
15727 Two kinds of coupling metrics are computed:
15729 @itemize @bullet
15730 @item fan-out coupling (``efferent coupling''):
15731 @cindex fan-out coupling
15732 @cindex efferent coupling
15733 the number of entities the given entity depends upon. This metric
15734 reflects how the given entity depends on the changes in the
15735 ``external world''.
15737 @item fan-in coupling (``afferent'' coupling):
15738 @cindex fan-in coupling
15739 @cindex afferent coupling
15740 the number of entities that depend on a given entity.
15741 This metric reflects how the ``external world'' depends on the changes in a
15742 given entity.
15743 @end itemize
15745 @noindent
15746 Object-oriented coupling metrics measure the dependencies
15747 between a given class (or a group of classes) and the other classes in the
15748 program. In this subsection the term ``class'' is used in its traditional
15749 object-oriented programming sense (an instantiable module that contains data
15750 and/or method members). A @emph{category} (of classes) is a group of closely
15751 related classes that are reused and/or modified together.
15753 A class @code{K}'s fan-out coupling is the number of classes
15754 that @code{K} depends upon.
15755 A category's fan-out coupling is the number of classes outside the
15756 category that the classes inside the category depend upon.
15758 A class @code{K}'s fan-in coupling is the number of classes
15759 that depend upon @code{K}.
15760 A category's fan-in coupling is the number of classes outside the
15761 category that depend on classes belonging to the category.
15763 Ada's object-oriented paradigm separates the instantiable entity
15764 (type) from the module (package), so the definition of the coupling
15765 metrics for Ada maps the class and class category notions
15766 onto Ada constructs.
15768 For the coupling metrics, several kinds of modules that define a tagged type
15769 or an interface type  -- library packages, library generic packages, and
15770 library generic package instantiations -- are considered to be classes.
15771 A category consists of a library package (or
15772 a library generic package) that defines a tagged or an interface type,
15773 together with all its descendant (generic) packages that define tagged
15774 or interface types. Thus a
15775 category is an Ada hierarchy of library-level program units. Class
15776 coupling in Ada is referred to as ``tagged coupling'', and category coupling
15777 is referred to as ``hierarchy coupling''.
15779 For any package serving as a class, its body and subunits (if any) are
15780 considered together with its spec when computing dependencies, and coupling
15781 metrics are reported for spec units only. Dependencies between classes
15782 mean Ada semantic dependencies. For object-oriented coupling
15783 metrics, only dependencies on units treated as classes are
15784 considered.
15786 Similarly, for unit and control coupling an entity is considered to be the
15787 conceptual construct consisting of the entity's specification, body, and
15788 any subunits (transitively).
15789 @command{gnatmetric} computes
15790 the dependencies of all these units as a whole, but
15791 metrics are only reported for spec
15792 units (or for a subprogram body unit in case if there is no
15793 separate spec for the given subprogram).
15795 For unit coupling, dependencies are computed between all kinds of program
15796 units. For control coupling, the dependencies of a given unit are limited to
15797 those units that define subprograms. Thus control fan-out coupling is reported
15798 for all units, but control fan-in coupling is only reported for units
15799 that define subprograms.
15801 The following simple example illustrates the difference between unit coupling
15802 and control coupling metrics:
15804 @smallexample @c ada
15805 @group
15806 @b{package} Lib_1 @b{is}
15807     @b{function} F_1 (I : Integer) @b{return} Integer;
15808 @b{end} Lib_1;
15809 @end group
15811 @group
15812 @b{package} Lib_2 @b{is}
15813     @b{type} T_2 @b{is} @b{new} Integer;
15814 @b{end} Lib_2;
15815 @end group
15817 @group
15818 @b{package} @b{body} Lib_1 @b{is}
15819     @b{function} F_1 (I : Integer) @b{return} Integer @b{is}
15820     @b{begin}
15821        @b{return} I + 1;
15822     @b{end} F_1;
15823 @b{end} Lib_1;
15824 @end group
15826 @group
15827 @b{with} Lib_2; @b{use} Lib_2;
15828 @b{package} Pack @b{is}
15829     Var : T_2;
15830     @b{function} Fun (I : Integer) @b{return} Integer;
15831 @b{end} Pack;
15832 @end group
15834 @group
15835 @b{with} Lib_1; @b{use} Lib_1;
15836 @b{package} @b{body} Pack @b{is}
15837     @b{function} Fun (I : Integer) @b{return} Integer @b{is}
15838     @b{begin}
15839        @b{return} F_1 (I);
15840     @b{end} Fun;
15841 @b{end} Pack;
15842 @end group
15843 @end smallexample
15845 @noindent
15846 If we apply @command{gnatmetric} with the @option{--coupling-all} option to
15847 these units, the result will be:
15849 @smallexample
15850 @group
15851 Coupling metrics:
15852 =================
15853     Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
15854        control fan-out coupling  : 0
15855        control fan-in coupling   : 1
15856        unit fan-out coupling     : 0
15857        unit fan-in coupling      : 1
15858 @end group
15860 @group
15861     Unit Pack (C:\customers\662\L406-007\pack.ads)
15862        control fan-out coupling  : 1
15863        control fan-in coupling   : 0
15864        unit fan-out coupling     : 2
15865        unit fan-in coupling      : 0
15866 @end group
15868 @group
15869     Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
15870        control fan-out coupling  : 0
15871        unit fan-out coupling     : 0
15872        unit fan-in coupling      : 1
15873 @end group
15874 @end smallexample
15876 @noindent
15877 The result does not contain values for object-oriented
15878 coupling because none of the argument units contains a tagged type and
15879 therefore none of these units can be treated as a class.
15881 The @code{Pack} package (spec and body) depends on two
15882 units -- @code{Lib_1} @code{and Lib_2} -- and so its unit fan-out coupling
15883 is 2. Since nothing depends on it, its unit fan-in coupling is 0, as
15884 is its control fan-in coupling. Only one of the units @code{Pack} depends
15885 upon defines a subprogram, so its control fan-out coupling is 1.
15887 @code{Lib_2} depends on nothing, so its fan-out metrics are 0. It does
15888 not define any subprograms, so it has no control fan-in metric.
15889 One unit (@code{Pack}) depends on it , so its unit fan-in coupling is 1.
15891 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
15892 Its control fan-in coupling is 1 (because there is one unit
15893 depending on it).
15895 When computing coupling metrics, @command{gnatmetric} counts only
15896 dependencies between units that are arguments of the @command{gnatmetric}
15897 invocation. Coupling metrics are program-wide (or project-wide) metrics, so
15898 you should invoke @command{gnatmetric} for
15899 the complete set of sources comprising your program. This can be done
15900 by invoking @command{gnatmetric} with the corresponding project file
15901 and with the @option{-U} option.
15903 By default, all the coupling metrics are disabled. You can use the following
15904 switches to specify the coupling metrics to be computed and reported:
15906 @table @option
15908 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
15909 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
15910 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
15911 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
15914 @item --coupling-all
15915 Report all the coupling metrics
15917 @item --tagged-coupling-out
15918 Report tagged (class) fan-out coupling
15920 @item --tagged-coupling-in
15921 Report tagged (class) fan-in coupling
15923 @item --hierarchy-coupling-out
15924 Report hierarchy (category) fan-out coupling
15926 @item --hierarchy-coupling-in
15927 Report hierarchy (category) fan-in coupling
15929 @item --unit-coupling-out
15930 Report unit fan-out coupling
15932 @item --unit-coupling-in
15933 Report unit fan-in coupling
15935 @item --control-coupling-out
15936 Report control fan-out coupling
15938 @item --control-coupling-in
15939 Report control fan-in coupling
15940 @end table
15942 @node Other gnatmetric Switches
15943 @subsection Other @code{gnatmetric} Switches
15945 @noindent
15946 Additional @command{gnatmetric} switches are as follows:
15948 @table @option
15949 @item --version
15950 @cindex @option{--version} @command{gnatmetric}
15951 Display Copyright and version, then exit disregarding all other options.
15953 @item --help
15954 @cindex @option{--help} @command{gnatmetric}
15955 Display usage, then exit disregarding all other options.
15957 @item -P @var{file}
15958 @cindex @option{-P} @command{gnatmetric}
15959 Indicates the name of the project file that describes the set of sources
15960 to be processed. The exact set of argument sources depends on other options
15961 specified, see below.
15963 @item -U
15964 @cindex @option{-U} @command{gnatmetric}
15965 If a project file is specified and no argument source is explicitly
15966 specified (either directly or by means of @option{-files} option), process
15967 all the units of the closure of the argument project. Otherwise this option
15968 has no effect.
15970 @item -U @var{main_unit}
15971 If a project file is specified and no argument source is explicitly
15972 specified (either directly or by means of @option{-files} option), process
15973 the closure of units rooted at @var{main_unit}. Otherwise this option
15974 has no effect.
15976 @item -X@var{name}=@var{value}
15977 @cindex @option{-X} @command{gnatmetric}
15978 Indicates that external variable @var{name} in the argument project
15979 has the value @var{value}. Has no effect if no project is specified as
15980 tool argument.
15982 @item --RTS=@var{rts-path}
15983 @cindex @option{--RTS} (@command{gnatmetric})
15984 Specifies the default location of the runtime library. Same meaning as the
15985 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15987 @item --subdirs=@var{dir}
15988 @cindex @option{--subdirs=@var{dir}} @command{gnatmetric}
15989 Use the specified subdirectory of the project objects file (or of the
15990 project file directory if the project does not specify an object directory)
15991 for tool output files. Has no effect if no project is specified as
15992 tool argument r if @option{--no_objects_dir} is specified.
15994 @item --no_objects_dir
15995 @cindex @option{--no_objects_dir} @command{gnatmetric}
15996 Place all the result files into the current directory instead of
15997 project objects directory. This corresponds to the @command{gnatcheck}
15998 behavior when it is called with the project file from the
15999 GNAT driver. Has no effect if no project is specified.
16001 @item -files @var{filename}
16002 @cindex @option{-files} (@code{gnatmetric})
16003 Take the argument source files from the specified file. This file should be an
16004 ordinary text file containing file names separated by spaces or
16005 line breaks. You can use this switch more than once in the same call to
16006 @command{gnatmetric}. You also can combine this switch with
16007 an explicit list of files.
16009 @item -j@var{n}
16010 @cindex @option{-j} (@command{gnatmetric})
16011 Use @var{n} processes to carry out the tree creations (internal representations
16012 of the argument sources). On a multiprocessor machine this speeds up processing
16013 of big sets of argument sources. If @var{n} is 0, then the maximum number of
16014 parallel tree creations is the number of core processors on the platform.
16016 @cindex @option{-t} (@command{gnatmetric})
16017 @item -t
16018 Print out execution time.
16020 @item -v
16021 @cindex @option{-v} (@command{gnatmetric})
16022 Verbose mode;
16023 @command{gnatmetric} generates version information and then
16024 a trace of sources being processed.
16026 @item -q
16027 @cindex @option{-q} (@command{gnatmetric})
16028 Quiet mode.
16029 @end table
16031 @noindent
16032 If a project file is specified and no argument source is explicitly
16033 specified (either directly or by means of @option{-files} option), and no
16034 @option{-U} is specified, then the set of processed sources is
16035 all the immediate units of the argument project.
16038 @ignore
16039 @node Generate project-wide metrics
16040 @subsection Generate project-wide metrics
16042 In order to compute metrics on all units of a given project, you can use
16043 the @command{gnat} driver along with the @option{-P} option:
16044 @smallexample
16045    gnat metric -Pproj
16046 @end smallexample
16048 @noindent
16049 If the project @code{proj} depends upon other projects, you can compute
16050 the metrics on the project closure using the @option{-U} option:
16051 @smallexample
16052    gnat metric -Pproj -U
16053 @end smallexample
16055 @noindent
16056 Finally, if not all the units are relevant to a particular main
16057 program in the project closure, you can generate metrics for the set
16058 of units needed to create a given main program (unit closure) using
16059 the @option{-U} option followed by the name of the main unit:
16060 @smallexample
16061    gnat metric -Pproj -U main
16062 @end smallexample
16063 @end ignore
16064 @end ifclear
16067 @c ***********************************
16068 @node File Name Krunching with gnatkr
16069 @chapter File Name Krunching with @code{gnatkr}
16070 @findex gnatkr
16072 @noindent
16073 This chapter discusses the method used by the compiler to shorten
16074 the default file names chosen for Ada units so that they do not
16075 exceed the maximum length permitted. It also describes the
16076 @code{gnatkr} utility that can be used to determine the result of
16077 applying this shortening.
16078 @menu
16079 * About gnatkr::
16080 * Using gnatkr::
16081 * Krunching Method::
16082 * Examples of gnatkr Usage::
16083 @end menu
16085 @node About gnatkr
16086 @section About @code{gnatkr}
16088 @noindent
16089 The default file naming rule in GNAT
16090 is that the file name must be derived from
16091 the unit name. The exact default rule is as follows:
16092 @itemize @bullet
16093 @item
16094 Take the unit name and replace all dots by hyphens.
16095 @item
16096 If such a replacement occurs in the
16097 second character position of a name, and the first character is
16098 @samp{a}, @samp{g}, @samp{s}, or @samp{i},
16099 then replace the dot by the character
16100 @samp{~} (tilde)
16101 instead of a minus.
16102 @end itemize
16103 The reason for this exception is to avoid clashes
16104 with the standard names for children of System, Ada, Interfaces,
16105 and GNAT, which use the prefixes
16106 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
16107 respectively.
16109 The @option{-gnatk@var{nn}}
16110 switch of the compiler activates a ``krunching''
16111 circuit that limits file names to nn characters (where nn is a decimal
16112 integer). For example, using OpenVMS,
16113 where the maximum file name length is
16114 39, the value of nn is usually set to 39, but if you want to generate
16115 a set of files that would be usable if ported to a system with some
16116 different maximum file length, then a different value can be specified.
16117 The default value of 39 for OpenVMS need not be specified.
16119 The @code{gnatkr} utility can be used to determine the krunched name for
16120 a given file, when krunched to a specified maximum length.
16122 @node Using gnatkr
16123 @section Using @code{gnatkr}
16125 @noindent
16126 The @code{gnatkr} command has the form
16128 @smallexample
16129 @c $ gnatkr @var{name} @ovar{length}
16130 @c Expanding @ovar macro inline (explanation in macro def comments)
16131 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16132 @end smallexample
16135 @noindent
16136 @var{name} is the uncrunched file name, derived from the name of the unit
16137 in the standard manner described in the previous section (i.e., in particular
16138 all dots are replaced by hyphens). The file name may or may not have an
16139 extension (defined as a suffix of the form period followed by arbitrary
16140 characters other than period). If an extension is present then it will
16141 be preserved in the output. For example, when krunching @file{hellofile.ads}
16142 to eight characters, the result will be hellofil.ads.
16144 Note: for compatibility with previous versions of @code{gnatkr} dots may
16145 appear in the name instead of hyphens, but the last dot will always be
16146 taken as the start of an extension. So if @code{gnatkr} is given an argument
16147 such as @file{Hello.World.adb} it will be treated exactly as if the first
16148 period had been a hyphen, and for example krunching to eight characters
16149 gives the result @file{hellworl.adb}.
16151 Note that the result is always all lower case (except on OpenVMS where it is
16152 all upper case). Characters of the other case are folded as required.
16154 @var{length} represents the length of the krunched name. The default
16155 when no argument is given is 8 characters. A length of zero stands for
16156 unlimited, in other words do not chop except for system files where the
16157 implied crunching length is always eight characters.
16159 @noindent
16160 The output is the krunched name. The output has an extension only if the
16161 original argument was a file name with an extension.
16163 @node Krunching Method
16164 @section Krunching Method
16166 @noindent
16167 The initial file name is determined by the name of the unit that the file
16168 contains. The name is formed by taking the full expanded name of the
16169 unit and replacing the separating dots with hyphens and
16170 using lowercase
16171 for all letters, except that a hyphen in the second character position is
16172 replaced by a tilde if the first character is
16173 @samp{a}, @samp{i}, @samp{g}, or @samp{s}.
16174 The extension is @code{.ads} for a
16175 spec and @code{.adb} for a body.
16176 Krunching does not affect the extension, but the file name is shortened to
16177 the specified length by following these rules:
16179 @itemize @bullet
16180 @item
16181 The name is divided into segments separated by hyphens, tildes or
16182 underscores and all hyphens, tildes, and underscores are
16183 eliminated. If this leaves the name short enough, we are done.
16185 @item
16186 If the name is too long, the longest segment is located (left-most
16187 if there are two of equal length), and shortened by dropping
16188 its last character. This is repeated until the name is short enough.
16190 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16191 to fit the name into 8 characters as required by some operating systems.
16193 @smallexample
16194 our-strings-wide_fixed 22
16195 our strings wide fixed 19
16196 our string  wide fixed 18
16197 our strin   wide fixed 17
16198 our stri    wide fixed 16
16199 our stri    wide fixe  15
16200 our str     wide fixe  14
16201 our str     wid  fixe  13
16202 our str     wid  fix   12
16203 ou  str     wid  fix   11
16204 ou  st      wid  fix   10
16205 ou  st      wi   fix   9
16206 ou  st      wi   fi    8
16207 Final file name: oustwifi.adb
16208 @end smallexample
16210 @item
16211 The file names for all predefined units are always krunched to eight
16212 characters. The krunching of these predefined units uses the following
16213 special prefix replacements:
16215 @table @file
16216 @item ada-
16217 replaced by @file{a-}
16219 @item gnat-
16220 replaced by @file{g-}
16222 @item interfaces-
16223 replaced by @file{i-}
16225 @item system-
16226 replaced by @file{s-}
16227 @end table
16229 These system files have a hyphen in the second character position. That
16230 is why normal user files replace such a character with a
16231 tilde, to
16232 avoid confusion with system file names.
16234 As an example of this special rule, consider
16235 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16237 @smallexample
16238 ada-strings-wide_fixed 22
16239 a-  strings wide fixed 18
16240 a-  string  wide fixed 17
16241 a-  strin   wide fixed 16
16242 a-  stri    wide fixed 15
16243 a-  stri    wide fixe  14
16244 a-  str     wide fixe  13
16245 a-  str     wid  fixe  12
16246 a-  str     wid  fix   11
16247 a-  st      wid  fix   10
16248 a-  st      wi   fix   9
16249 a-  st      wi   fi    8
16250 Final file name: a-stwifi.adb
16251 @end smallexample
16252 @end itemize
16254 Of course no file shortening algorithm can guarantee uniqueness over all
16255 possible unit names, and if file name krunching is used then it is your
16256 responsibility to ensure that no name clashes occur. The utility
16257 program @code{gnatkr} is supplied for conveniently determining the
16258 krunched name of a file.
16260 @node Examples of gnatkr Usage
16261 @section Examples of @code{gnatkr} Usage
16263 @smallexample
16264 @iftex
16265 @leftskip=0cm
16266 @end iftex
16267 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16268 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16269 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16270 $ gnatkr grandparent-parent-child     --> grparchi
16271 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16272 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16273 @end smallexample
16275 @node Preprocessing with gnatprep
16276 @chapter Preprocessing with @code{gnatprep}
16277 @findex gnatprep
16279 @noindent
16280 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16281 preprocessing.
16282 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16283 special GNAT features.
16284 For further discussion of conditional compilation in general, see
16285 @ref{Conditional Compilation}.
16287 @menu
16288 * Preprocessing Symbols::
16289 * Using gnatprep::
16290 * Switches for gnatprep::
16291 * Form of Definitions File::
16292 * Form of Input Text for gnatprep::
16293 @end menu
16295 @node Preprocessing Symbols
16296 @section Preprocessing Symbols
16298 @noindent
16299 Preprocessing symbols are defined in definition files and referred to in
16300 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16301 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16302 all characters need to be in the ASCII set (no accented letters).
16304 @node Using gnatprep
16305 @section Using @code{gnatprep}
16307 @noindent
16308 To call @code{gnatprep} use
16310 @smallexample
16311 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16312 @c Expanding @ovar macro inline (explanation in macro def comments)
16313 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16314 @end smallexample
16316 @noindent
16317 where
16318 @table @var
16319 @item switches
16320 is an optional sequence of switches as described in the next section.
16322 @item infile
16323 is the full name of the input file, which is an Ada source
16324 file containing preprocessor directives.
16326 @item outfile
16327 is the full name of the output file, which is an Ada source
16328 in standard Ada form. When used with GNAT, this file name will
16329 normally have an ads or adb suffix.
16331 @item deffile
16332 is the full name of a text file containing definitions of
16333 preprocessing symbols to be referenced by the preprocessor. This argument is
16334 optional, and can be replaced by the use of the @option{-D} switch.
16336 @end table
16338 @node Switches for gnatprep
16339 @section Switches for @code{gnatprep}
16341 @table @option
16342 @c !sort!
16344 @item -b
16345 @cindex @option{-b} (@command{gnatprep})
16346 Causes both preprocessor lines and the lines deleted by
16347 preprocessing to be replaced by blank lines in the output source file,
16348 preserving line numbers in the output file.
16350 @item -c
16351 @cindex @option{-c} (@command{gnatprep})
16352 Causes both preprocessor lines and the lines deleted
16353 by preprocessing to be retained in the output source as comments marked
16354 with the special string @code{"--! "}. This option will result in line numbers
16355 being preserved in the output file.
16357 @item -C
16358 @cindex @option{-C} (@command{gnatprep})
16359 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16360 If this option is specified, then comments are scanned and any $symbol
16361 substitutions performed as in program text. This is particularly useful
16362 when structured comments are used (e.g., when writing programs in the
16363 SPARK dialect of Ada). Note that this switch is not available when
16364 doing integrated preprocessing (it would be useless in this context
16365 since comments are ignored by the compiler in any case).
16367 @item -Dsymbol=value
16368 @cindex @option{-D} (@command{gnatprep})
16369 Defines a new preprocessing symbol, associated with value. If no value is given
16370 on the command line, then symbol is considered to be @code{True}. This switch
16371 can be used in place of a definition file.
16374 @item -r
16375 @cindex @option{-r} (@command{gnatprep})
16376 Causes a @code{Source_Reference} pragma to be generated that
16377 references the original input file, so that error messages will use
16378 the file name of this original file. The use of this switch implies
16379 that preprocessor lines are not to be removed from the file, so its
16380 use will force @option{-b} mode if
16381 @option{-c}
16382 has not been specified explicitly.
16384 Note that if the file to be preprocessed contains multiple units, then
16385 it will be necessary to @code{gnatchop} the output file from
16386 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16387 in the preprocessed file, it will be respected by
16388 @code{gnatchop -r}
16389 so that the final chopped files will correctly refer to the original
16390 input source file for @code{gnatprep}.
16392 @item -s
16393 @cindex @option{-s} (@command{gnatprep})
16394 Causes a sorted list of symbol names and values to be
16395 listed on the standard output file.
16397 @item -u
16398 @cindex @option{-u} (@command{gnatprep})
16399 Causes undefined symbols to be treated as having the value FALSE in the context
16400 of a preprocessor test. In the absence of this option, an undefined symbol in
16401 a @code{#if} or @code{#elsif} test will be treated as an error.
16403 @end table
16405 @noindent
16406 Note: if neither @option{-b} nor @option{-c} is present,
16407 then preprocessor lines and
16408 deleted lines are completely removed from the output, unless -r is
16409 specified, in which case -b is assumed.
16411 @node Form of Definitions File
16412 @section Form of Definitions File
16414 @noindent
16415 The definitions file contains lines of the form
16417 @smallexample
16418 symbol := value
16419 @end smallexample
16421 @noindent
16422 where symbol is a preprocessing symbol, and value is one of the following:
16424 @itemize @bullet
16425 @item
16426 Empty, corresponding to a null substitution
16427 @item
16428 A string literal using normal Ada syntax
16429 @item
16430 Any sequence of characters from the set
16431 (letters, digits, period, underline).
16432 @end itemize
16434 @noindent
16435 Comment lines may also appear in the definitions file, starting with
16436 the usual @code{--},
16437 and comments may be added to the definitions lines.
16439 @node Form of Input Text for gnatprep
16440 @section Form of Input Text for @code{gnatprep}
16442 @noindent
16443 The input text may contain preprocessor conditional inclusion lines,
16444 as well as general symbol substitution sequences.
16446 The preprocessor conditional inclusion commands have the form
16448 @smallexample
16449 @group
16450 @cartouche
16451 #if @i{expression} @r{[}then@r{]}
16452    lines
16453 #elsif @i{expression} @r{[}then@r{]}
16454    lines
16455 #elsif @i{expression} @r{[}then@r{]}
16456    lines
16457 @dots{}
16458 #else
16459    lines
16460 #end if;
16461 @end cartouche
16462 @end group
16463 @end smallexample
16465 @noindent
16466 In this example, @i{expression} is defined by the following grammar:
16467 @smallexample
16468 @i{expression} ::=  <symbol>
16469 @i{expression} ::=  <symbol> = "<value>"
16470 @i{expression} ::=  <symbol> = <symbol>
16471 @i{expression} ::=  <symbol> = <integer>
16472 @i{expression} ::=  <symbol> > <integer>
16473 @i{expression} ::=  <symbol> >= <integer>
16474 @i{expression} ::=  <symbol> < <integer>
16475 @i{expression} ::=  <symbol> <= <integer>
16476 @i{expression} ::=  <symbol> 'Defined
16477 @i{expression} ::=  not @i{expression}
16478 @i{expression} ::=  @i{expression} and @i{expression}
16479 @i{expression} ::=  @i{expression} or @i{expression}
16480 @i{expression} ::=  @i{expression} and then @i{expression}
16481 @i{expression} ::=  @i{expression} or else @i{expression}
16482 @i{expression} ::=  ( @i{expression} )
16483 @end smallexample
16485 The following restriction exists: it is not allowed to have "and" or "or"
16486 following "not" in the same expression without parentheses. For example, this
16487 is not allowed:
16489 @smallexample
16490    not X or Y
16491 @end smallexample
16493 This should be one of the following:
16495 @smallexample
16496    (not X) or Y
16497    not (X or Y)
16498 @end smallexample
16500 @noindent
16501 For the first test (@i{expression} ::= <symbol>) the symbol must have
16502 either the value true or false, that is to say the right-hand of the
16503 symbol definition must be one of the (case-insensitive) literals
16504 @code{True} or @code{False}. If the value is true, then the
16505 corresponding lines are included, and if the value is false, they are
16506 excluded.
16508 When comparing a symbol to an integer, the integer is any non negative
16509 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
16510 2#11#. The symbol value must also be a non negative integer. Integer values
16511 in the range 0 .. 2**31-1 are supported.
16513 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16514 the symbol has been defined in the definition file or by a @option{-D}
16515 switch on the command line. Otherwise, the test is false.
16517 The equality tests are case insensitive, as are all the preprocessor lines.
16519 If the symbol referenced is not defined in the symbol definitions file,
16520 then the effect depends on whether or not switch @option{-u}
16521 is specified. If so, then the symbol is treated as if it had the value
16522 false and the test fails. If this switch is not specified, then
16523 it is an error to reference an undefined symbol. It is also an error to
16524 reference a symbol that is defined with a value other than @code{True}
16525 or @code{False}.
16527 The use of the @code{not} operator inverts the sense of this logical test.
16528 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16529 operators, without parentheses. For example, "if not X or Y then" is not
16530 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16532 The @code{then} keyword is optional as shown
16534 The @code{#} must be the first non-blank character on a line, but
16535 otherwise the format is free form. Spaces or tabs may appear between
16536 the @code{#} and the keyword. The keywords and the symbols are case
16537 insensitive as in normal Ada code. Comments may be used on a
16538 preprocessor line, but other than that, no other tokens may appear on a
16539 preprocessor line. Any number of @code{elsif} clauses can be present,
16540 including none at all. The @code{else} is optional, as in Ada.
16542 The @code{#} marking the start of a preprocessor line must be the first
16543 non-blank character on the line, i.e., it must be preceded only by
16544 spaces or horizontal tabs.
16546 Symbol substitution outside of preprocessor lines is obtained by using
16547 the sequence
16549 @smallexample
16550 $symbol
16551 @end smallexample
16553 @noindent
16554 anywhere within a source line, except in a comment or within a
16555 string literal. The identifier
16556 following the @code{$} must match one of the symbols defined in the symbol
16557 definition file, and the result is to substitute the value of the
16558 symbol in place of @code{$symbol} in the output file.
16560 Note that although the substitution of strings within a string literal
16561 is not possible, it is possible to have a symbol whose defined value is
16562 a string literal. So instead of setting XYZ to @code{hello} and writing:
16564 @smallexample
16565 Header : String := "$XYZ";
16566 @end smallexample
16568 @noindent
16569 you should set XYZ to @code{"hello"} and write:
16571 @smallexample
16572 Header : String := $XYZ;
16573 @end smallexample
16575 @noindent
16576 and then the substitution will occur as desired.
16578 @node The GNAT Library Browser gnatls
16579 @chapter The GNAT Library Browser @code{gnatls}
16580 @findex gnatls
16581 @cindex Library browser
16583 @noindent
16584 @code{gnatls} is a tool that outputs information about compiled
16585 units. It gives the relationship between objects, unit names and source
16586 files. It can also be used to check the source dependencies of a unit
16587 as well as various characteristics.
16589 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16590 driver (see @ref{The GNAT Driver and Project Files}).
16592 @menu
16593 * Running gnatls::
16594 * Switches for gnatls::
16595 * Examples of gnatls Usage::
16596 @end menu
16598 @node Running gnatls
16599 @section Running @code{gnatls}
16601 @noindent
16602 The @code{gnatls} command has the form
16604 @smallexample
16605 $ gnatls switches @var{object_or_ali_file}
16606 @end smallexample
16608 @noindent
16609 The main argument is the list of object or @file{ali} files
16610 (@pxref{The Ada Library Information Files})
16611 for which information is requested.
16613 In normal mode, without additional option, @code{gnatls} produces a
16614 four-column listing. Each line represents information for a specific
16615 object. The first column gives the full path of the object, the second
16616 column gives the name of the principal unit in this object, the third
16617 column gives the status of the source and the fourth column gives the
16618 full path of the source representing this unit.
16619 Here is a simple example of use:
16621 @smallexample
16622 $ gnatls *.o
16623 ./demo1.o            demo1            DIF demo1.adb
16624 ./demo2.o            demo2             OK demo2.adb
16625 ./hello.o            h1                OK hello.adb
16626 ./instr-child.o      instr.child      MOK instr-child.adb
16627 ./instr.o            instr             OK instr.adb
16628 ./tef.o              tef              DIF tef.adb
16629 ./text_io_example.o  text_io_example   OK text_io_example.adb
16630 ./tgef.o             tgef             DIF tgef.adb
16631 @end smallexample
16633 @noindent
16634 The first line can be interpreted as follows: the main unit which is
16635 contained in
16636 object file @file{demo1.o} is demo1, whose main source is in
16637 @file{demo1.adb}. Furthermore, the version of the source used for the
16638 compilation of demo1 has been modified (DIF). Each source file has a status
16639 qualifier which can be:
16641 @table @code
16642 @item OK (unchanged)
16643 The version of the source file used for the compilation of the
16644 specified unit corresponds exactly to the actual source file.
16646 @item MOK (slightly modified)
16647 The version of the source file used for the compilation of the
16648 specified unit differs from the actual source file but not enough to
16649 require recompilation. If you use gnatmake with the qualifier
16650 @option{-m (minimal recompilation)}, a file marked
16651 MOK will not be recompiled.
16653 @item DIF (modified)
16654 No version of the source found on the path corresponds to the source
16655 used to build this object.
16657 @item ??? (file not found)
16658 No source file was found for this unit.
16660 @item HID (hidden,  unchanged version not first on PATH)
16661 The version of the source that corresponds exactly to the source used
16662 for compilation has been found on the path but it is hidden by another
16663 version of the same source that has been modified.
16665 @end table
16667 @node Switches for gnatls
16668 @section Switches for @code{gnatls}
16670 @noindent
16671 @code{gnatls} recognizes the following switches:
16673 @table @option
16674 @c !sort!
16675 @cindex @option{--version} @command{gnatls}
16676 Display Copyright and version, then exit disregarding all other options.
16678 @item --help
16679 @cindex @option{--help} @command{gnatls}
16680 If @option{--version} was not used, display usage, then exit disregarding
16681 all other options.
16683 @item -a
16684 @cindex @option{-a} (@code{gnatls})
16685 Consider all units, including those of the predefined Ada library.
16686 Especially useful with @option{-d}.
16688 @item -d
16689 @cindex @option{-d} (@code{gnatls})
16690 List sources from which specified units depend on.
16692 @item -h
16693 @cindex @option{-h} (@code{gnatls})
16694 Output the list of options.
16696 @item -o
16697 @cindex @option{-o} (@code{gnatls})
16698 Only output information about object files.
16700 @item -s
16701 @cindex @option{-s} (@code{gnatls})
16702 Only output information about source files.
16704 @item -u
16705 @cindex @option{-u} (@code{gnatls})
16706 Only output information about compilation units.
16708 @item -files=@var{file}
16709 @cindex @option{-files} (@code{gnatls})
16710 Take as arguments the files listed in text file @var{file}.
16711 Text file @var{file} may contain empty lines that are ignored.
16712 Each nonempty line should contain the name of an existing file.
16713 Several such switches may be specified simultaneously.
16715 @item -aO@var{dir}
16716 @itemx -aI@var{dir}
16717 @itemx -I@var{dir}
16718 @itemx  -I-
16719 @itemx -nostdinc
16720 @cindex @option{-aO} (@code{gnatls})
16721 @cindex @option{-aI} (@code{gnatls})
16722 @cindex @option{-I} (@code{gnatls})
16723 @cindex @option{-I-} (@code{gnatls})
16724 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16725 flags (@pxref{Switches for gnatmake}).
16727 @item -aP@var{dir}
16728 @cindex @option{-aP} (@code{gnatls})
16729 Add @var{dir} at the beginning of the project search dir.
16731 @item --RTS=@var{rts-path}
16732 @cindex @option{--RTS} (@code{gnatls})
16733 Specifies the default location of the runtime library. Same meaning as the
16734 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16736 @item -v
16737 @cindex @option{-v} (@code{gnatls})
16738 Verbose mode. Output the complete source, object and project paths. Do not use
16739 the default column layout but instead use long format giving as much as
16740 information possible on each requested units, including special
16741 characteristics such as:
16743 @table @code
16744 @item  Preelaborable
16745 The unit is preelaborable in the Ada sense.
16747 @item No_Elab_Code
16748 No elaboration code has been produced by the compiler for this unit.
16750 @item Pure
16751 The unit is pure in the Ada sense.
16753 @item Elaborate_Body
16754 The unit contains a pragma Elaborate_Body.
16756 @item Remote_Types
16757 The unit contains a pragma Remote_Types.
16759 @item Shared_Passive
16760 The unit contains a pragma Shared_Passive.
16762 @item Predefined
16763 This unit is part of the predefined environment and cannot be modified
16764 by the user.
16766 @item Remote_Call_Interface
16767 The unit contains a pragma Remote_Call_Interface.
16769 @end table
16771 @end table
16773 @node Examples of gnatls Usage
16774 @section Example of @code{gnatls} Usage
16776 @noindent
16777 Example of using the verbose switch. Note how the source and
16778 object paths are affected by the -I switch.
16780 @smallexample
16781 $ gnatls -v -I.. demo1.o
16783 GNATLS 5.03w (20041123-34)
16784 Copyright 1997-2004 Free Software Foundation, Inc.
16786 Source Search Path:
16787    <Current_Directory>
16788    ../
16789    /home/comar/local/adainclude/
16791 Object Search Path:
16792    <Current_Directory>
16793    ../
16794    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16796 Project Search Path:
16797    <Current_Directory>
16798    /home/comar/local/lib/gnat/
16800 ./demo1.o
16801    Unit =>
16802      Name   => demo1
16803      Kind   => subprogram body
16804      Flags  => No_Elab_Code
16805      Source => demo1.adb    modified
16806 @end smallexample
16808 @noindent
16809 The following is an example of use of the dependency list.
16810 Note the use of the -s switch
16811 which gives a straight list of source files. This can be useful for
16812 building specialized scripts.
16814 @smallexample
16815 $ gnatls -d demo2.o
16816 ./demo2.o   demo2        OK demo2.adb
16817                          OK gen_list.ads
16818                          OK gen_list.adb
16819                          OK instr.ads
16820                          OK instr-child.ads
16822 $ gnatls -d -s -a demo1.o
16823 demo1.adb
16824 /home/comar/local/adainclude/ada.ads
16825 /home/comar/local/adainclude/a-finali.ads
16826 /home/comar/local/adainclude/a-filico.ads
16827 /home/comar/local/adainclude/a-stream.ads
16828 /home/comar/local/adainclude/a-tags.ads
16829 gen_list.ads
16830 gen_list.adb
16831 /home/comar/local/adainclude/gnat.ads
16832 /home/comar/local/adainclude/g-io.ads
16833 instr.ads
16834 /home/comar/local/adainclude/system.ads
16835 /home/comar/local/adainclude/s-exctab.ads
16836 /home/comar/local/adainclude/s-finimp.ads
16837 /home/comar/local/adainclude/s-finroo.ads
16838 /home/comar/local/adainclude/s-secsta.ads
16839 /home/comar/local/adainclude/s-stalib.ads
16840 /home/comar/local/adainclude/s-stoele.ads
16841 /home/comar/local/adainclude/s-stratt.ads
16842 /home/comar/local/adainclude/s-tasoli.ads
16843 /home/comar/local/adainclude/s-unstyp.ads
16844 /home/comar/local/adainclude/unchconv.ads
16845 @end smallexample
16848 @node Cleaning Up with gnatclean
16849 @chapter Cleaning Up with @code{gnatclean}
16850 @findex gnatclean
16851 @cindex Cleaning tool
16853 @noindent
16854 @code{gnatclean} is a tool that allows the deletion of files produced by the
16855 compiler, binder and linker, including ALI files, object files, tree files,
16856 expanded source files, library files, interface copy source files, binder
16857 generated files and executable files.
16859 @menu
16860 * Running gnatclean::
16861 * Switches for gnatclean::
16862 @c * Examples of gnatclean Usage::
16863 @end menu
16865 @node Running gnatclean
16866 @section Running @code{gnatclean}
16868 @noindent
16869 The @code{gnatclean} command has the form:
16871 @smallexample
16872 $ gnatclean switches @var{names}
16873 @end smallexample
16875 @noindent
16876 @var{names} is a list of source file names. Suffixes @code{.ads} and
16877 @code{adb} may be omitted. If a project file is specified using switch
16878 @code{-P}, then @var{names} may be completely omitted.
16880 @noindent
16881 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16882 if switch @code{-c} is not specified, by the binder and
16883 the linker. In informative-only mode, specified by switch
16884 @code{-n}, the list of files that would have been deleted in
16885 normal mode is listed, but no file is actually deleted.
16887 @node Switches for gnatclean
16888 @section Switches for @code{gnatclean}
16890 @noindent
16891 @code{gnatclean} recognizes the following switches:
16893 @table @option
16894 @c !sort!
16895 @cindex @option{--version} @command{gnatclean}
16896 Display Copyright and version, then exit disregarding all other options.
16898 @item --help
16899 @cindex @option{--help} @command{gnatclean}
16900 If @option{--version} was not used, display usage, then exit disregarding
16901 all other options.
16903 @item --subdirs=subdir
16904 Actual object directory of each project file is the subdirectory subdir of the
16905 object directory specified or defaulted in the project file.
16907 @item --unchecked-shared-lib-imports
16908 By default, shared library projects are not allowed to import static library
16909 projects. When this switch is used on the command line, this restriction is
16910 relaxed.
16912 @item -c
16913 @cindex @option{-c} (@code{gnatclean})
16914 Only attempt to delete the files produced by the compiler, not those produced
16915 by the binder or the linker. The files that are not to be deleted are library
16916 files, interface copy files, binder generated files and executable files.
16918 @item -D @var{dir}
16919 @cindex @option{-D} (@code{gnatclean})
16920 Indicate that ALI and object files should normally be found in directory
16921 @var{dir}.
16923 @item -F
16924 @cindex @option{-F} (@code{gnatclean})
16925 When using project files, if some errors or warnings are detected during
16926 parsing and verbose mode is not in effect (no use of switch
16927 -v), then error lines start with the full path name of the project
16928 file, rather than its simple file name.
16930 @item -h
16931 @cindex @option{-h} (@code{gnatclean})
16932 Output a message explaining the usage of @code{gnatclean}.
16934 @item -n
16935 @cindex @option{-n} (@code{gnatclean})
16936 Informative-only mode. Do not delete any files. Output the list of the files
16937 that would have been deleted if this switch was not specified.
16939 @item -P@var{project}
16940 @cindex @option{-P} (@code{gnatclean})
16941 Use project file @var{project}. Only one such switch can be used.
16942 When cleaning a project file, the files produced by the compilation of the
16943 immediate sources or inherited sources of the project files are to be
16944 deleted. This is not depending on the presence or not of executable names
16945 on the command line.
16947 @item -q
16948 @cindex @option{-q} (@code{gnatclean})
16949 Quiet output. If there are no errors, do not output anything, except in
16950 verbose mode (switch -v) or in informative-only mode
16951 (switch -n).
16953 @item -r
16954 @cindex @option{-r} (@code{gnatclean})
16955 When a project file is specified (using switch -P),
16956 clean all imported and extended project files, recursively. If this switch
16957 is not specified, only the files related to the main project file are to be
16958 deleted. This switch has no effect if no project file is specified.
16960 @item -v
16961 @cindex @option{-v} (@code{gnatclean})
16962 Verbose mode.
16964 @item -vP@emph{x}
16965 @cindex @option{-vP} (@code{gnatclean})
16966 Indicates the verbosity of the parsing of GNAT project files.
16967 @xref{Switches Related to Project Files}.
16969 @item -X@var{name=value}
16970 @cindex @option{-X} (@code{gnatclean})
16971 Indicates that external variable @var{name} has the value @var{value}.
16972 The Project Manager will use this value for occurrences of
16973 @code{external(name)} when parsing the project file.
16974 @xref{Switches Related to Project Files}.
16976 @item -aO@var{dir}
16977 @cindex @option{-aO} (@code{gnatclean})
16978 When searching for ALI and object files, look in directory
16979 @var{dir}.
16981 @item -I@var{dir}
16982 @cindex @option{-I} (@code{gnatclean})
16983 Equivalent to @option{-aO@var{dir}}.
16985 @item -I-
16986 @cindex @option{-I-} (@code{gnatclean})
16987 @cindex Source files, suppressing search
16988 Do not look for ALI or object files in the directory
16989 where @code{gnatclean} was invoked.
16991 @end table
16993 @c @node Examples of gnatclean Usage
16994 @c @section Examples of @code{gnatclean} Usage
16996 @node GNAT and Libraries
16997 @chapter GNAT and Libraries
16998 @cindex Library, building, installing, using
17000 @noindent
17001 This chapter describes how to build and use libraries with GNAT, and also shows
17002 how to recompile the GNAT run-time library. You should be familiar with the
17003 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17004 chapter.
17006 @menu
17007 * Introduction to Libraries in GNAT::
17008 * General Ada Libraries::
17009 * Stand-alone Ada Libraries::
17010 * Rebuilding the GNAT Run-Time Library::
17011 @end menu
17013 @node Introduction to Libraries in GNAT
17014 @section Introduction to Libraries in GNAT
17016 @noindent
17017 A library is, conceptually, a collection of objects which does not have its
17018 own main thread of execution, but rather provides certain services to the
17019 applications that use it. A library can be either statically linked with the
17020 application, in which case its code is directly included in the application,
17021 or, on platforms that support it, be dynamically linked, in which case
17022 its code is shared by all applications making use of this library.
17024 GNAT supports both types of libraries.
17025 In the static case, the compiled code can be provided in different ways. The
17026 simplest approach is to provide directly the set of objects resulting from
17027 compilation of the library source files. Alternatively, you can group the
17028 objects into an archive using whatever commands are provided by the operating
17029 system. For the latter case, the objects are grouped into a shared library.
17031 In the GNAT environment, a library has three types of components:
17032 @itemize @bullet
17033 @item
17034 Source files.
17035 @item
17036 @file{ALI} files.
17037 @xref{The Ada Library Information Files}.
17038 @item
17039 Object files, an archive or a shared library.
17040 @end itemize
17042 @noindent
17043 A GNAT library may expose all its source files, which is useful for
17044 documentation purposes. Alternatively, it may expose only the units needed by
17045 an external user to make use of the library. That is to say, the specs
17046 reflecting the library services along with all the units needed to compile
17047 those specs, which can include generic bodies or any body implementing an
17048 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17049 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17051 All compilation units comprising an application, including those in a library,
17052 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17053 computes the elaboration order from the @file{ALI} files and this is why they
17054 constitute a mandatory part of GNAT libraries.
17055 @emph{Stand-alone libraries} are the exception to this rule because a specific
17056 library elaboration routine is produced independently of the application(s)
17057 using the library.
17059 @node General Ada Libraries
17060 @section General Ada Libraries
17062 @menu
17063 * Building a library::
17064 * Installing a library::
17065 * Using a library::
17066 @end menu
17068 @node Building a library
17069 @subsection Building a library
17071 @noindent
17072 The easiest way to build a library is to use the Project Manager,
17073 which supports a special type of project called a @emph{Library Project}
17074 (@pxref{Library Projects}).
17076 A project is considered a library project, when two project-level attributes
17077 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17078 control different aspects of library configuration, additional optional
17079 project-level attributes can be specified:
17080 @table @code
17081 @item Library_Kind
17082 This attribute controls whether the library is to be static or dynamic
17084 @item Library_Version
17085 This attribute specifies the library version; this value is used
17086 during dynamic linking of shared libraries to determine if the currently
17087 installed versions of the binaries are compatible.
17089 @item Library_Options
17090 @item Library_GCC
17091 These attributes specify additional low-level options to be used during
17092 library generation, and redefine the actual application used to generate
17093 library.
17094 @end table
17096 @noindent
17097 The GNAT Project Manager takes full care of the library maintenance task,
17098 including recompilation of the source files for which objects do not exist
17099 or are not up to date, assembly of the library archive, and installation of
17100 the library (i.e., copying associated source, object and @file{ALI} files
17101 to the specified location).
17103 Here is a simple library project file:
17104 @smallexample @c ada
17105 project My_Lib @b{is}
17106    @b{for} Source_Dirs @b{use} ("src1", "src2");
17107    @b{for} Object_Dir @b{use} "obj";
17108    @b{for} Library_Name @b{use} "mylib";
17109    @b{for} Library_Dir @b{use} "lib";
17110    @b{for} Library_Kind @b{use} "dynamic";
17111 @b{end} My_lib;
17112 @end smallexample
17114 @noindent
17115 and the compilation command to build and install the library:
17117 @smallexample @c ada
17118   $ gnatmake -Pmy_lib
17119 @end smallexample
17121 @noindent
17122 It is not entirely trivial to perform manually all the steps required to
17123 produce a library. We recommend that you use the GNAT Project Manager
17124 for this task. In special cases where this is not desired, the necessary
17125 steps are discussed below.
17127 There are various possibilities for compiling the units that make up the
17128 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17129 with a conventional script. For simple libraries, it is also possible to create
17130 a dummy main program which depends upon all the packages that comprise the
17131 interface of the library. This dummy main program can then be given to
17132 @command{gnatmake}, which will ensure that all necessary objects are built.
17134 After this task is accomplished, you should follow the standard procedure
17135 of the underlying operating system to produce the static or shared library.
17137 Here is an example of such a dummy program:
17138 @smallexample @c ada
17139 @group
17140 @b{with} My_Lib.Service1;
17141 @b{with} My_Lib.Service2;
17142 @b{with} My_Lib.Service3;
17143 @b{procedure} My_Lib_Dummy @b{is}
17144 @b{begin}
17145    @b{null};
17146 @b{end};
17147 @end group
17148 @end smallexample
17150 @noindent
17151 Here are the generic commands that will build an archive or a shared library.
17153 @smallexample
17154 # compiling the library
17155 $ gnatmake -c my_lib_dummy.adb
17157 # we don't need the dummy object itself
17158 $ rm my_lib_dummy.o my_lib_dummy.ali
17160 # create an archive with the remaining objects
17161 $ ar rc libmy_lib.a *.o
17162 # some systems may require "ranlib" to be run as well
17164 # or create a shared library
17165 $ gcc -shared -o libmy_lib.so *.o
17166 # some systems may require the code to have been compiled with -fPIC
17168 # remove the object files that are now in the library
17169 $ rm *.o
17171 # Make the ALI files read-only so that gnatmake will not try to
17172 # regenerate the objects that are in the library
17173 $ chmod -w *.ali
17174 @end smallexample
17176 @noindent
17177 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17178 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17179 be accessed by the directive @option{-l@var{xxx}} at link time.
17181 @node Installing a library
17182 @subsection Installing a library
17183 @cindex @code{ADA_PROJECT_PATH}
17184 @cindex @code{GPR_PROJECT_PATH}
17186 @noindent
17187 If you use project files, library installation is part of the library build
17188 process (@pxref{Installing a library with project files}).
17190 When project files are not an option, it is also possible, but not recommended,
17191 to install the library so that the sources needed to use the library are on the
17192 Ada source path and the ALI files & libraries be on the Ada Object path (see
17193 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17194 administrator can place general-purpose libraries in the default compiler
17195 paths, by specifying the libraries' location in the configuration files
17196 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17197 must be located in the GNAT installation tree at the same place as the gcc spec
17198 file. The location of the gcc spec file can be determined as follows:
17199 @smallexample
17200 $ gcc -v
17201 @end smallexample
17203 @noindent
17204 The configuration files mentioned above have a simple format: each line
17205 must contain one unique directory name.
17206 Those names are added to the corresponding path
17207 in their order of appearance in the file. The names can be either absolute
17208 or relative; in the latter case, they are relative to where theses files
17209 are located.
17211 The files @file{ada_source_path} and @file{ada_object_path} might not be
17212 present in a
17213 GNAT installation, in which case, GNAT will look for its run-time library in
17214 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17215 objects and @file{ALI} files). When the files exist, the compiler does not
17216 look in @file{adainclude} and @file{adalib}, and thus the
17217 @file{ada_source_path} file
17218 must contain the location for the GNAT run-time sources (which can simply
17219 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17220 contain the location for the GNAT run-time objects (which can simply
17221 be @file{adalib}).
17223 You can also specify a new default path to the run-time library at compilation
17224 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17225 the run-time library you want your program to be compiled with. This switch is
17226 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17227 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17229 It is possible to install a library before or after the standard GNAT
17230 library, by reordering the lines in the configuration files. In general, a
17231 library must be installed before the GNAT library if it redefines
17232 any part of it.
17234 @node Using a library
17235 @subsection Using a library
17237 @noindent Once again, the project facility greatly simplifies the use of
17238 libraries. In this context, using a library is just a matter of adding a
17239 @code{with} clause in the user project. For instance, to make use of the
17240 library @code{My_Lib} shown in examples in earlier sections, you can
17241 write:
17243 @smallexample @c projectfile
17244 @b{with} "my_lib";
17245 @b{project} My_Proj @b{is}
17246   @dots{}
17247 @b{end} My_Proj;
17248 @end smallexample
17250 Even if you have a third-party, non-Ada library, you can still use GNAT's
17251 Project Manager facility to provide a wrapper for it. For example, the
17252 following project, when @code{with}ed by your main project, will link with the
17253 third-party library @file{liba.a}:
17255 @smallexample @c projectfile
17256 @group
17257 @b{project} Liba @b{is}
17258    @b{for} Externally_Built @b{use} "true";
17259    @b{for} Source_Files @b{use} ();
17260    @b{for} Library_Dir @b{use} "lib";
17261    @b{for} Library_Name @b{use} "a";
17262    @b{for} Library_Kind @b{use} "static";
17263 @b{end} Liba;
17264 @end group
17265 @end smallexample
17266 This is an alternative to the use of @code{pragma Linker_Options}. It is
17267 especially interesting in the context of systems with several interdependent
17268 static libraries where finding a proper linker order is not easy and best be
17269 left to the tools having visibility over project dependence information.
17271 @noindent
17272 In order to use an Ada library manually, you need to make sure that this
17273 library is on both your source and object path
17274 (see @ref{Search Paths and the Run-Time Library (RTL)}
17275 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17276 in an archive or a shared library, you need to specify the desired
17277 library at link time.
17279 For example, you can use the library @file{mylib} installed in
17280 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17282 @smallexample
17283 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17284   -largs -lmy_lib
17285 @end smallexample
17287 @noindent
17288 This can be expressed more simply:
17289 @smallexample
17290 $ gnatmake my_appl
17291 @end smallexample
17292 @noindent
17293 when the following conditions are met:
17294 @itemize @bullet
17295 @item
17296 @file{/dir/my_lib_src} has been added by the user to the environment
17297 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17298 @file{ada_source_path}
17299 @item
17300 @file{/dir/my_lib_obj} has been added by the user to the environment
17301 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17302 @file{ada_object_path}
17303 @item
17304 a pragma @code{Linker_Options} has been added to one of the sources.
17305 For example:
17307 @smallexample @c ada
17308 @b{pragma} Linker_Options ("-lmy_lib");
17309 @end smallexample
17310 @end itemize
17312 Note that you may also load a library dynamically at
17313 run time given its filename, as illustrated in the GNAT @file{plugins} example
17314 in the directory @file{share/examples/gnat/plugins} within the GNAT
17315 install area.
17317 @node Stand-alone Ada Libraries
17318 @section Stand-alone Ada Libraries
17319 @cindex Stand-alone library, building, using
17321 @menu
17322 * Introduction to Stand-alone Libraries::
17323 * Building a Stand-alone Library::
17324 * Creating a Stand-alone Library to be used in a non-Ada context::
17325 * Restrictions in Stand-alone Libraries::
17326 @end menu
17328 @node Introduction to Stand-alone Libraries
17329 @subsection Introduction to Stand-alone Libraries
17331 @noindent
17332 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17333 necessary code to
17334 elaborate the Ada units that are included in the library. In contrast with
17335 an ordinary library, which consists of all sources, objects and @file{ALI}
17336 files of the
17337 library, a SAL may specify a restricted subset of compilation units
17338 to serve as a library interface. In this case, the fully
17339 self-sufficient set of files will normally consist of an objects
17340 archive, the sources of interface units' specs, and the @file{ALI}
17341 files of interface units.
17342 If an interface spec contains a generic unit or an inlined subprogram,
17343 the body's
17344 source must also be provided; if the units that must be provided in the source
17345 form depend on other units, the source and @file{ALI} files of those must
17346 also be provided.
17348 The main purpose of a SAL is to minimize the recompilation overhead of client
17349 applications when a new version of the library is installed. Specifically,
17350 if the interface sources have not changed, client applications do not need to
17351 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17352 version, controlled by @code{Library_Version} attribute, is not changed,
17353 then the clients do not need to be relinked.
17355 SALs also allow the library providers to minimize the amount of library source
17356 text exposed to the clients.  Such ``information hiding'' might be useful or
17357 necessary for various reasons.
17359 Stand-alone libraries are also well suited to be used in an executable whose
17360 main routine is not written in Ada.
17362 @node Building a Stand-alone Library
17363 @subsection Building a Stand-alone Library
17365 @noindent
17366 GNAT's Project facility provides a simple way of building and installing
17367 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17368 To be a Stand-alone Library Project, in addition to the two attributes
17369 that make a project a Library Project (@code{Library_Name} and
17370 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17371 @code{Library_Interface} must be defined.  For example:
17373 @smallexample @c projectfile
17374 @group
17375    @b{for} Library_Dir @b{use} "lib_dir";
17376    @b{for} Library_Name @b{use} "dummy";
17377    @b{for} Library_Interface @b{use} ("int1", "int1.child");
17378 @end group
17379 @end smallexample
17381 @noindent
17382 Attribute @code{Library_Interface} has a non-empty string list value,
17383 each string in the list designating a unit contained in an immediate source
17384 of the project file.
17386 When a Stand-alone Library is built, first the binder is invoked to build
17387 a package whose name depends on the library name
17388 (@file{b~dummy.ads/b} in the example above).
17389 This binder-generated package includes initialization and
17390 finalization procedures whose
17391 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17392 in the example
17393 above). The object corresponding to this package is included in the library.
17395 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17396 calling of these procedures if a static SAL is built, or if a shared SAL
17397 is built
17398 with the project-level attribute @code{Library_Auto_Init} set to
17399 @code{"false"}.
17401 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17402 (those that are listed in attribute @code{Library_Interface}) are copied to
17403 the Library Directory. As a consequence, only the Interface Units may be
17404 imported from Ada units outside of the library. If other units are imported,
17405 the binding phase will fail.
17407 @noindent
17408 It is also possible to build an encapsulated library where not only
17409 the code to elaborate and finalize the library is embedded but also
17410 ensuring that the library is linked only against static
17411 libraries. So an encapsulated library only depends on system
17412 libraries, all other code, including the GNAT runtime, is embedded. To
17413 build an encapsulated library the attribute
17414 @code{Library_Standalone} must be set to @code{encapsulated}:
17416 @smallexample @c projectfile
17417 @group
17418    @b{for} Library_Dir @b{use} "lib_dir";
17419    @b{for} Library_Name @b{use} "dummy";
17420    @b{for} Library_Kind @b{use} "dynamic";
17421    @b{for} Library_Interface @b{use} ("int1", "int1.child");
17422    @b{for} Library_Standalone @b{use} "encapsulated";
17423 @end group
17424 @end smallexample
17426 @noindent
17427 The default value for this attribute is @code{standard} in which case
17428 a stand-alone library is built.
17430 The attribute @code{Library_Src_Dir} may be specified for a
17431 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17432 single string value. Its value must be the path (absolute or relative to the
17433 project directory) of an existing directory. This directory cannot be the
17434 object directory or one of the source directories, but it can be the same as
17435 the library directory. The sources of the Interface
17436 Units of the library that are needed by an Ada client of the library will be
17437 copied to the designated directory, called the Interface Copy directory.
17438 These sources include the specs of the Interface Units, but they may also
17439 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17440 are used, or when there is a generic unit in the spec. Before the sources
17441 are copied to the Interface Copy directory, an attempt is made to delete all
17442 files in the Interface Copy directory.
17444 Building stand-alone libraries by hand is somewhat tedious, but for those
17445 occasions when it is necessary here are the steps that you need to perform:
17446 @itemize @bullet
17447 @item
17448 Compile all library sources.
17450 @item
17451 Invoke the binder with the switch @option{-n} (No Ada main program),
17452 with all the @file{ALI} files of the interfaces, and
17453 with the switch @option{-L} to give specific names to the @code{init}
17454 and @code{final} procedures.  For example:
17455 @smallexample
17456   gnatbind -n int1.ali int2.ali -Lsal1
17457 @end smallexample
17459 @item
17460 Compile the binder generated file:
17461 @smallexample
17462   gcc -c b~int2.adb
17463 @end smallexample
17465 @item
17466 Link the dynamic library with all the necessary object files,
17467 indicating to the linker the names of the @code{init} (and possibly
17468 @code{final}) procedures for automatic initialization (and finalization).
17469 The built library should be placed in a directory different from
17470 the object directory.
17472 @item
17473 Copy the @code{ALI} files of the interface to the library directory,
17474 add in this copy an indication that it is an interface to a SAL
17475 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17476 with letter ``P'') and make the modified copy of the @file{ALI} file
17477 read-only.
17478 @end itemize
17480 @noindent
17481 Using SALs is not different from using other libraries
17482 (see @ref{Using a library}).
17484 @node Creating a Stand-alone Library to be used in a non-Ada context
17485 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17487 @noindent
17488 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17489 a non-Ada context.
17491 The only extra step required is to ensure that library interface subprograms
17492 are compatible with the main program, by means of @code{pragma Export}
17493 or @code{pragma Convention}.
17495 Here is an example of simple library interface for use with C main program:
17497 @smallexample @c ada
17498 @b{package} My_Package @b{is}
17500    @b{procedure} Do_Something;
17501    @b{pragma} Export (C, Do_Something, "do_something");
17503    @b{procedure} Do_Something_Else;
17504    @b{pragma} Export (C, Do_Something_Else, "do_something_else");
17506 @b{end} My_Package;
17507 @end smallexample
17509 @noindent
17510 On the foreign language side, you must provide a ``foreign'' view of the
17511 library interface; remember that it should contain elaboration routines in
17512 addition to interface subprograms.
17514 The example below shows the content of @code{mylib_interface.h} (note
17515 that there is no rule for the naming of this file, any name can be used)
17516 @smallexample
17517 /* the library elaboration procedure */
17518 extern void mylibinit (void);
17520 /* the library finalization procedure */
17521 extern void mylibfinal (void);
17523 /* the interface exported by the library */
17524 extern void do_something (void);
17525 extern void do_something_else (void);
17526 @end smallexample
17528 @noindent
17529 Libraries built as explained above can be used from any program, provided
17530 that the elaboration procedures (named @code{mylibinit} in the previous
17531 example) are called before the library services are used. Any number of
17532 libraries can be used simultaneously, as long as the elaboration
17533 procedure of each library is called.
17535 Below is an example of a C program that uses the @code{mylib} library.
17537 @smallexample
17538 #include "mylib_interface.h"
17541 main (void)
17543    /* First, elaborate the library before using it */
17544    mylibinit ();
17546    /* Main program, using the library exported entities */
17547    do_something ();
17548    do_something_else ();
17550    /* Library finalization at the end of the program */
17551    mylibfinal ();
17552    return 0;
17554 @end smallexample
17556 @noindent
17557 Note that invoking any library finalization procedure generated by
17558 @code{gnatbind} shuts down the Ada run-time environment.
17559 Consequently, the
17560 finalization of all Ada libraries must be performed at the end of the program.
17561 No call to these libraries or to the Ada run-time library should be made
17562 after the finalization phase.
17564 @noindent
17565 Note also that special care must be taken with multi-tasks
17566 applications. The initialization and finalization routines are not
17567 protected against concurrent access. If such requirement is needed it
17568 must be ensured at the application level using a specific operating
17569 system services like a mutex or a critical-section.
17571 @node Restrictions in Stand-alone Libraries
17572 @subsection Restrictions in Stand-alone Libraries
17574 @noindent
17575 The pragmas listed below should be used with caution inside libraries,
17576 as they can create incompatibilities with other Ada libraries:
17577 @itemize @bullet
17578 @item pragma @code{Locking_Policy}
17579 @item pragma @code{Partition_Elaboration_Policy}
17580 @item pragma @code{Queuing_Policy}
17581 @item pragma @code{Task_Dispatching_Policy}
17582 @item pragma @code{Unreserve_All_Interrupts}
17583 @end itemize
17585 @noindent
17586 When using a library that contains such pragmas, the user must make sure
17587 that all libraries use the same pragmas with the same values. Otherwise,
17588 @code{Program_Error} will
17589 be raised during the elaboration of the conflicting
17590 libraries. The usage of these pragmas and its consequences for the user
17591 should therefore be well documented.
17593 Similarly, the traceback in the exception occurrence mechanism should be
17594 enabled or disabled in a consistent manner across all libraries.
17595 Otherwise, Program_Error will be raised during the elaboration of the
17596 conflicting libraries.
17598 If the @code{Version} or @code{Body_Version}
17599 attributes are used inside a library, then you need to
17600 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17601 libraries, so that version identifiers can be properly computed.
17602 In practice these attributes are rarely used, so this is unlikely
17603 to be a consideration.
17605 @node  Rebuilding the GNAT Run-Time Library
17606 @section Rebuilding the GNAT Run-Time Library
17607 @cindex GNAT Run-Time Library, rebuilding
17608 @cindex Building the GNAT Run-Time Library
17609 @cindex Rebuilding the GNAT Run-Time Library
17610 @cindex Run-Time Library, rebuilding
17612 @noindent
17613 It may be useful to recompile the GNAT library in various contexts, the
17614 most important one being the use of partition-wide configuration pragmas
17615 such as @code{Normalize_Scalars}. A special Makefile called
17616 @code{Makefile.adalib} is provided to that effect and can be found in
17617 the directory containing the GNAT library. The location of this
17618 directory depends on the way the GNAT environment has been installed and can
17619 be determined by means of the command:
17621 @smallexample
17622 $ gnatls -v
17623 @end smallexample
17625 @noindent
17626 The last entry in the object search path usually contains the
17627 gnat library. This Makefile contains its own documentation and in
17628 particular the set of instructions needed to rebuild a new library and
17629 to use it.
17631 @node Using the GNU make Utility
17632 @chapter Using the GNU @code{make} Utility
17633 @findex make
17635 @noindent
17636 This chapter offers some examples of makefiles that solve specific
17637 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
17638 make, make, GNU @code{make}}), nor does it try to replace the
17639 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
17641 All the examples in this section are specific to the GNU version of
17642 make. Although @command{make} is a standard utility, and the basic language
17643 is the same, these examples use some advanced features found only in
17644 @code{GNU make}.
17646 @menu
17647 * Using gnatmake in a Makefile::
17648 * Automatically Creating a List of Directories::
17649 * Generating the Command Line Switches::
17650 * Overcoming Command Line Length Limits::
17651 @end menu
17653 @node Using gnatmake in a Makefile
17654 @section Using gnatmake in a Makefile
17655 @findex makefile
17656 @cindex GNU make
17658 @noindent
17659 Complex project organizations can be handled in a very powerful way by
17660 using GNU make combined with gnatmake. For instance, here is a Makefile
17661 which allows you to build each subsystem of a big project into a separate
17662 shared library. Such a makefile allows you to significantly reduce the link
17663 time of very big applications while maintaining full coherence at
17664 each step of the build process.
17666 The list of dependencies are handled automatically by
17667 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17668 the appropriate directories.
17670 Note that you should also read the example on how to automatically
17671 create the list of directories
17672 (@pxref{Automatically Creating a List of Directories})
17673 which might help you in case your project has a lot of subdirectories.
17675 @smallexample
17676 @iftex
17677 @leftskip=0cm
17678 @font@heightrm=cmr8
17679 @heightrm
17680 @end iftex
17681 ## This Makefile is intended to be used with the following directory
17682 ## configuration:
17683 ##  - The sources are split into a series of csc (computer software components)
17684 ##    Each of these csc is put in its own directory.
17685 ##    Their name are referenced by the directory names.
17686 ##    They will be compiled into shared library (although this would also work
17687 ##    with static libraries
17688 ##  - The main program (and possibly other packages that do not belong to any
17689 ##    csc is put in the top level directory (where the Makefile is).
17690 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17691 ##                    \_ second_csc (sources) __ lib (will contain the library)
17692 ##                    \_ @dots{}
17693 ## Although this Makefile is build for shared library, it is easy to modify
17694 ## to build partial link objects instead (modify the lines with -shared and
17695 ## gnatlink below)
17697 ## With this makefile, you can change any file in the system or add any new
17698 ## file, and everything will be recompiled correctly (only the relevant shared
17699 ## objects will be recompiled, and the main program will be re-linked).
17701 # The list of computer software component for your project. This might be
17702 # generated automatically.
17703 CSC_LIST=aa bb cc
17705 # Name of the main program (no extension)
17706 MAIN=main
17708 # If we need to build objects with -fPIC, uncomment the following line
17709 #NEED_FPIC=-fPIC
17711 # The following variable should give the directory containing libgnat.so
17712 # You can get this directory through 'gnatls -v'. This is usually the last
17713 # directory in the Object_Path.
17714 GLIB=@dots{}
17716 # The directories for the libraries
17717 # (This macro expands the list of CSC to the list of shared libraries, you
17718 # could simply use the expanded form:
17719 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17720 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17722 $@{MAIN@}: objects $@{LIB_DIR@}
17723     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17724     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17726 objects::
17727     # recompile the sources
17728     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17730 # Note: In a future version of GNAT, the following commands will be simplified
17731 # by a new tool, gnatmlib
17732 $@{LIB_DIR@}:
17733     mkdir -p $@{dir $@@ @}
17734     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17735     cd $@{dir $@@ @} && cp -f ../*.ali .
17737 # The dependencies for the modules
17738 # Note that we have to force the expansion of *.o, since in some cases
17739 # make won't be able to do it itself.
17740 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17741 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17742 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17744 # Make sure all of the shared libraries are in the path before starting the
17745 # program
17746 run::
17747     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17749 clean::
17750     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17751     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17752     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17753     $@{RM@} *.o *.ali $@{MAIN@}
17754 @end smallexample
17756 @node Automatically Creating a List of Directories
17757 @section Automatically Creating a List of Directories
17759 @noindent
17760 In most makefiles, you will have to specify a list of directories, and
17761 store it in a variable. For small projects, it is often easier to
17762 specify each of them by hand, since you then have full control over what
17763 is the proper order for these directories, which ones should be
17764 included.
17766 However, in larger projects, which might involve hundreds of
17767 subdirectories, it might be more convenient to generate this list
17768 automatically.
17770 The example below presents two methods. The first one, although less
17771 general, gives you more control over the list. It involves wildcard
17772 characters, that are automatically expanded by @command{make}. Its
17773 shortcoming is that you need to explicitly specify some of the
17774 organization of your project, such as for instance the directory tree
17775 depth, whether some directories are found in a separate tree, @enddots{}
17777 The second method is the most general one. It requires an external
17778 program, called @command{find}, which is standard on all Unix systems. All
17779 the directories found under a given root directory will be added to the
17780 list.
17782 @smallexample
17783 @iftex
17784 @leftskip=0cm
17785 @font@heightrm=cmr8
17786 @heightrm
17787 @end iftex
17788 # The examples below are based on the following directory hierarchy:
17789 # All the directories can contain any number of files
17790 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17791 #                       ->  ab
17792 #                       ->  ac
17793 #                ->  b  ->  ba  ->  baa
17794 #                       ->  bb
17795 #                       ->  bc
17796 # This Makefile creates a variable called DIRS, that can be reused any time
17797 # you need this list (see the other examples in this section)
17799 # The root of your project's directory hierarchy
17800 ROOT_DIRECTORY=.
17802 ####
17803 # First method: specify explicitly the list of directories
17804 # This allows you to specify any subset of all the directories you need.
17805 ####
17807 DIRS := a/aa/ a/ab/ b/ba/
17809 ####
17810 # Second method: use wildcards
17811 # Note that the argument(s) to wildcard below should end with a '/'.
17812 # Since wildcards also return file names, we have to filter them out
17813 # to avoid duplicate directory names.
17814 # We thus use make's @code{dir} and @code{sort} functions.
17815 # It sets DIRs to the following value (note that the directories aaa and baa
17816 # are not given, unless you change the arguments to wildcard).
17817 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17818 ####
17820 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17821                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17823 ####
17824 # Third method: use an external program
17825 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17826 # This is the most complete command: it sets DIRs to the following value:
17827 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17828 ####
17830 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17832 @end smallexample
17834 @node Generating the Command Line Switches
17835 @section Generating the Command Line Switches
17837 @noindent
17838 Once you have created the list of directories as explained in the
17839 previous section (@pxref{Automatically Creating a List of Directories}),
17840 you can easily generate the command line arguments to pass to gnatmake.
17842 For the sake of completeness, this example assumes that the source path
17843 is not the same as the object path, and that you have two separate lists
17844 of directories.
17846 @smallexample
17847 # see "Automatically creating a list of directories" to create
17848 # these variables
17849 SOURCE_DIRS=
17850 OBJECT_DIRS=
17852 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17853 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17855 all:
17856         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17857 @end smallexample
17859 @node Overcoming Command Line Length Limits
17860 @section Overcoming Command Line Length Limits
17862 @noindent
17863 One problem that might be encountered on big projects is that many
17864 operating systems limit the length of the command line. It is thus hard to give
17865 gnatmake the list of source and object directories.
17867 This example shows how you can set up environment variables, which will
17868 make @command{gnatmake} behave exactly as if the directories had been
17869 specified on the command line, but have a much higher length limit (or
17870 even none on most systems).
17872 It assumes that you have created a list of directories in your Makefile,
17873 using one of the methods presented in
17874 @ref{Automatically Creating a List of Directories}.
17875 For the sake of completeness, we assume that the object
17876 path (where the ALI files are found) is different from the sources patch.
17878 Note a small trick in the Makefile below: for efficiency reasons, we
17879 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17880 expanded immediately by @code{make}. This way we overcome the standard
17881 make behavior which is to expand the variables only when they are
17882 actually used.
17884 On Windows, if you are using the standard Windows command shell, you must
17885 replace colons with semicolons in the assignments to these variables.
17887 @smallexample
17888 @iftex
17889 @leftskip=0cm
17890 @font@heightrm=cmr8
17891 @heightrm
17892 @end iftex
17893 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17894 # This is the same thing as putting the -I arguments on the command line.
17895 # (the equivalent of using -aI on the command line would be to define
17896 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17897 # You can of course have different values for these variables.
17899 # Note also that we need to keep the previous values of these variables, since
17900 # they might have been set before running 'make' to specify where the GNAT
17901 # library is installed.
17903 # see "Automatically creating a list of directories" to create these
17904 # variables
17905 SOURCE_DIRS=
17906 OBJECT_DIRS=
17908 empty:=
17909 space:=$@{empty@} $@{empty@}
17910 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17911 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17912 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17913 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17914 export ADA_INCLUDE_PATH
17915 export ADA_OBJECTS_PATH
17917 all:
17918         gnatmake main_unit
17919 @end smallexample
17921 @node Memory Management Issues
17922 @chapter Memory Management Issues
17924 @noindent
17925 This chapter describes some useful memory pools provided in the GNAT library
17926 and in particular the GNAT Debug Pool facility, which can be used to detect
17927 incorrect uses of access values (including ``dangling references'').
17928 @ifclear FSFEDITION
17929 It also describes the @command{gnatmem} tool, which can be used to track down
17930 ``memory leaks''.
17931 @end ifclear
17933 @menu
17934 * Some Useful Memory Pools::
17935 * The GNAT Debug Pool Facility::
17936 @ifclear FSFEDITION
17937 * The gnatmem Tool::
17938 @end ifclear
17939 @end menu
17941 @node Some Useful Memory Pools
17942 @section Some Useful Memory Pools
17943 @findex Memory Pool
17944 @cindex storage, pool
17946 @noindent
17947 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17948 storage pool. Allocations use the standard system call @code{malloc} while
17949 deallocations use the standard system call @code{free}. No reclamation is
17950 performed when the pool goes out of scope. For performance reasons, the
17951 standard default Ada allocators/deallocators do not use any explicit storage
17952 pools but if they did, they could use this storage pool without any change in
17953 behavior. That is why this storage pool is used  when the user
17954 manages to make the default implicit allocator explicit as in this example:
17955 @smallexample @c ada
17956    @b{type} T1 @b{is} @b{access} Something;
17957     --@i{ no Storage pool is defined for T2}
17958    @b{type} T2 @b{is} @b{access} Something_Else;
17959    @b{for} T2'Storage_Pool @b{use} T1'Storage_Pool;
17960    --@i{ the above is equivalent to}
17961    @b{for} T2'Storage_Pool @b{use} System.Pool_Global.Global_Pool_Object;
17962 @end smallexample
17964 @noindent
17965 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17966 pool. The allocation strategy is similar to @code{Pool_Local}'s
17967 except that the all
17968 storage allocated with this pool is reclaimed when the pool object goes out of
17969 scope. This pool provides a explicit mechanism similar to the implicit one
17970 provided by several Ada 83 compilers for allocations performed through a local
17971 access type and whose purpose was to reclaim memory when exiting the
17972 scope of a given local access. As an example, the following program does not
17973 leak memory even though it does not perform explicit deallocation:
17975 @smallexample @c ada
17976 @b{with} System.Pool_Local;
17977 @b{procedure} Pooloc1 @b{is}
17978    @b{procedure} Internal @b{is}
17979       @b{type} A @b{is} @b{access} Integer;
17980       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17981       @b{for} A'Storage_Pool @b{use} X;
17982       v : A;
17983    @b{begin}
17984       @b{for} I @b{in}  1 .. 50 @b{loop}
17985          v := @b{new} Integer;
17986       @b{end} @b{loop};
17987    @b{end} Internal;
17988 @b{begin}
17989    @b{for} I @b{in}  1 .. 100 @b{loop}
17990       Internal;
17991    @b{end} @b{loop};
17992 @b{end} Pooloc1;
17993 @end smallexample
17995 @noindent
17996 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17997 @code{Storage_Size} is specified for an access type.
17998 The whole storage for the pool is
17999 allocated at once, usually on the stack at the point where the access type is
18000 elaborated. It is automatically reclaimed when exiting the scope where the
18001 access type is defined. This package is not intended to be used directly by the
18002 user and it is implicitly used for each such declaration:
18004 @smallexample @c ada
18005    @b{type} T1 @b{is} @b{access} Something;
18006    @b{for} T1'Storage_Size @b{use} 10_000;
18007 @end smallexample
18009 @node The GNAT Debug Pool Facility
18010 @section The GNAT Debug Pool Facility
18011 @findex Debug Pool
18012 @cindex storage, pool, memory corruption
18014 @noindent
18015 The use of unchecked deallocation and unchecked conversion can easily
18016 lead to incorrect memory references. The problems generated by such
18017 references are usually difficult to tackle because the symptoms can be
18018 very remote from the origin of the problem. In such cases, it is
18019 very helpful to detect the problem as early as possible. This is the
18020 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18022 In order to use the GNAT specific debugging pool, the user must
18023 associate a debug pool object with each of the access types that may be
18024 related to suspected memory problems. See Ada Reference Manual 13.11.
18025 @smallexample @c ada
18026 @b{type} Ptr @b{is} @b{access} Some_Type;
18027 Pool : GNAT.Debug_Pools.Debug_Pool;
18028 @b{for} Ptr'Storage_Pool @b{use} Pool;
18029 @end smallexample
18031 @noindent
18032 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18033 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18034 allow the user to redefine allocation and deallocation strategies. They
18035 also provide a checkpoint for each dereference, through the use of
18036 the primitive operation @code{Dereference} which is implicitly called at
18037 each dereference of an access value.
18039 Once an access type has been associated with a debug pool, operations on
18040 values of the type may raise four distinct exceptions,
18041 which correspond to four potential kinds of memory corruption:
18042 @itemize @bullet
18043 @item
18044 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18045 @item
18046 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18047 @item
18048 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18049 @item
18050 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18051 @end itemize
18053 @noindent
18054 For types associated with a Debug_Pool, dynamic allocation is performed using
18055 the standard GNAT allocation routine. References to all allocated chunks of
18056 memory are kept in an internal dictionary. Several deallocation strategies are
18057 provided, whereupon the user can choose to release the memory to the system,
18058 keep it allocated for further invalid access checks, or fill it with an easily
18059 recognizable pattern for debug sessions. The memory pattern is the old IBM
18060 hexadecimal convention: @code{16#DEADBEEF#}.
18062 See the documentation in the file g-debpoo.ads for more information on the
18063 various strategies.
18065 Upon each dereference, a check is made that the access value denotes a
18066 properly allocated memory location. Here is a complete example of use of
18067 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18068 @smallexample @c ada
18069 @iftex
18070 @leftskip=0cm
18071 @end iftex
18072 @b{with} Gnat.Io; @b{use} Gnat.Io;
18073 @b{with} Unchecked_Deallocation;
18074 @b{with} Unchecked_Conversion;
18075 @b{with} GNAT.Debug_Pools;
18076 @b{with} System.Storage_Elements;
18077 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
18078 @b{procedure} Debug_Pool_Test @b{is}
18080    @b{type} T @b{is} @b{access} Integer;
18081    @b{type} U @b{is} @b{access} @b{all} T;
18083    P : GNAT.Debug_Pools.Debug_Pool;
18084    @b{for} T'Storage_Pool @b{use} P;
18086    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
18087    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
18088    A, B : @b{aliased} T;
18090    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
18092 @b{begin}
18093    Info (P);
18094    A := @b{new} Integer;
18095    B := @b{new} Integer;
18096    B := A;
18097    Info (P);
18098    Free (A);
18099    @b{begin}
18100       Put_Line (Integer'Image(B.@b{all}));
18101    @b{exception}
18102       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18103    @b{end};
18104    @b{begin}
18105       Free (B);
18106    @b{exception}
18107       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18108    @b{end};
18109    B := UC(A'Access);
18110    @b{begin}
18111       Put_Line (Integer'Image(B.@b{all}));
18112    @b{exception}
18113       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18114    @b{end};
18115    @b{begin}
18116       Free (B);
18117    @b{exception}
18118       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18119    @b{end};
18120    Info (P);
18121 @b{end} Debug_Pool_Test;
18122 @end smallexample
18124 @noindent
18125 The debug pool mechanism provides the following precise diagnostics on the
18126 execution of this erroneous program:
18127 @smallexample
18128 Debug Pool info:
18129   Total allocated bytes :  0
18130   Total deallocated bytes :  0
18131   Current Water Mark:  0
18132   High Water Mark:  0
18134 Debug Pool info:
18135   Total allocated bytes :  8
18136   Total deallocated bytes :  0
18137   Current Water Mark:  8
18138   High Water Mark:  8
18140 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18141 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18142 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18143 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18144 Debug Pool info:
18145   Total allocated bytes :  8
18146   Total deallocated bytes :  4
18147   Current Water Mark:  4
18148   High Water Mark:  8
18149 @end smallexample
18151 @ifclear FSFEDITION
18152 @node The gnatmem Tool
18153 @section The @command{gnatmem} Tool
18154 @findex gnatmem
18156 @noindent
18157 The @code{gnatmem} utility monitors dynamic allocation and
18158 deallocation activity in a program, and displays information about
18159 incorrect deallocations and possible sources of memory leaks.
18160 It is designed to work in association with a static runtime library
18161 only and in this context provides three types of information:
18162 @itemize @bullet
18163 @item
18164 General information concerning memory management, such as the total
18165 number of allocations and deallocations, the amount of allocated
18166 memory and the high water mark, i.e.@: the largest amount of allocated
18167 memory in the course of program execution.
18169 @item
18170 Backtraces for all incorrect deallocations, that is to say deallocations
18171 which do not correspond to a valid allocation.
18173 @item
18174 Information on each allocation that is potentially the origin of a memory
18175 leak.
18176 @end itemize
18178 @menu
18179 * Running gnatmem::
18180 * Switches for gnatmem::
18181 * Example of gnatmem Usage::
18182 @end menu
18184 @node Running gnatmem
18185 @subsection Running @code{gnatmem}
18187 @noindent
18188 @code{gnatmem} makes use of the output created by the special version of
18189 allocation and deallocation routines that record call information. This allows
18190 it to obtain accurate dynamic memory usage history at a minimal cost to the
18191 execution speed. Note however, that @code{gnatmem} is not supported on all
18192 platforms (currently, it is supported on AIX, HP-UX, GNU/Linux, Solaris and
18193 Windows NT/2000/XP (x86).
18195 @noindent
18196 The @code{gnatmem} command has the form
18198 @smallexample
18199 @c    $ gnatmem @ovar{switches} user_program
18200 @c Expanding @ovar macro inline (explanation in macro def comments)
18201       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18202 @end smallexample
18204 @noindent
18205 The program must have been linked with the instrumented version of the
18206 allocation and deallocation routines. This is done by linking with the
18207 @file{libgmem.a} library. For correct symbolic backtrace information,
18208 the user program should be compiled with debugging options
18209 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18211 @smallexample
18212 $ gnatmake -g my_program -largs -lgmem
18213 @end smallexample
18215 @noindent
18216 As library @file{libgmem.a} contains an alternate body for package
18217 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18218 when an executable is linked with library @file{libgmem.a}. It is then not
18219 recommended to use @command{gnatmake} with switch @option{-a}.
18221 @noindent
18222 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18223 This file contains information about all allocations and deallocations
18224 performed by the program. It is produced by the instrumented allocations and
18225 deallocations routines and will be used by @code{gnatmem}.
18227 In order to produce symbolic backtrace information for allocations and
18228 deallocations performed by the GNAT run-time library, you need to use a
18229 version of that library that has been compiled with the @option{-g} switch
18230 (see @ref{Rebuilding the GNAT Run-Time Library}).
18232 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18233 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18234 @option{-i} switch, gnatmem will assume that this file can be found in the
18235 current directory. For example, after you have executed @file{my_program},
18236 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18238 @smallexample
18239 $ gnatmem my_program
18240 @end smallexample
18242 @noindent
18243 This will produce the output with the following format:
18245 *************** debut cc
18246 @smallexample
18247 $ gnatmem my_program
18249 Global information
18250 ------------------
18251    Total number of allocations        :  45
18252    Total number of deallocations      :   6
18253    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18254    High Water Mark                    :  11.40 Kilobytes
18259 Allocation Root # 2
18260 -------------------
18261  Number of non freed allocations    :  11
18262  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18263  High Water Mark                    :   1.27 Kilobytes
18264  Backtrace                          :
18265    my_program.adb:23 my_program.alloc
18269 @end smallexample
18271 The first block of output gives general information. In this case, the
18272 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18273 Unchecked_Deallocation routine occurred.
18275 @noindent
18276 Subsequent paragraphs display  information on all allocation roots.
18277 An allocation root is a specific point in the execution of the program
18278 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18279 construct. This root is represented by an execution backtrace (or subprogram
18280 call stack). By default the backtrace depth for allocations roots is 1, so
18281 that a root corresponds exactly to a source location. The backtrace can
18282 be made deeper, to make the root more specific.
18284 @node Switches for gnatmem
18285 @subsection Switches for @code{gnatmem}
18287 @noindent
18288 @code{gnatmem} recognizes the following switches:
18290 @table @option
18292 @item -q
18293 @cindex @option{-q} (@code{gnatmem})
18294 Quiet. Gives the minimum output needed to identify the origin of the
18295 memory leaks. Omits statistical information.
18297 @item @var{N}
18298 @cindex @var{N} (@code{gnatmem})
18299 N is an integer literal (usually between 1 and 10) which controls the
18300 depth of the backtraces defining allocation root. The default value for
18301 N is 1. The deeper the backtrace, the more precise the localization of
18302 the root. Note that the total number of roots can depend on this
18303 parameter. This parameter must be specified @emph{before} the name of the
18304 executable to be analyzed, to avoid ambiguity.
18306 @item -b n
18307 @cindex @option{-b} (@code{gnatmem})
18308 This switch has the same effect as just depth parameter.
18310 @item -i @var{file}
18311 @cindex @option{-i} (@code{gnatmem})
18312 Do the @code{gnatmem} processing starting from @file{file}, rather than
18313 @file{gmem.out} in the current directory.
18315 @item -m n
18316 @cindex @option{-m} (@code{gnatmem})
18317 This switch causes @code{gnatmem} to mask the allocation roots that have less
18318 than n leaks.  The default value is 1. Specifying the value of 0 will allow
18319 examination of even the roots that did not result in leaks.
18321 @item -s order
18322 @cindex @option{-s} (@code{gnatmem})
18323 This switch causes @code{gnatmem} to sort the allocation roots according to the
18324 specified order of sort criteria, each identified by a single letter. The
18325 currently supported criteria are @code{n, h, w} standing respectively for
18326 number of unfreed allocations, high watermark, and final watermark
18327 corresponding to a specific root. The default order is @code{nwh}.
18329 @item -t
18330 @cindex @option{-t} (@code{gnatmem})
18331 This switch causes memory allocated size to be always output in bytes.
18332 Default @code{gnatmem} behavior is to show memory sizes less then 1 kilobyte
18333 in bytes, from 1 kilobyte till 1 megabyte in kilobytes and the rest in
18334 megabytes.
18336 @end table
18338 @node Example of gnatmem Usage
18339 @subsection Example of @code{gnatmem} Usage
18341 @noindent
18342 The following example shows the use of @code{gnatmem}
18343 on a simple memory-leaking program.
18344 Suppose that we have the following Ada program:
18346 @smallexample @c ada
18347 @group
18348 @cartouche
18349 @b{with} Unchecked_Deallocation;
18350 @b{procedure} Test_Gm @b{is}
18352    @b{type} T @b{is} @b{array} (1..1000) @b{of} Integer;
18353    @b{type} Ptr @b{is} @b{access} T;
18354    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (T, Ptr);
18355    A : Ptr;
18357    @b{procedure} My_Alloc @b{is}
18358    @b{begin}
18359       A := @b{new} T;
18360    @b{end} My_Alloc;
18362    @b{procedure} My_DeAlloc @b{is}
18363       B : Ptr := A;
18364    @b{begin}
18365       Free (B);
18366    @b{end} My_DeAlloc;
18368 @b{begin}
18369    My_Alloc;
18370    @b{for} I @b{in} 1 .. 5 @b{loop}
18371       @b{for} J @b{in} I .. 5 @b{loop}
18372          My_Alloc;
18373       @b{end} @b{loop};
18374       My_Dealloc;
18375    @b{end} @b{loop};
18376 @b{end};
18377 @end cartouche
18378 @end group
18379 @end smallexample
18381 @noindent
18382 The program needs to be compiled with debugging option and linked with
18383 @code{gmem} library:
18385 @smallexample
18386 $ gnatmake -g test_gm -largs -lgmem
18387 @end smallexample
18389 @noindent
18390 Then we execute the program as usual:
18392 @smallexample
18393 $ test_gm
18394 @end smallexample
18396 @noindent
18397 Then @code{gnatmem} is invoked simply with
18398 @smallexample
18399 $ gnatmem test_gm
18400 @end smallexample
18402 @noindent
18403 which produces the following output (result may vary on different platforms):
18405 @smallexample
18406 Global information
18407 ------------------
18408    Total number of allocations        :  18
18409    Total number of deallocations      :   5
18410    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18411    High Water Mark                    :  56.90 Kilobytes
18413 Allocation Root # 1
18414 -------------------
18415  Number of non freed allocations    :  11
18416  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18417  High Water Mark                    :  46.88 Kilobytes
18418  Backtrace                          :
18419    test_gm.adb:11 test_gm.my_alloc
18421 Allocation Root # 2
18422 -------------------
18423  Number of non freed allocations    :   1
18424  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18425  High Water Mark                    :  10.02 Kilobytes
18426  Backtrace                          :
18427    s-secsta.adb:81 system.secondary_stack.ss_init
18429 Allocation Root # 3
18430 -------------------
18431  Number of non freed allocations    :   1
18432  Final Water Mark (non freed mem)   :  12 Bytes
18433  High Water Mark                    :  12 Bytes
18434  Backtrace                          :
18435    s-secsta.adb:181 system.secondary_stack.ss_init
18436 @end smallexample
18438 @noindent
18439 Note that the GNAT run time contains itself a certain number of
18440 allocations that have no  corresponding deallocation,
18441 as shown here for root #2 and root
18442 #3. This is a normal behavior when the number of non-freed allocations
18443 is one, it allocates dynamic data structures that the run time needs for
18444 the complete lifetime of the program. Note also that there is only one
18445 allocation root in the user program with a single line back trace:
18446 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18447 program shows that 'My_Alloc' is called at 2 different points in the
18448 source (line 21 and line 24). If those two allocation roots need to be
18449 distinguished, the backtrace depth parameter can be used:
18451 @smallexample
18452 $ gnatmem 3 test_gm
18453 @end smallexample
18455 @noindent
18456 which will give the following output:
18458 @smallexample
18459 Global information
18460 ------------------
18461    Total number of allocations        :  18
18462    Total number of deallocations      :   5
18463    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18464    High Water Mark                    :  56.90 Kilobytes
18466 Allocation Root # 1
18467 -------------------
18468  Number of non freed allocations    :  10
18469  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18470  High Water Mark                    :  42.97 Kilobytes
18471  Backtrace                          :
18472    test_gm.adb:11 test_gm.my_alloc
18473    test_gm.adb:24 test_gm
18474    b_test_gm.c:52 main
18476 Allocation Root # 2
18477 -------------------
18478  Number of non freed allocations    :   1
18479  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18480  High Water Mark                    :  10.02 Kilobytes
18481  Backtrace                          :
18482    s-secsta.adb:81  system.secondary_stack.ss_init
18483    s-secsta.adb:283 <system__secondary_stack___elabb>
18484    b_test_gm.c:33   adainit
18486 Allocation Root # 3
18487 -------------------
18488  Number of non freed allocations    :   1
18489  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18490  High Water Mark                    :   3.91 Kilobytes
18491  Backtrace                          :
18492    test_gm.adb:11 test_gm.my_alloc
18493    test_gm.adb:21 test_gm
18494    b_test_gm.c:52 main
18496 Allocation Root # 4
18497 -------------------
18498  Number of non freed allocations    :   1
18499  Final Water Mark (non freed mem)   :  12 Bytes
18500  High Water Mark                    :  12 Bytes
18501  Backtrace                          :
18502    s-secsta.adb:181 system.secondary_stack.ss_init
18503    s-secsta.adb:283 <system__secondary_stack___elabb>
18504    b_test_gm.c:33   adainit
18505 @end smallexample
18507 @noindent
18508 The allocation root #1 of the first example has been split in 2 roots #1
18509 and #3 thanks to the more precise associated backtrace.
18510 @end ifclear
18512 @node Stack Related Facilities
18513 @chapter Stack Related Facilities
18515 @noindent
18516 This chapter describes some useful tools associated with stack
18517 checking and analysis. In
18518 particular, it deals with dynamic and static stack usage measurements.
18520 @menu
18521 * Stack Overflow Checking::
18522 * Static Stack Usage Analysis::
18523 * Dynamic Stack Usage Analysis::
18524 @end menu
18526 @node Stack Overflow Checking
18527 @section Stack Overflow Checking
18528 @cindex Stack Overflow Checking
18529 @cindex -fstack-check
18531 @noindent
18532 For most operating systems, @command{gcc} does not perform stack overflow
18533 checking by default. This means that if the main environment task or
18534 some other task exceeds the available stack space, then unpredictable
18535 behavior will occur. Most native systems offer some level of protection by
18536 adding a guard page at the end of each task stack. This mechanism is usually
18537 not enough for dealing properly with stack overflow situations because
18538 a large local variable could ``jump'' above the guard page.
18539 Furthermore, when the
18540 guard page is hit, there may not be any space left on the stack for executing
18541 the exception propagation code. Enabling stack checking avoids
18542 such situations.
18544 To activate stack checking, compile all units with the gcc option
18545 @option{-fstack-check}. For example:
18547 @smallexample
18548 gcc -c -fstack-check package1.adb
18549 @end smallexample
18551 @noindent
18552 Units compiled with this option will generate extra instructions to check
18553 that any use of the stack (for procedure calls or for declaring local
18554 variables in declare blocks) does not exceed the available stack space.
18555 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18557 For declared tasks, the stack size is controlled by the size
18558 given in an applicable @code{Storage_Size} pragma or by the value specified
18559 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18560 the default size as defined in the GNAT runtime otherwise.
18562 For the environment task, the stack size depends on
18563 system defaults and is unknown to the compiler. Stack checking
18564 may still work correctly if a fixed
18565 size stack is allocated, but this cannot be guaranteed.
18566 To ensure that a clean exception is signalled for stack
18567 overflow, set the environment variable
18568 @env{GNAT_STACK_LIMIT} to indicate the maximum
18569 stack area that can be used, as in:
18570 @cindex GNAT_STACK_LIMIT
18572 @smallexample
18573 SET GNAT_STACK_LIMIT 1600
18574 @end smallexample
18576 @noindent
18577 The limit is given in kilobytes, so the above declaration would
18578 set the stack limit of the environment task to 1.6 megabytes.
18579 Note that the only purpose of this usage is to limit the amount
18580 of stack used by the environment task. If it is necessary to
18581 increase the amount of stack for the environment task, then this
18582 is an operating systems issue, and must be addressed with the
18583 appropriate operating systems commands.
18585 @node Static Stack Usage Analysis
18586 @section Static Stack Usage Analysis
18587 @cindex Static Stack Usage Analysis
18588 @cindex -fstack-usage
18590 @noindent
18591 A unit compiled with @option{-fstack-usage} will generate an extra file
18592 that specifies
18593 the maximum amount of stack used, on a per-function basis.
18594 The file has the same
18595 basename as the target object file with a @file{.su} extension.
18596 Each line of this file is made up of three fields:
18598 @itemize
18599 @item
18600 The name of the function.
18601 @item
18602 A number of bytes.
18603 @item
18604 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18605 @end itemize
18607 The second field corresponds to the size of the known part of the function
18608 frame.
18610 The qualifier @code{static} means that the function frame size
18611 is purely static.
18612 It usually means that all local variables have a static size.
18613 In this case, the second field is a reliable measure of the function stack
18614 utilization.
18616 The qualifier @code{dynamic} means that the function frame size is not static.
18617 It happens mainly when some local variables have a dynamic size. When this
18618 qualifier appears alone, the second field is not a reliable measure
18619 of the function stack analysis. When it is qualified with  @code{bounded}, it
18620 means that the second field is a reliable maximum of the function stack
18621 utilization.
18623 A unit compiled with @option{-Wstack-usage} will issue a warning for each
18624 subprogram whose stack usage might be larger than the specified amount of
18625 bytes.  The wording is in keeping with the qualifier documented above.
18627 @node Dynamic Stack Usage Analysis
18628 @section Dynamic Stack Usage Analysis
18630 @noindent
18631 It is possible to measure the maximum amount of stack used by a task, by
18632 adding a switch to @command{gnatbind}, as:
18634 @smallexample
18635 $ gnatbind -u0 file
18636 @end smallexample
18638 @noindent
18639 With this option, at each task termination, its stack usage is  output on
18640 @file{stderr}.
18641 It is not always convenient to output the stack usage when the program
18642 is still running. Hence, it is possible to delay this output until program
18643 termination. for a given number of tasks specified as the argument of the
18644 @option{-u} option. For instance:
18646 @smallexample
18647 $ gnatbind -u100 file
18648 @end smallexample
18650 @noindent
18651 will buffer the stack usage information of the first 100 tasks to terminate and
18652 output this info at program termination. Results are displayed in four
18653 columns:
18655 @noindent
18656 Index | Task Name | Stack Size | Stack Usage
18658 @noindent
18659 where:
18661 @table @emph
18662 @item Index
18663 is a number associated with each task.
18665 @item Task Name
18666 is the name of the task analyzed.
18668 @item Stack Size
18669 is the maximum size for the stack.
18671 @item Stack Usage
18672 is the measure done by the stack analyzer. In order to prevent overflow, the stack
18673 is not entirely analyzed, and it's not possible to know exactly how
18674 much has actually been used.
18676 @end table
18678 @noindent
18679 The environment task stack, e.g., the stack that contains the main unit, is
18680 only processed when the environment variable GNAT_STACK_LIMIT is set.
18682 @noindent
18683 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
18684 stack usage reports at run-time. See its body for the details.
18686 @ifclear FSFEDITION
18687 @c *********************************
18688 @c *            GNATCHECK          *
18689 @c *********************************
18690 @node Verifying Properties with gnatcheck
18691 @chapter Verifying Properties with @command{gnatcheck}
18692 @findex gnatcheck
18693 @cindex @command{gnatcheck}
18695 @noindent
18696 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18697 of Ada source files according to a given set of semantic rules.
18698 @cindex ASIS
18700 In order to check compliance with a given rule, @command{gnatcheck} has to
18701 semantically analyze the Ada sources.
18702 Therefore, checks can only be performed on
18703 legal Ada units. Moreover, when a unit depends semantically upon units located
18704 outside the current directory, the source search path has to be provided when
18705 calling @command{gnatcheck}, either through a specified project file or
18706 through @command{gnatcheck} switches.
18708 For full details, refer to @cite{GNATcheck Reference Manual} document.
18709 @end ifclear
18711 @ifclear FSFEDITION
18712 @c *********************************
18713 @node Creating Sample Bodies with gnatstub
18714 @chapter Creating Sample Bodies with @command{gnatstub}
18715 @findex gnatstub
18717 @noindent
18718 @command{gnatstub} creates empty but compilable bodies
18719 for library unit declarations and empty but compilable
18720 subunit for body stubs.
18722 To create a body or a subunit, @command{gnatstub} invokes the Ada
18723 compiler and generates and uses the ASIS tree for the input source;
18724 thus the input must be legal Ada code, and the tool should have all the
18725 information needed to compile the input source. To provide this information,
18726 you may specify as a tool parameter the project file the input source belongs to
18727 (or you may call @command{gnatstub}
18728 through the @command{gnat} driver (see @ref{The GNAT Driver and
18729 Project Files}). Another possibility is to specify the source search
18730 path and needed configuration files in @option{-cargs} section of @command{gnatstub}
18731 call, see the description of the @command{gnatstub} switches below.
18733 If the @command{gnatstub} argument source contains preprocessing directives
18734 then the needed options should be provided to run preprocessor as a part of
18735 the @command{gnatstub} call, and the generated body stub will correspond to
18736 the preprocessed source.
18738 By default, all the program unit bodies generated by @code{gnatstub}
18739 raise the predefined @code{Program_Error} exception, which will catch
18740 accidental calls of generated stubs. This behavior can be changed with
18741 option @option{--no-exception} (see below).
18743 @menu
18744 * Running gnatstub::
18745 * Switches for gnatstub::
18746 @end menu
18748 @node Running gnatstub
18749 @section Running @command{gnatstub}
18751 @noindent
18752 @command{gnatstub} has a command-line interface of the form:
18754 @smallexample
18755 @c $ gnatstub @ovar{switches} @var{filename}
18756 @c Expanding @ovar macro inline (explanation in macro def comments)
18757 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
18758 @end smallexample
18760 @noindent
18761 where
18762 @table @var
18763 @item filename
18764 is the name of the source file that contains a library unit declaration
18765 for which a body must be created or a library unit body for which subunits
18766 must be created for the body stubs declared in this body.
18767 The file name may contain the path information.
18768 If the name does not follow GNAT file naming conventions and a set
18769 of seitches does not contain a project file that defines naming
18770 conventions, the name of the body file must
18771 be provided
18772 explicitly as the value of the @option{-o@var{body-name}} option.
18773 If the file name follows the GNAT file naming
18774 conventions and the name of the body file is not provided,
18775 @command{gnatstub}
18776 takes the naming conventions for the generated source from the
18777 project file provided as a parameter of @option{-P} switch if any,
18778 or creates the name file to generate using the standard GNAT
18779 naming conventions.
18781 @item @samp{@var{gcc_switches}} is a list of switches for
18782 @command{gcc}. They will be passed on to all compiler invocations made by
18783 @command{gnatstub} to generate the ASIS trees. Here you can provide
18784 @option{-I} switches to form the source search path,
18785 use the @option{-gnatec} switch to set the configuration file,
18786 use the @option{-gnat05} switch if sources should be compiled in
18787 Ada 2005 mode etc.
18789 @item switches
18790 is an optional sequence of switches as described in the next section
18791 @end table
18793 @node Switches for gnatstub
18794 @section Switches for @command{gnatstub}
18796 @table @option
18797 @c !sort!
18799 @item --version
18800 @cindex @option{--version} @command{gnatstub}
18801 Display Copyright and version, then exit disregarding all other options.
18803 @item --help
18804 @cindex @option{--help} @command{gnatstub}
18805 Display usage, then exit disregarding all other options.
18807 @item -P @var{file}
18808 @cindex @option{-P} @command{gnatstub}
18809 Indicates the name of the project file that describes the set of sources
18810 to be processed.
18812 @item -X@var{name}=@var{value}
18813 @cindex @option{-X} @command{gnatstub}
18814 Indicates that external variable @var{name} in the argument project
18815 has the value @var{value}. Has no effect if no project is specified as
18816 tool argument.
18818 @item --RTS=@var{rts-path}
18819 @cindex @option{--RTS} (@command{gnatstub})
18820 Specifies the default location of the runtime library. Same meaning as the
18821 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18823 @item --subunits
18824 @cindex @option{--subunits} (@command{gnatstub})
18825 Generate subunits for body stubs. If this switch is specified,
18826 @command{gnatstub} expects a library unit body as an agrument file,
18827 otherwise a library unit declaration is expected. If a body stub
18828 already has a corresponding subunit, @command{gnatstub} does not
18829 generate anything for it.
18831 @item -f
18832 @cindex @option{-f} (@command{gnatstub})
18833 If the destination directory already contains a file with the name of the
18834 body file
18835 for the argument spec file, replace it with the generated body stub.
18836 This switch cannot be used together with @option{--subunits}.
18838 @item -hs
18839 @cindex @option{-hs} (@command{gnatstub})
18840 Put the comment header (i.e., all the comments preceding the
18841 compilation unit) from the source of the library unit declaration
18842 into the body stub.
18844 @item -hg
18845 @cindex @option{-hg} (@command{gnatstub})
18846 Put a sample comment header into the body stub.
18848 @item --header-file=@var{filename}
18849 @cindex @option{--header-file} (@command{gnatstub})
18850 Use the content of the file as the comment header for a generated body stub.
18852 @item -IDIR
18853 @cindex @option{-IDIR} (@command{gnatstub})
18854 @itemx -I-
18855 @cindex @option{-I-} (@command{gnatstub})
18856 These switches have  the same meaning as in calls to
18857 @command{gcc}.
18858 They define  the source search path in the call to
18859 @command{gcc} issued
18860 by @command{gnatstub} to compile an argument source file.
18862 @item -gnatec@var{PATH}
18863 @cindex @option{-gnatec} (@command{gnatstub})
18864 This switch has the same meaning as in calls to @command{gcc}.
18865 It defines the additional configuration file to be passed to the call to
18866 @command{gcc} issued
18867 by @command{gnatstub} to compile an argument source file.
18869 @item -gnatyM@var{n}
18870 @cindex @option{-gnatyM} (@command{gnatstub})
18871 (@var{n} is a non-negative integer). Set the maximum line length that is
18872 allowed in a source file. The default is 79. The maximum value that can be
18873 specified is 32767. Note that in the special case of configuration
18874 pragma files, the maximum is always 32767 regardless of whether or
18875 not this switch appears.
18877 @item -gnaty@var{n}
18878 @cindex @option{-gnaty} (@command{gnatstub})
18879 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18880 the generated body sample to @var{n}.
18881 The default indentation is 3.
18883 @item -gnatyo
18884 @cindex @option{-gnatyo} (@command{gnatstub})
18885 Order local bodies alphabetically. (By default local bodies are ordered
18886 in the same way as the corresponding local specs in the argument spec file.)
18888 @item -i@var{n}
18889 @cindex @option{-i} (@command{gnatstub})
18890 Same as @option{-gnaty@var{n}}
18892 @item -k
18893 @cindex @option{-k} (@command{gnatstub})
18894 Do not remove the tree file (i.e., the snapshot of the compiler internal
18895 structures used by @command{gnatstub}) after creating the body stub.
18897 @item -l@var{n}
18898 @cindex @option{-l} (@command{gnatstub})
18899 Same as @option{-gnatyM@var{n}}
18901 @item --no-exception
18902 @cindex @option{--no-exception} (@command{gnatstub})
18903 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18904 This is not always possible for function stubs.
18906 @item --no-local-header
18907 @cindex @option{--no-local-header} (@command{gnatstub})
18908 Do not place local comment header with unit name before body stub for a
18909 unit.
18911 @item -o @var{body-name}
18912 @cindex @option{-o} (@command{gnatstub})
18913 Body file name.  This should be set if the argument file name does not
18914 follow
18915 the GNAT file naming
18916 conventions. If this switch is omitted the default name for the body will be
18917 obtained
18918 from the argument file name according to the GNAT file naming conventions.
18920 @item --dir=@var{dir-name}
18921 @cindex @option{--dir} (@command{gnatstub})
18922 The path to the directory to place the generated files into.
18923 If this switch is not set, the generated library unit body is
18924 placed in the current directory, and generated sununits -
18925 in the directory where the argument body is located.
18927 @item -W@var{e}
18928 @cindex @option{-W} (@command{gnatstub})
18929 Specify the wide character encoding method for the output body file.
18930 @var{e} is one of the following:
18932 @itemize @bullet
18934 @item h
18935 Hex encoding
18937 @item u
18938 Upper half encoding
18940 @item s
18941 Shift/JIS encoding
18943 @item e
18944 EUC encoding
18946 @item 8
18947 UTF-8 encoding
18949 @item b
18950 Brackets encoding (default value)
18951 @end itemize
18953 @item -q
18954 @cindex @option{-q} (@command{gnatstub})
18955 Quiet mode: do not generate a confirmation when a body is
18956 successfully created, and do not generate a message when a body is not
18957 required for an
18958 argument unit.
18960 @item -r
18961 @cindex @option{-r} (@command{gnatstub})
18962 Reuse the tree file (if it exists) instead of creating it.  Instead of
18963 creating the tree file for the library unit declaration, @command{gnatstub}
18964 tries to find it in the current directory and use it for creating
18965 a body. If the tree file is not found, no body is created. This option
18966 also implies @option{-k}, whether or not
18967 the latter is set explicitly.
18969 @item -t
18970 @cindex @option{-t} (@command{gnatstub})
18971 Overwrite the existing tree file.  If the current directory already
18972 contains the file which, according to the GNAT file naming rules should
18973 be considered as a tree file for the argument source file,
18974 @command{gnatstub}
18975 will refuse to create the tree file needed to create a sample body
18976 unless this option is set.
18978 @item -v
18979 @cindex @option{-v} (@command{gnatstub})
18980 Verbose mode: generate version information.
18982 @end table
18983 @end ifclear
18985 @ifclear FSFEDITION
18986 @c *********************************
18987 @node Creating Unit Tests with gnattest
18988 @chapter Creating Unit Tests with @command{gnattest}
18989 @findex gnattest
18991 @noindent
18992 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
18993 as well as a test driver infrastructure (harness). @command{gnattest} creates
18994 a skeleton for each visible subprogram in the packages under consideration when
18995 they do not exist already.
18997 The user can choose to generate a single test driver
18998 that will run all individual tests, or separate test drivers for each test. The
18999 second option allows much greater flexibility in test execution environment,
19000 allows to benefit from parallel tests execution to increase performance, and
19001 provides stubbing support.
19003 @command{gnattest} also has a mode of operation where it acts as the test
19004 aggregator when multiple test executables must be run, in particular when
19005 the separate test drivers were generated. In this mode it handles individual
19006 tests execution and upon completion reports the summary results of the test
19007 run.
19009 In order to process source files from a project, @command{gnattest} has to
19010 semantically analyze the sources. Therefore, test skeletons can only be
19011 generated for legal Ada units. If a unit is dependent on other units,
19012 those units should be among the source files of the project or of other projects
19013 imported by this one.
19015 Generated skeletons and harnesses are based on the AUnit testing framework.
19016 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19017 for Java or CppUnit for C++. While it is advised that gnattest users read
19018 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19019 For correct operation of @command{gnattest}, AUnit should be installed and
19020 aunit.gpr must be on the project path. This happens automatically when Aunit
19021 is installed at its default location.
19023 @menu
19024 * Running gnattest::
19025 * Switches for gnattest in framework generation mode::
19026 * Switches for gnattest in tests execution mode::
19027 * Project Attributes for gnattest::
19028 * Simple Example::
19029 * Setting Up and Tearing Down the Testing Environment::
19030 * Regenerating Tests::
19031 * Default Test Behavior::
19032 * Testing Primitive Operations of Tagged Types::
19033 * Testing Inheritance::
19034 * Tagged Types Substitutability Testing::
19035 * Testing with Contracts::
19036 * Additional Tests::
19037 * Individual Test Drivers::
19038 * Stubbing::
19039 * Putting Tests under Version Control::
19040 * Support for other platforms/run-times::
19041 * Current Limitations::
19042 @end menu
19044 @node Running gnattest
19045 @section Running @command{gnattest}
19047 @noindent
19048 @b{In the framework generation mode}, @command{gnattest} has a command-line
19049 interface of the form
19051 @smallexample
19052 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19053 @c Expanding @ovar macro inline (explanation in macro def comments)
19054 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19055 @end smallexample
19057 @noindent
19058 where
19059 @table @var
19061 @item -Pprojname
19062 specifies the project defining the location of source files. When no
19063 file names are provided on the command line, all sources in the project
19064 are used as input. This switch is required.
19066 @item filename
19067 is the name of the source file containing the library unit package declaration
19068 for which a test package will be created. The file name may be given with a
19069 path.
19071 @item @samp{@var{gcc_switches}}
19072 is a list of switches for
19073 @command{gcc}. These switches will be passed on to all compiler invocations
19074 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19075 @option{-I} switches to form the source search path,
19076 use the @option{-gnatec} switch to set the configuration file,
19077 use the @option{-gnat05} switch if sources should be compiled in
19078 Ada 2005 mode, etc.
19080 @item switches
19081 is an optional sequence of switches as described in the next section.
19083 @end table
19085 @command{gnattest} results can be found in two different places.
19087 @itemize @bullet
19088 @item automatic harness:
19089 the harness code, which is located by default in "gnattest/harness" directory
19090 that is created in the object directory of corresponding project file. All of
19091 this code is generated completely automatically and can be destroyed and
19092 regenerated at will. It is not recommended to modify this code manually, since
19093 it could easily be overridden by mistake. The entry point in the harness code is
19094 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19095 using a command such as:
19097 @smallexample
19098 gnatmake -P<harness-dir>/test_driver
19099 test_runner
19100 @end smallexample
19102 Note that you might need to specify the necessary values of scenario variables
19103 when you are not using the AUnit defaults.
19105 @item actual unit test skeletons:
19106 a test skeleton for each visible subprogram is created in a separate file, if it
19107 doesn't exist already. By default, those separate test files are located in a
19108 "gnattest/tests" directory that is created in the object directory of
19109 corresponding project file. For example, if a source file my_unit.ads in
19110 directory src contains a visible subprogram Proc, then the corresponding unit
19111 test will be found in file src/tests/my_unit-test_data-tests.adb and will be
19112 called Test_Proc_<code>. <code> is a signature encoding used to differentiate
19113 test names in case of overloading.
19115 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19116 this will cause a name conflict with the generated test package.
19117 @end itemize
19120 @noindent
19121 @b{In the tests execution mode mode}, @command{gnattest} has a command-line
19122 interface of the form
19124 @smallexample
19125 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19126 @c Expanding @ovar macro inline (explanation in macro def comments)
19127 $ gnattest @var{test_drivers.list} @r{[}@var{switches}@r{]}
19128 @end smallexample
19130 @noindent
19131 where
19132 @table @var
19134 @item test_drivers.list
19135 is the name of the text file containing the list of executables to treat as
19136 test drivers. This file is automatically generated by gnattest, but can be
19137 hand-edited to add or remove tests. This switch is required.
19139 @item switches
19140 is an optional sequence of switches as described below.
19142 @end table
19145 @node Switches for gnattest in framework generation mode
19146 @section Switches for @command{gnattest} in framework generation mode
19148 @table @option
19149 @c !sort!
19151 @item -q
19152 @cindex @option{-q} (@command{gnattest})
19153 Quiet mode: suppresses noncritical output messages.
19155 @item -v
19156 @cindex @option{-v} (@command{gnattest})
19157 Verbose mode: generates version information if specified by itself on the
19158 command line.  If specified via GNATtest_Switches, produces output
19159 about the execution of the tool.
19161 @item -r
19162 @cindex @option{-r} (@command{gnattest})
19163 Recursively considers all sources from all projects.
19166 @item -X@var{name=value}
19167 @cindex @option{-X} (@command{gnattest})
19168 Indicate that external variable @var{name} has the value @var{value}.
19170 @item --RTS=@var{rts-path}
19171 @cindex @option{--RTS} (@command{gnattest})
19172 Specifies the default location of the runtime library. Same meaning as the
19173 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
19176 @item --additional-tests=@var{projname}
19177 @cindex @option{--additional-tests} (@command{gnattest})
19178 Sources described in @var{projname} are considered potential additional
19179 manual tests to be added to the test suite.
19181 @item --harness-only
19182 @cindex @option{--harness-only} (@command{gnattest})
19183 When this option is given, @command{gnattest} creates a harness for all
19184 sources, treating them as test packages.
19186 @item --separate-drivers
19187 @cindex @option{--separate-drivers} (@command{gnattest})
19188 Generates a separate test driver for each test, rather than a single
19189 executable incorporating all tests.
19191 @item --stub
19192 @cindex @option{--stub} (@command{gnattest})
19193 Generates the testing framework that uses subsystem stubbing to isolate the
19194 code under test.
19197 @item --harness-dir=@var{dirname}
19198 @cindex @option{--harness-dir} (@command{gnattest})
19199 Specifies the directory that will hold the harness packages and project file
19200 for the test driver. If the @var{dirname} is a relative path, it is considered
19201 relative to the object directory of the project file.
19203 @item --tests-dir=@var{dirname}
19204 @cindex @option{--tests-dir} (@command{gnattest})
19205 All test packages are placed in the @var{dirname} directory.
19206 If the @var{dirname} is a relative path, it is considered relative to the object
19207 directory of the project file. When all sources from all projects are taken
19208 recursively from all projects, @var{dirname} directories are created for each
19209 project in their object directories and test packages are placed accordingly.
19211 @item --subdir=@var{dirname}
19212 @cindex @option{--subdir} (@command{gnattest})
19213 Test packages are placed in a subdirectory of the corresponding source
19214 directory, with the name @var{dirname}. Thus, each set of unit tests is located
19215 in a subdirectory of the code under test.  If the sources are in separate
19216 directories, each source directory has a test subdirectory named @var{dirname}.
19218 @item --tests-root=@var{dirname}
19219 @cindex @option{--tests-root} (@command{gnattest})
19220 The hierarchy of source directories, if any, is recreated in the @var{dirname}
19221 directory, with test packages placed in directories corresponding to those
19222 of the sources.
19223 If the @var{dirname} is a relative path, it is considered relative to the object
19224 directory of the project file. When projects are considered recursively,
19225 directory hierarchies of tested sources are
19226 recreated for each project in their object directories and test packages are
19227 placed accordingly.
19229 @item --stubs-dir=@var{dirname}
19230 @cindex @option{--stubs-dir} (@command{gnattest})
19231 The hierarchy of directories containing stubbed units is recreated in
19232 the @var{dirname} directory, with stubs placed in directories corresponding to
19233 projects they are derived from.
19234 If the @var{dirname} is a relative path, it is considered relative to the object
19235 directory of the project file. When projects are considered recursively,
19236 directory hierarchies of stubs are
19237 recreated for each project in their object directories and test packages are
19238 placed accordingly.
19241 @item --validate-type-extensions
19242 @cindex @option{--validate-type-extensions} (@command{gnattest})
19243 Enables substitution check: run all tests from all parents in order
19244 to check substitutability in accordance with LSP.
19246 @item --skeleton-default=@var{val}
19247 @cindex @option{--skeleton-default} (@command{gnattest})
19248 Specifies the default behavior of generated skeletons. @var{val} can be either
19249 "fail" or "pass", "fail" being the default.
19251 @item --passed-tests=@var{val}
19252 @cindex @option{--passed-tests} (@command{gnattest})
19253 Specifies whether or not passed tests should be shown. @var{val} can be either
19254 "show" or "hide", "show" being the default.
19256 @item --exit-status=@var{val}
19257 @cindex @option{--exit-status} (@command{gnattest})
19258 Specifies whether or not generated test driver should return failure exit
19259 status if at least one test fails or crashes. @var{val} can be either
19260 "on" or "off", "off" being the default.
19262 @item --omit-sloc
19263 @cindex @option{--omit-sloc} (@command{gnattest})
19264 Suppresses comment line containing file name and line number of corresponding
19265 subprograms in test skeletons.
19267 @item --no-command-line
19268 @cindex @option{--no-command-line} (@command{gnattest})
19269 Don't add command line support to test driver. Note that regardless of this
19270 switch, @command{gnattest} will automatically refrain from adding command
19271 line support if it detects that the selected run-time doesn't provide
19272 this capability.
19275 @item --separates
19276 @cindex @option{--separates} (@command{gnattest})
19277 Bodies of all test routines are generated as separates. Note that this mode is
19278 kept for compatibility reasons only and it is not advised to use it due to
19279 possible problems with hash in names of test skeletons when using an
19280 inconsistent casing. Separate test skeletons can be incorporated to monolith
19281 test package with improved hash being used by using @option{--transition}
19282 switch.
19285 @item --transition
19286 @cindex @option{--transition} (@command{gnattest})
19287 This allows transition from separate test routines to monolith test packages.
19288 All matching test routines are overwritten with contents of corresponding
19289 separates. Note that if separate test routines had any manually added with
19290 clauses they will be moved to the test package body as is and have to be moved
19291 by hand.
19293 @item --test-duration
19294 @cindex @option{--test-duration} (@command{gnattest})
19295 Adds time measurements for each test in generated test driver.
19297 @end table
19299 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19300 mutually exclusive.
19303 @node Switches for gnattest in tests execution mode
19304 @section Switches for @command{gnattest} in tests execution mode
19306 @table @option
19307 @c !sort!
19309 @item --passed-tests=@var{val}
19310 @cindex @option{--passed-tests} (@command{gnattest})
19311 Specifies whether or not passed tests should be shown. @var{val} can be either
19312 "show" or "hide", "show" being the default.
19314 @item --queues=@var{n}, -j@var{n}
19315 @cindex @option{--queues} (@command{gnattest})
19316 @cindex @option{-j} (@command{gnattest})
19317 Runs @var{n} tests in parallel (default is 1).
19319 @end table
19322 @node Project Attributes for gnattest
19323 @section Project Attributes for @command{gnattest}
19325 @noindent
19327 Most of the command-line options can also be passed to the tool by adding
19328 special attributes to the project file. Those attributes should be put in
19329 package gnattest. Here is the list of attributes:
19331 @itemize @bullet
19333 @item Tests_Root
19334 is used to select the same output mode as with the --tests-root option.
19335 This attribute cannot be used together with Subdir or Tests_Dir.
19337 @item Subdir
19338 is used to select the same output mode as with the --subdir option.
19339 This attribute cannot be used together with Tests_Root or Tests_Dir.
19341 @item Tests_Dir
19342 is used to select the same output mode as with the --tests-dir option.
19343 This attribute cannot be used together with Subdir or Tests_Root.
19345 @item Harness_Dir
19346 is used to specify the directory in which to place harness packages and project
19347 file for the test driver, otherwise specified by --harness-dir.
19349 @item Additional_Tests
19350 is used to specify the project file, otherwise given by
19351 --additional-tests switch.
19353 @item Skeletons_Default
19354 is used to specify the default behaviour of test skeletons, otherwise
19355 specified by --skeleton-default option. The value of this attribute
19356 should be either "pass" or "fail".
19358 @end itemize
19360 Each of those attributes can be overridden from the command line if needed.
19361 Other @command{gnattest} switches can also be passed via the project
19362 file as an attribute list called GNATtest_Switches.
19364 @node Simple Example
19365 @section Simple Example
19367 @noindent
19369 Let's take a very simple example using the first @command{gnattest} example
19370 located in:
19372 @smallexample
19373 <install_prefix>/share/examples/gnattest/simple
19374 @end smallexample
19376 This project contains a simple package containing one subprogram. By running gnattest:
19378 @smallexample
19379 $ gnattest --harness-dir=driver -Psimple.gpr
19380 @end smallexample
19382 a test driver is created in directory "driver". It can be compiled and run:
19384 @smallexample
19385 $ cd obj/driver
19386 $ gnatmake -Ptest_driver
19387 $ test_runner
19388 @end smallexample
19390 One failed test with diagnosis "test not implemented" is reported.
19391 Since no special output option was specified, the test package Simple.Tests
19392 is located in:
19394 @smallexample
19395 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19396 @end smallexample
19398 For each package containing visible subprograms, a child test package is
19399 generated. It contains one test routine per tested subprogram. Each
19400 declaration of a test subprogram has a comment specifying which tested
19401 subprogram it corresponds to. Bodies of test routines are placed in test package
19402 bodies and are surrounded by special comment sections. Those comment sections
19403 should not be removed or modified in order for gnattest to be able to regenerate
19404 test packages and keep already written tests in place.
19405 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19406 a single statement: a call to procedure Assert. It has two arguments:
19407 the Boolean expression we want to check and the diagnosis message to display if
19408 the condition is false.
19410 That is where actual testing code should be written after a proper setup.
19411 An actual check can be performed by replacing the Assert call with:
19413 @smallexample @c ada
19414 Assert (Inc (1) = 2, "wrong incrementation");
19415 @end smallexample
19417 After recompiling and running the test driver, one successfully passed test
19418 is reported.
19420 @node Setting Up and Tearing Down the Testing Environment
19421 @section Setting Up and Tearing Down the Testing Environment
19423 @noindent
19425 Besides test routines themselves, each test package has a parent package
19426 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19427 overwritten by the tool. Set_Up is called before each test routine of the
19428 package and Tear_Down is called after each test routine. Those two procedures
19429 can be used to perform necessary initialization and finalization,
19430 memory allocation, etc. Test type declared in Test_Data package is parent type
19431 for the test type of test package and can have user-defined components whose
19432 values can be set by Set_Up routine and used in test routines afterwards.
19434 @node Regenerating Tests
19435 @section Regenerating Tests
19437 @noindent
19439 Bodies of test routines and test_data packages are never overridden after they
19440 have been created once. As long as the name of the subprogram, full expanded Ada
19441 names, and the order of its parameters is the same, and comment sections are
19442 intact the old test routine will fit in its place and no test skeleton will be
19443 generated for the subprogram.
19445 This can be demonstrated with the previous example. By uncommenting declaration
19446 and body of function Dec in simple.ads and simple.adb, running
19447 @command{gnattest} on the project, and then running the test driver:
19449 @smallexample
19450 gnattest --harness-dir=driver -Psimple.gpr
19451 cd obj/driver
19452 gnatmake -Ptest_driver
19453 test_runner
19454 @end smallexample
19456 the old test is not replaced with a stub, nor is it lost, but a new test
19457 skeleton is created for function Dec.
19459 The only way of regenerating tests skeletons is to remove the previously created
19460 tests together with corresponding comment sections.
19462 @node Default Test Behavior
19463 @section Default Test Behavior
19465 @noindent
19467 The generated test driver can treat unimplemented tests in two ways:
19468 either count them all as failed (this is useful to see which tests are still
19469 left to implement) or as passed (to sort out unimplemented ones from those
19470 actually failing).
19472 The test driver accepts a switch to specify this behavior:
19473 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19474 @command{gnattest}).
19476 The default behavior of the test driver is set with the same switch
19477 as passed to gnattest when generating the test driver.
19479 Passing it to the driver generated on the first example:
19481 @smallexample
19482 test_runner --skeleton-default=pass
19483 @end smallexample
19485 makes both tests pass, even the unimplemented one.
19487 @node Testing Primitive Operations of Tagged Types
19488 @section Testing Primitive Operations of Tagged Types
19490 @noindent
19492 Creation of test skeletons for primitive operations of tagged types entails
19493 a number of features. Test routines for all primitives of a given tagged type
19494 are placed in a separate child package named according to the tagged type. For
19495 example, if you have tagged type T in package P, all tests for primitives
19496 of T will be in P.T_Test_Data.T_Tests.
19498 Consider running gnattest on the second example (note: actual tests for this
19499 example already exist, so there's no need to worry if the tool reports that
19500 no new stubs were generated):
19502 @smallexample
19503 cd <install_prefix>/share/examples/gnattest/tagged_rec
19504 gnattest --harness-dir=driver -Ptagged_rec.gpr
19505 @end smallexample
19507 Taking a closer look at the test type declared in the test package
19508 Speed1.Controller_Test_Data is necessary. It is declared in:
19510 @smallexample
19511 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19512 @end smallexample
19514 Test types are direct or indirect descendants of
19515 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19516 subprograms, the user doesn't need to be concerned with them. However,
19517 when generating test packages for primitive operations, there are some things
19518 the user needs to know.
19520 Type Test_Controller has components that allow assignment of various
19521 derivations of type Controller. And if you look at the specification of
19522 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19523 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19524 Thus, test types mirror the hierarchy of tested types.
19526 The Set_Up procedure of Test_Data package corresponding to a test package
19527 of primitive operations of type T assigns to Fixture a reference to an
19528 object of that exact type T. Notice, however, that if the tagged type has
19529 discriminants, the Set_Up only has a commented template for setting
19530 up the fixture, since filling the discriminant with actual value is up
19531 to the user.
19533 The knowledge of the structure of test types allows additional testing
19534 without additional effort. Those possibilities are described below.
19536 @node Testing Inheritance
19537 @section Testing Inheritance
19539 @noindent
19541 Since the test type hierarchy mimics the hierarchy of tested types, the
19542 inheritance of tests takes place. An example of such inheritance can be
19543 seen by running the test driver generated for the second example. As previously
19544 mentioned, actual tests are already written for this example.
19546 @smallexample
19547 cd obj/driver
19548 gnatmake -Ptest_driver
19549 test_runner
19550 @end smallexample
19552 There are 6 passed tests while there are only 5 testable subprograms. The test
19553 routine for function Speed has been inherited and run against objects of the
19554 derived type.
19556 @node Tagged Types Substitutability Testing
19557 @section Tagged Types Substitutability Testing
19559 @noindent
19561 Tagged Types Substitutability Testing is a way of verifying the global type
19562 consistency by testing. Global type consistency is a principle stating that if
19563 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19564 then objects of type T may be replaced with objects of type S (that is,
19565 objects of type S may be substituted for objects of type T), without
19566 altering any of the desirable properties of the program. When the properties
19567 of the program are expressed in the form of subprogram preconditions and
19568 postconditions (let's call them pre and post), the principle is formulated as
19569 relations between the pre and post of primitive operations and the pre and post
19570 of their derived operations. The pre of a derived operation should not be
19571 stronger than the original pre, and the post of the derived operation should
19572 not be weaker than the original post. Those relations ensure that verifying if
19573 a dispatching call is safe can be done just by using the pre and post of the
19574 root operation.
19576 Verifying global type consistency by testing consists of running all the unit
19577 tests associated with the primitives of a given tagged type with objects of its
19578 derived types.
19580 In the example used in the previous section, there was clearly a violation of
19581 type consistency. The overriding primitive Adjust_Speed in package Speed2
19582 removes the functionality of the overridden primitive and thus doesn't respect
19583 the consistency principle.
19584 Gnattest has a special option to run overridden parent tests against objects
19585 of the type which have overriding primitives:
19587 @smallexample
19588 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19589 cd obj/driver
19590 gnatmake -Ptest_driver
19591 test_runner
19592 @end smallexample
19594 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19595 against objects of the derived type.
19597 Non-overridden tests are already inherited for derived test types, so the
19598 --validate-type-extensions enables the application of overriden tests to objects
19599 of derived types.
19601 @node Testing with Contracts
19602 @section Testing with Contracts
19604 @noindent
19606 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19607 as well as corresponding aspects.
19608 Test routines are generated, one per each Test_Case associated with a tested
19609 subprogram. Those test routines have special wrappers for tested functions
19610 that have composition of pre- and postcondition of the subprogram with
19611 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19612 either count for Nominal mode or do not count for Robustness mode).
19614 The third example demonstrates how this works:
19616 @smallexample
19617 cd <install_prefix>/share/examples/gnattest/contracts
19618 gnattest --harness-dir=driver -Pcontracts.gpr
19619 @end smallexample
19621 Putting actual checks within the range of the contract does not cause any
19622 error reports. For example, for the test routine which corresponds to
19623 test case 1:
19625 @smallexample @c ada
19626 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19627 @end smallexample
19629 and for the test routine corresponding to test case 2:
19631 @smallexample @c ada
19632 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19633 @end smallexample
19635 are acceptable:
19637 @smallexample
19638 cd obj/driver
19639 gnatmake -Ptest_driver
19640 test_runner
19641 @end smallexample
19643 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19644 a precondition violation for test case one. Also, by using any otherwise
19645 correct but positive pair of numbers in the second test routine, you can also
19646 get a precondition violation. Postconditions are checked and reported
19647 the same way.
19649 @node Additional Tests
19650 @section Additional Tests
19652 @noindent
19653 @command{gnattest} can add user-written tests to the main suite of the test
19654 driver. @command{gnattest} traverses the given packages and searches for test
19655 routines. All procedures with a single in out parameter of a type which is
19656 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19657 specifications are added to the suites and are then executed by the test driver.
19658 (Set_Up and Tear_Down are filtered out.)
19660 An example illustrates two ways of creating test harnesses for user-written
19661 tests. Directory additional_tests contains an AUnit-based test driver written
19662 by hand.
19664 @smallexample
19665 <install_prefix>/share/examples/gnattest/additional_tests/
19666 @end smallexample
19668 To create a test driver for already-written tests, use the --harness-only
19669 option:
19671 @smallexample
19672 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19673   --harness-only
19674 gnatmake -Pharness_only/test_driver.gpr
19675 harness_only/test_runner
19676 @end smallexample
19678 Additional tests can also be executed together with generated tests:
19680 @smallexample
19681 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19682   --harness-dir=mixing
19683 gnatmake -Pmixing/test_driver.gpr
19684 mixing/test_runner
19685 @end smallexample
19688 @node Individual Test Drivers
19689 @section Individual Test Drivers
19691 @noindent
19692 By default, @command{gnattest} generates a monolithic test driver that
19693 aggregates the individual tests into a single executable. It is also possible
19694 to generate separate executables for each test, by passing the switch
19695 @option{--separate-drivers}. This approach scales better for large testing
19696 campaigns, especially involving target architectures with limited resources
19697 typical for embedded development. It can also provide a major performance
19698 benefit on multi-core systems by allowing simultaneous execution of multiple
19699 tests.
19701 @command{gnattest} can take charge of executing the individual tests; for this,
19702 instead of passing a project file, a text file containing the list of
19703 executables can be passed. Such a file is automatically generated by gnattest
19704 under the name @option{test_drivers.list}, but it can be
19705 hand-edited to add or remove tests, or replaced. The individual tests can
19706 also be executed standalone, or from any user-defined scripted framework.
19709 @node Stubbing
19710 @section Stubbing
19712 @noindent
19713 Depending on the testing campaign, it is sometimes necessary to isolate the
19714 part of the algorithm under test from its dependencies. This is accomplished
19715 via @emph{stubbing}, i.e. replacing the subprograms that are called from the
19716 subprogram under test by stand-in subprograms that match the profiles of the
19717 original ones, but simply return predetermined values required by the test
19718 scenario.
19720 This mode of test harness generation is activated by the switch @option{--stub}.
19722 The implementation approach chosen by @command{gnattest} is as follows.
19723 For each package under consideration all the packages it is directly depending
19724 on are stubbed, excluding the generic packages and package instantiations.
19725 The stubs are shared for each package under test. The specs of packages to stub
19726 remain intact, while their bodies are replaced, and hide the original bodies by
19727 means of extending projects. Also, for each stubbed
19728 package, a child package with setter routines for each subprogram declaration
19729 is created. These setters are meant to be used to set the behaviour of
19730 stubbed subprograms from within test cases.
19732 Note that subprograms belonging to the same package as the subprogram under
19733 test are not stubbed. This guarantees that the sources being tested are
19734 exactly the sources used for production, which is an important property for
19735 establishing the traceability between the testing campaign and production code.
19737 Due to the nature of stubbing process, this mode implies the switch
19738 @option{--separate-drivers}, i.e. an individual test driver (with the
19739 corresponding hierarchy of extending projects) is generated for each test.
19741 @quotation Note
19742 Developing a stubs-based testing campaign requires
19743 good understanding of the infrastructure created by @command{gnattest} for
19744 this purpose. We recommend following the stubbing tutorials provided
19745 under @file{<install_prefix>/share/examples/gnattest/stubbing*} before
19746 attempting to use this powerful feature.
19747 @end quotation
19749 @node Putting Tests under Version Control
19750 @section Putting Tests under Version Control
19752 @noindent
19753 As has been stated earlier, @command{gnattest} generates two different types
19754 of code, test skeletons and harness. The harness is generated completely
19755 automatically each time, does not require manual changes and therefore should
19756 not be put under version control.
19757 It makes sense to put under version control files containing test data packages,
19758 both specs and bodies, and files containing bodies of test packages. Note that
19759 test package specs are also generated automatically each time and should not be
19760 put under version control.
19761 Option @option{--omit-sloc} may be usefull when putting test packages under VCS.
19763 @node Support for other platforms/run-times
19764 @section Support for other platforms/run-times
19766 @noindent
19767 @command{gnattest} can be used to generate the test harness for platforms
19768 and run-time libraries others than the default native target with the
19769 default full run-time. For example, when using a limited run-time library
19770 such as Zero FootPrint (ZFP), a simplified harness is generated.
19772 Two variables are used to tell the underlying AUnit framework how to generate
19773 the test harness: @code{PLATFORM}, which identifies the target, and
19774 @code{RUNTIME}, used to determine the run-time library for which the harness
19775 is generated. Corresponding prefix should also be used when calling
19776 @command{gnattest} for non-native targets. For example, the following options
19777 are used to generate the AUnit test harness for a PowerPC ELF target using
19778 the ZFP run-time library:
19780 @smallexample
19781 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19782 @end smallexample
19784 @node Current Limitations
19785 @section Current Limitations
19787 @noindent
19789 The tool currently does not support following features:
19791 @itemize @bullet
19792 @item generic tests for nested generic packages and their instantiations
19793 @item tests for protected subprograms and entries
19795 @end itemize
19796 @end ifclear
19799 @c *********************************
19800 @node Performing Dimensionality Analysis in GNAT
19801 @chapter Performing Dimensionality Analysis in GNAT
19802 @cindex Dimensionality analysis
19804 @noindent
19805 The GNAT compiler now supports dimensionality checking. The user can
19806 specify physical units for objects, and the compiler will verify that uses
19807 of these objects are compatible with their dimensions, in a fashion that is
19808 familiar to engineering practice. The dimensions of algebraic expressions
19809 (including powers with static exponents) are computed from their constituents.
19811 This feature depends on Ada 2012 aspect specifications, and is available from
19812 version 7.0.1 of GNAT onwards.
19813 The GNAT-specific aspect @code{Dimension_System}
19814 @cindex @code{Dimension_System} aspect
19815 allows you to define a system of units; the aspect @code{Dimension}
19816 @cindex @code{Dimension} aspect
19817 then allows the user to declare dimensioned quantities within a given system.
19818 (These aspects are described in the @i{Implementation Defined Aspects}
19819 chapter of the @i{GNAT Reference Manual}).
19821 The major advantage of this model is that it does not require the declaration of
19822 multiple operators for all possible combinations of types: it is only necessary
19823 to use the proper subtypes in object declarations.
19825 The simplest way to impose dimensionality checking on a computation is to make
19826 use of the package @code{System.Dim.Mks},
19827 @cindex @code{System.Dim.Mks} package (GNAT library)
19828 which is part of the GNAT library. This
19829 package defines a floating-point type @code{MKS_Type},
19830 @cindex @code{MKS_Type} type
19831 for which a sequence of
19832 dimension names are specified, together with their conventional abbreviations.
19833 The following should be read together with the full specification of the
19834 package, in file @file{s-dimmks.ads}.
19835 @cindex @file{s-dimmks.ads} file
19837 @smallexample @c ada
19838 @group
19839    @b{type} Mks_Type @b{is} @b{new} Long_Long_Float
19840      @b{with}
19841       Dimension_System => (
19842         (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
19843         (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
19844         (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
19845         (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
19846         (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
19847         (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
19848         (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
19849 @end group
19850 @end smallexample
19852 @noindent
19853 The package then defines a series of subtypes that correspond to these
19854 conventional units. For example:
19856 @smallexample @c ada
19857 @group
19858    @b{subtype} Length @b{is} Mks_Type
19859      @b{with}
19860       Dimension => (Symbol => 'm', Meter  => 1, @b{others} => 0);
19861 @end group
19862 @end smallexample
19864 @noindent
19865 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
19866 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
19867 @code{Luminous_Intensity} (the standard set of units of the SI system).
19869 The package also defines conventional names for values of each unit, for
19870 example:
19872 @smallexample @c ada
19873 @group
19874    m   : @b{constant} Length           := 1.0;
19875    kg  : @b{constant} Mass             := 1.0;
19876    s   : @b{constant} Time             := 1.0;
19877    A   : @b{constant} Electric_Current := 1.0;
19878 @end group
19879 @end smallexample
19881 @noindent
19882 as well as useful multiples of these units:
19884 @smallexample @c ada
19885 @group
19886    cm  : @b{constant} Length := 1.0E-02;
19887    g   : @b{constant} Mass   := 1.0E-03;
19888    min : @b{constant} Time   := 60.0;
19889    day : @b{constant} Time   := 60.0 * 24.0 * min;
19890   ...
19891 @end group
19892 @end smallexample
19894 @noindent
19895 Using this package, you can then define a derived unit by
19896 providing the aspect that
19897 specifies its dimensions within the MKS system, as well as the string to
19898 be used for output of a value of that unit:
19900 @smallexample @c ada
19901 @group
19902   @b{subtype} Acceleration @b{is} Mks_Type
19903     @b{with} Dimension => ("m/sec^2",
19904                        Meter => 1,
19905                        Second => -2,
19906                        @b{others} => 0);
19907 @end group
19908 @end smallexample
19910 @noindent
19911 Here is a complete example of use:
19913 @smallexample @c ada
19914 @group
19915 @b{with} System.Dim.MKS; @b{use} System.Dim.Mks;
19916 @b{with} System.Dim.Mks_IO; @b{use} System.Dim.Mks_IO;
19917 @b{with} Text_IO; @b{use} Text_IO;
19918 @b{procedure} Free_Fall @b{is}
19919   @b{subtype} Acceleration @b{is} Mks_Type
19920     @b{with} Dimension => ("m/sec^2", 1, 0, -2, @b{others} => 0);
19921   G : @b{constant} acceleration := 9.81 * m / (s ** 2);
19922   T : Time := 10.0*s;
19923   Distance : Length;
19924 @end group
19925 @group
19926 @b{begin}
19927   Put ("Gravitational constant: ");
19928   Put (G, Aft => 2, Exp => 0); Put_Line ("");
19929   Distance := 0.5 * G * T ** 2;
19930   Put ("distance travelled in 10 seconds of free fall ");
19931   Put (Distance, Aft => 2, Exp => 0);
19932   Put_Line ("");
19933 @b{end} Free_Fall;
19934 @end group
19935 @end smallexample
19937 @noindent
19938 Execution of this program yields:
19939 @smallexample
19940 @group
19941 Gravitational constant:  9.81 m/sec^2
19942 distance travelled in 10 seconds of free fall 490.50 m
19943 @end group
19944 @end smallexample
19946 @noindent
19947 However, incorrect assignments such as:
19949 @smallexample @c ada
19950 @group
19951    Distance := 5.0;
19952    Distance := 5.0 * kg:
19953 @end group
19954 @end smallexample
19956 @noindent
19957 are rejected with the following diagnoses:
19959 @smallexample
19960 @group
19961    Distance := 5.0;
19962       >>> dimensions mismatch in assignment
19963       >>> left-hand side has dimension [L]
19964       >>> right-hand side is dimensionless
19965 @end group
19967 @group
19968    Distance := 5.0 * kg:
19969       >>> dimensions mismatch in assignment
19970       >>> left-hand side has dimension [L]
19971       >>> right-hand side has dimension [M]
19972 @end group
19973 @end smallexample
19975 @noindent
19976 The dimensions of an expression are properly displayed, even if there is
19977 no explicit subtype for it. If we add to the program:
19979 @smallexample @c ada
19980 @group
19981       Put ("Final velocity: ");
19982       Put (G * T, Aft =>2, Exp =>0);
19983       Put_Line ("");
19984 @end group
19985 @end smallexample
19987 @noindent
19988 then the output includes:
19989 @smallexample
19990      Final velocity: 98.10 m.s**(-1)
19991 @end smallexample
19994 @c *********************************
19995 @node Generating Ada Bindings for C and C++ headers
19996 @chapter Generating Ada Bindings for C and C++ headers
19997 @findex binding
19999 @noindent
20000 GNAT now comes with a binding generator for C and C++ headers which is
20001 intended to do 95% of the tedious work of generating Ada specs from C
20002 or C++ header files.
20004 Note that this capability is not intended to generate 100% correct Ada specs,
20005 and will is some cases require manual adjustments, although it can often
20006 be used out of the box in practice.
20008 Some of the known limitations include:
20010 @itemize @bullet
20011 @item only very simple character constant macros are translated into Ada
20012 constants. Function macros (macros with arguments) are partially translated
20013 as comments, to be completed manually if needed.
20014 @item some extensions (e.g. vector types) are not supported
20015 @item pointers to pointers or complex structures are mapped to System.Address
20016 @item identifiers with identical name (except casing) will generate compilation
20017       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
20018 @end itemize
20020 The code generated is using the Ada 2005 syntax, which makes it
20021 easier to interface with other languages than previous versions of Ada.
20023 @menu
20024 * Running the binding generator::
20025 * Generating bindings for C++ headers::
20026 * Switches::
20027 @end menu
20029 @node Running the binding generator
20030 @section Running the binding generator
20032 @noindent
20033 The binding generator is part of the @command{gcc} compiler and can be
20034 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20035 spec files for the header files specified on the command line, and all
20036 header files needed by these files transitively. For example:
20038 @smallexample
20039 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
20040 $ gcc -c -gnat05 *.ads
20041 @end smallexample
20043 will generate, under GNU/Linux, the following files: @file{time_h.ads},
20044 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20045 correspond to the files @file{/usr/include/time.h},
20046 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20047 mode these Ada specs.
20049 The @code{-C} switch tells @command{gcc} to extract comments from headers,
20050 and will attempt to generate corresponding Ada comments.
20052 If you want to generate a single Ada file and not the transitive closure, you
20053 can use instead the @option{-fdump-ada-spec-slim} switch.
20055 You can optionally specify a parent unit, of which all generated units will
20056 be children, using @code{-fada-spec-parent=}@var{unit}.
20058 Note that we recommend when possible to use the @command{g++} driver to
20059 generate bindings, even for most C headers, since this will in general
20060 generate better Ada specs. For generating bindings for C++ headers, it is
20061 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20062 is equivalent in this case. If @command{g++} cannot work on your C headers
20063 because of incompatibilities between C and C++, then you can fallback to
20064 @command{gcc} instead.
20066 For an example of better bindings generated from the C++ front-end,
20067 the name of the parameters (when available) are actually ignored by the C
20068 front-end. Consider the following C header:
20070 @smallexample
20071 extern void foo (int variable);
20072 @end smallexample
20074 with the C front-end, @code{variable} is ignored, and the above is handled as:
20076 @smallexample
20077 extern void foo (int);
20078 @end smallexample
20080 generating a generic:
20082 @smallexample
20083 procedure foo (param1 : int);
20084 @end smallexample
20086 with the C++ front-end, the name is available, and we generate:
20088 @smallexample
20089 procedure foo (variable : int);
20090 @end smallexample
20092 In some cases, the generated bindings will be more complete or more meaningful
20093 when defining some macros, which you can do via the @option{-D} switch. This
20094 is for example the case with @file{Xlib.h} under GNU/Linux:
20096 @smallexample
20097 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20098 @end smallexample
20100 The above will generate more complete bindings than a straight call without
20101 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20103 In other cases, it is not possible to parse a header file in a stand-alone
20104 manner, because other include files need to be included first. In this
20105 case, the solution is to create a small header file including the needed
20106 @code{#include} and possible @code{#define} directives. For example, to
20107 generate Ada bindings for @file{readline/readline.h}, you need to first
20108 include @file{stdio.h}, so you can create a file with the following two
20109 lines in e.g. @file{readline1.h}:
20111 @smallexample
20112 #include <stdio.h>
20113 #include <readline/readline.h>
20114 @end smallexample
20116 and then generate Ada bindings from this file:
20118 @smallexample
20119 $ g++ -c -fdump-ada-spec readline1.h
20120 @end smallexample
20122 @node Generating bindings for C++ headers
20123 @section Generating bindings for C++ headers
20125 @noindent
20126 Generating bindings for C++ headers is done using the same options, always
20127 with the @command{g++} compiler.
20129 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20130 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20131 multiple inheritance of abstract classes will be mapped to Ada interfaces
20132 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20133 information on interfacing to C++).
20135 For example, given the following C++ header file:
20137 @smallexample
20138 @group
20139 @cartouche
20140 class Carnivore @{
20141 public:
20142    virtual int Number_Of_Teeth () = 0;
20145 class Domestic @{
20146 public:
20147    virtual void Set_Owner (char* Name) = 0;
20150 class Animal @{
20151 public:
20152   int Age_Count;
20153   virtual void Set_Age (int New_Age);
20156 class Dog : Animal, Carnivore, Domestic @{
20157  public:
20158   int  Tooth_Count;
20159   char *Owner;
20161   virtual int  Number_Of_Teeth ();
20162   virtual void Set_Owner (char* Name);
20164   Dog();
20166 @end cartouche
20167 @end group
20168 @end smallexample
20170 The corresponding Ada code is generated:
20172 @smallexample @c ada
20173 @group
20174 @cartouche
20175   @b{package} Class_Carnivore @b{is}
20176     @b{type} Carnivore @b{is} @b{limited} interface;
20177     @b{pragma} Import (CPP, Carnivore);
20179     @b{function} Number_Of_Teeth (this : @b{access} Carnivore) @b{return} int @b{is} @b{abstract};
20180   @b{end};
20181   @b{use} Class_Carnivore;
20183   @b{package} Class_Domestic @b{is}
20184     @b{type} Domestic @b{is} @b{limited} interface;
20185     @b{pragma} Import (CPP, Domestic);
20187     @b{procedure} Set_Owner
20188       (this : @b{access} Domestic;
20189        Name : Interfaces.C.Strings.chars_ptr) @b{is} @b{abstract};
20190   @b{end};
20191   @b{use} Class_Domestic;
20193   @b{package} Class_Animal @b{is}
20194     @b{type} Animal @b{is} @b{tagged} @b{limited} @b{record}
20195       Age_Count : @b{aliased} int;
20196     @b{end} @b{record};
20197     @b{pragma} Import (CPP, Animal);
20199     @b{procedure} Set_Age (this : @b{access} Animal; New_Age : int);
20200     @b{pragma} Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20201   @b{end};
20202   @b{use} Class_Animal;
20204   @b{package} Class_Dog @b{is}
20205     @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
20206       Tooth_Count : @b{aliased} int;
20207       Owner : Interfaces.C.Strings.chars_ptr;
20208     @b{end} @b{record};
20209     @b{pragma} Import (CPP, Dog);
20211     @b{function} Number_Of_Teeth (this : @b{access} Dog) @b{return} int;
20212     @b{pragma} Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20214     @b{procedure} Set_Owner
20215       (this : @b{access} Dog; Name : Interfaces.C.Strings.chars_ptr);
20216     @b{pragma} Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20218     @b{function} New_Dog @b{return} Dog;
20219     @b{pragma} CPP_Constructor (New_Dog);
20220     @b{pragma} Import (CPP, New_Dog, "_ZN3DogC1Ev");
20221   @b{end};
20222   @b{use} Class_Dog;
20223 @end cartouche
20224 @end group
20225 @end smallexample
20227 @node Switches
20228 @section Switches
20230 @table @option
20231 @item -fdump-ada-spec
20232 @cindex @option{-fdump-ada-spec} (@command{gcc})
20233 Generate Ada spec files for the given header files transitively (including
20234 all header files that these headers depend upon).
20236 @item -fdump-ada-spec-slim
20237 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20238 Generate Ada spec files for the header files specified on the command line
20239 only.
20241 @item -fada-spec-parent=@var{unit}
20242 @cindex -fada-spec-parent (@command{gcc})
20243 Specifies that all files generated by @option{-fdump-ada-spec*} are
20244 to be child units of the specified parent unit.
20246 @item -C
20247 @cindex @option{-C} (@command{gcc})
20248 Extract comments from headers and generate Ada comments in the Ada spec files.
20249 @end table
20251 @node Other Utility Programs
20252 @chapter Other Utility Programs
20254 @noindent
20255 This chapter discusses some other utility programs available in the Ada
20256 environment.
20258 @menu
20259 * Using Other Utility Programs with GNAT::
20260 * The External Symbol Naming Scheme of GNAT::
20261 * Converting Ada Files to html with gnathtml::
20262 * Installing gnathtml::
20263 @end menu
20265 @node Using Other Utility Programs with GNAT
20266 @section Using Other Utility Programs with GNAT
20268 @noindent
20269 The object files generated by GNAT are in standard system format and in
20270 particular the debugging information uses this format. This means
20271 programs generated by GNAT can be used with existing utilities that
20272 depend on these formats.
20274 In general, any utility program that works with C will also often work with
20275 Ada programs generated by GNAT. This includes software utilities such as
20276 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20277 as Purify.
20279 @node The External Symbol Naming Scheme of GNAT
20280 @section The External Symbol Naming Scheme of GNAT
20282 @noindent
20283 In order to interpret the output from GNAT, when using tools that are
20284 originally intended for use with other languages, it is useful to
20285 understand the conventions used to generate link names from the Ada
20286 entity names.
20288 All link names are in all lowercase letters. With the exception of library
20289 procedure names, the mechanism used is simply to use the full expanded
20290 Ada name with dots replaced by double underscores. For example, suppose
20291 we have the following package spec:
20293 @smallexample @c ada
20294 @group
20295 @cartouche
20296 @b{package} QRS @b{is}
20297    MN : Integer;
20298 @b{end} QRS;
20299 @end cartouche
20300 @end group
20301 @end smallexample
20303 @noindent
20304 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20305 the corresponding link name is @code{qrs__mn}.
20306 @findex Export
20307 Of course if a @code{pragma Export} is used this may be overridden:
20309 @smallexample @c ada
20310 @group
20311 @cartouche
20312 @b{package} Exports @b{is}
20313    Var1 : Integer;
20314    @b{pragma} Export (Var1, C, External_Name => "var1_name");
20315    Var2 : Integer;
20316    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
20317 @b{end} Exports;
20318 @end cartouche
20319 @end group
20320 @end smallexample
20322 @noindent
20323 In this case, the link name for @var{Var1} is whatever link name the
20324 C compiler would assign for the C function @var{var1_name}. This typically
20325 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20326 system conventions, but other possibilities exist. The link name for
20327 @var{Var2} is @var{var2_link_name}, and this is not operating system
20328 dependent.
20330 @findex _main
20331 One exception occurs for library level procedures. A potential ambiguity
20332 arises between the required name @code{_main} for the C main program,
20333 and the name we would otherwise assign to an Ada library level procedure
20334 called @code{Main} (which might well not be the main program).
20336 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20337 names. So if we have a library level procedure such as
20339 @smallexample @c ada
20340 @group
20341 @cartouche
20342 @b{procedure} Hello (S : String);
20343 @end cartouche
20344 @end group
20345 @end smallexample
20347 @noindent
20348 the external name of this procedure will be @var{_ada_hello}.
20351 @node Converting Ada Files to html with gnathtml
20352 @section Converting Ada Files to HTML with @code{gnathtml}
20354 @noindent
20355 This @code{Perl} script allows Ada source files to be browsed using
20356 standard Web browsers. For installation procedure, see the section
20357 @xref{Installing gnathtml}.
20359 Ada reserved keywords are highlighted in a bold font and Ada comments in
20360 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20361 switch to suppress the generation of cross-referencing information, user
20362 defined variables and types will appear in a different color; you will
20363 be able to click on any identifier and go to its declaration.
20365 The command line is as follow:
20366 @smallexample
20367 @c $ perl gnathtml.pl @ovar{switches} @var{ada-files}
20368 @c Expanding @ovar macro inline (explanation in macro def comments)
20369 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{ada-files}
20370 @end smallexample
20372 @noindent
20373 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20374 an html file for every ada file, and a global file called @file{index.htm}.
20375 This file is an index of every identifier defined in the files.
20377 The available switches are the following ones:
20379 @table @option
20380 @item -83
20381 @cindex @option{-83} (@code{gnathtml})
20382 Only the Ada 83 subset of keywords will be highlighted.
20384 @item -cc @var{color}
20385 @cindex @option{-cc} (@code{gnathtml})
20386 This option allows you to change the color used for comments. The default
20387 value is green. The color argument can be any name accepted by html.
20389 @item -d
20390 @cindex @option{-d} (@code{gnathtml})
20391 If the Ada files depend on some other files (for instance through
20392 @code{with} clauses, the latter files will also be converted to html.
20393 Only the files in the user project will be converted to html, not the files
20394 in the run-time library itself.
20396 @item -D
20397 @cindex @option{-D} (@code{gnathtml})
20398 This command is the same as @option{-d} above, but @command{gnathtml} will
20399 also look for files in the run-time library, and generate html files for them.
20401 @item -ext @var{extension}
20402 @cindex @option{-ext} (@code{gnathtml})
20403 This option allows you to change the extension of the generated HTML files.
20404 If you do not specify an extension, it will default to @file{htm}.
20406 @item -f
20407 @cindex @option{-f} (@code{gnathtml})
20408 By default, gnathtml will generate html links only for global entities
20409 ('with'ed units, global variables and types,@dots{}).  If you specify
20410 @option{-f} on the command line, then links will be generated for local
20411 entities too.
20413 @item -l @var{number}
20414 @cindex @option{-l} (@code{gnathtml})
20415 If this switch is provided and @var{number} is not 0, then
20416 @code{gnathtml} will number the html files every @var{number} line.
20418 @item -I @var{dir}
20419 @cindex @option{-I} (@code{gnathtml})
20420 Specify a directory to search for library files (@file{.ALI} files) and
20421 source files. You can provide several -I switches on the command line,
20422 and the directories will be parsed in the order of the command line.
20424 @item -o @var{dir}
20425 @cindex @option{-o} (@code{gnathtml})
20426 Specify the output directory for html files. By default, gnathtml will
20427 saved the generated html files in a subdirectory named @file{html/}.
20429 @item -p @var{file}
20430 @cindex @option{-p} (@code{gnathtml})
20431 If you are using Emacs and the most recent Emacs Ada mode, which provides
20432 a full Integrated Development Environment for compiling, checking,
20433 running and debugging applications, you may use @file{.gpr} files
20434 to give the directories where Emacs can find sources and object files.
20436 Using this switch, you can tell gnathtml to use these files.
20437 This allows you to get an html version of your application, even if it
20438 is spread over multiple directories.
20440 @item -sc @var{color}
20441 @cindex @option{-sc} (@code{gnathtml})
20442 This switch allows you to change the color used for symbol
20443 definitions.
20444 The default value is red. The color argument can be any name accepted by html.
20446 @item -t @var{file}
20447 @cindex @option{-t} (@code{gnathtml})
20448 This switch provides the name of a file. This file contains a list of
20449 file names to be converted, and the effect is exactly as though they had
20450 appeared explicitly on the command line. This
20451 is the recommended way to work around the command line length limit on some
20452 systems.
20454 @end table
20456 @node Installing gnathtml
20457 @section Installing @code{gnathtml}
20459 @noindent
20460 @code{Perl} needs to be installed on your machine to run this script.
20461 @code{Perl} is freely available for almost every architecture and
20462 Operating System via the Internet.
20464 On Unix systems, you  may want to modify  the  first line of  the script
20465 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
20466 is. The syntax of this line is:
20467 @smallexample
20468 #!full_path_name_to_perl
20469 @end smallexample
20471 @noindent
20472 Alternatively, you may run the script using the following command line:
20474 @smallexample
20475 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20476 @c Expanding @ovar macro inline (explanation in macro def comments)
20477 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20478 @end smallexample
20481 @c ******************************
20482 @node Code Coverage and Profiling
20483 @chapter Code Coverage and Profiling
20484 @cindex Code Coverage
20485 @cindex Profiling
20487 @noindent
20488 This chapter describes how to use @code{gcov} - coverage testing tool - and
20489 @code{gprof} - profiler tool - on your Ada programs.
20491 @menu
20492 * Code Coverage of Ada Programs with gcov::
20493 * Profiling an Ada Program with gprof::
20494 @end menu
20496 @node Code Coverage of Ada Programs with gcov
20497 @section Code Coverage of Ada Programs with gcov
20498 @cindex gcov
20499 @cindex -fprofile-arcs
20500 @cindex -ftest-coverage
20501 @cindex -coverage
20502 @cindex Code Coverage
20504 @noindent
20505 @code{gcov} is a test coverage program: it analyzes the execution of a given
20506 program on selected tests, to help you determine the portions of the program
20507 that are still untested.
20509 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20510 User's Guide. You can refer to this documentation for a more complete
20511 description.
20513 This chapter provides a quick startup guide, and
20514 details some Gnat-specific features.
20516 @menu
20517 * Quick startup guide::
20518 * Gnat specifics::
20519 @end menu
20521 @node Quick startup guide
20522 @subsection Quick startup guide
20524 In order to perform coverage analysis of a program using @code{gcov}, 3
20525 steps are needed:
20527 @itemize @bullet
20528 @item
20529 Code instrumentation during the compilation process
20530 @item
20531 Execution of the instrumented program
20532 @item
20533 Execution of the @code{gcov} tool to generate the result.
20534 @end itemize
20536 The code instrumentation needed by gcov is created at the object level:
20537 The source code is not modified in any way, because the instrumentation code is
20538 inserted by gcc during the compilation process. To compile your code with code
20539 coverage activated, you need to recompile your whole project using the
20540 switches
20541 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20542 @code{-fprofile-arcs}.
20544 @smallexample
20545 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20546    -largs -fprofile-arcs
20547 @end smallexample
20549 This compilation process will create @file{.gcno} files together with
20550 the usual object files.
20552 Once the program is compiled with coverage instrumentation, you can
20553 run it as many times as needed - on portions of a test suite for
20554 example. The first execution will produce @file{.gcda} files at the
20555 same location as the @file{.gcno} files.  The following executions
20556 will update those files, so that a cumulative result of the covered
20557 portions of the program is generated.
20559 Finally, you need to call the @code{gcov} tool. The different options of
20560 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20562 This will create annotated source files with a @file{.gcov} extension:
20563 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20565 @node Gnat specifics
20566 @subsection Gnat specifics
20568 Because Ada semantics, portions of the source code may be shared among
20569 several object files. This is the case for example when generics are
20570 involved, when inlining is active  or when declarations generate  initialisation
20571 calls. In order to take
20572 into account this shared code, you need to call @code{gcov} on all
20573 source files of the tested program at once.
20575 The list of source files might exceed the system's maximum command line
20576 length. In order to bypass this limitation, a new mechanism has been
20577 implemented in @code{gcov}: you can now list all your project's files into a
20578 text file, and provide this file to gcov as a parameter,  preceded by a @@
20579 (e.g. @samp{gcov @@mysrclist.txt}).
20581 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20582 not supported as there can be unresolved symbols during the final link.
20584 @node Profiling an Ada Program with gprof
20585 @section Profiling an Ada Program with gprof
20586 @cindex gprof
20587 @cindex -pg
20588 @cindex Profiling
20590 @noindent
20591 This section is not meant to be an exhaustive documentation of @code{gprof}.
20592 Full documentation for it can be found in the GNU Profiler User's Guide
20593 documentation that is part of this GNAT distribution.
20595 Profiling a program helps determine the parts of a program that are executed
20596 most often, and are therefore the most time-consuming.
20598 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20599 better handle Ada programs and multitasking.
20600 It is currently supported on the following platforms
20601 @itemize @bullet
20602 @item
20603 linux x86/x86_64
20604 @item
20605 solaris sparc/sparc64/x86
20606 @item
20607 windows x86
20608 @end itemize
20610 @noindent
20611 In order to profile a program using @code{gprof}, 3 steps are needed:
20613 @itemize @bullet
20614 @item
20615 Code instrumentation, requiring a full recompilation of the project with the
20616 proper switches.
20617 @item
20618 Execution of the program under the analysis conditions, i.e. with the desired
20619 input.
20620 @item
20621 Analysis of the results using the @code{gprof} tool.
20622 @end itemize
20624 @noindent
20625 The following sections detail the different steps, and indicate how
20626 to interpret the results:
20627 @menu
20628 * Compilation for profiling::
20629 * Program execution::
20630 * Running gprof::
20631 * Interpretation of profiling results::
20632 @end menu
20634 @node Compilation for profiling
20635 @subsection Compilation for profiling
20636 @cindex -pg
20637 @cindex Profiling
20639 In order to profile a program the first step is to tell the compiler
20640 to generate the necessary profiling information. The compiler switch to be used
20641 is @code{-pg}, which must be added to other compilation switches. This
20642 switch needs to be specified both during compilation and link stages, and can
20643 be specified once when using gnatmake:
20645 @smallexample
20646 gnatmake -f -pg -P my_project
20647 @end smallexample
20649 @noindent
20650 Note that only the objects that were compiled with the @samp{-pg} switch will
20651 be profiled; if you need to profile your whole project, use the @samp{-f}
20652 gnatmake switch to force full recompilation.
20654 @node Program execution
20655 @subsection Program execution
20657 @noindent
20658 Once the program has been compiled for profiling, you can run it as usual.
20660 The only constraint imposed by profiling is that the program must terminate
20661 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20662 properly analyzed.
20664 Once the program completes execution, a data file called @file{gmon.out} is
20665 generated in the directory where the program was launched from. If this file
20666 already exists, it will be overwritten.
20668 @node Running gprof
20669 @subsection Running gprof
20671 @noindent
20672 The @code{gprof} tool is called as follow:
20674 @smallexample
20675 gprof my_prog gmon.out
20676 @end smallexample
20678 @noindent
20679 or simpler:
20681 @smallexample
20682 gprof my_prog
20683 @end smallexample
20685 @noindent
20686 The complete form of the gprof command line is the following:
20688 @smallexample
20689 gprof [switches] [executable [data-file]]
20690 @end smallexample
20692 @noindent
20693 @code{gprof} supports numerous switch. The order of these
20694 switch does not matter. The full list of options can be found in
20695 the GNU Profiler User's Guide documentation that comes with this documentation.
20697 The following is the subset of those switches that is most relevant:
20699 @table @option
20701 @item --demangle[=@var{style}]
20702 @itemx --no-demangle
20703 @cindex @option{--demangle} (@code{gprof})
20704 These options control whether symbol names should be demangled when
20705 printing output.  The default is to demangle C++ symbols.  The
20706 @code{--no-demangle} option may be used to turn off demangling. Different
20707 compilers have different mangling styles.  The optional demangling style
20708 argument can be used to choose an appropriate demangling style for your
20709 compiler, in particular Ada symbols generated by GNAT can be demangled using
20710 @code{--demangle=gnat}.
20712 @item -e @var{function_name}
20713 @cindex @option{-e} (@code{gprof})
20714 The @samp{-e @var{function}} option tells @code{gprof} not to print
20715 information about the function @var{function_name} (and its
20716 children@dots{}) in the call graph.  The function will still be listed
20717 as a child of any functions that call it, but its index number will be
20718 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
20719 given; only one @var{function_name} may be indicated with each @samp{-e}
20720 option.
20722 @item -E @var{function_name}
20723 @cindex @option{-E} (@code{gprof})
20724 The @code{-E @var{function}} option works like the @code{-e} option, but
20725 execution time spent in the function (and children who were not called from
20726 anywhere else), will not be used to compute the percentages-of-time for
20727 the call graph.  More than one @samp{-E} option may be given; only one
20728 @var{function_name} may be indicated with each @samp{-E} option.
20730 @item -f @var{function_name}
20731 @cindex @option{-f} (@code{gprof})
20732 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20733 call graph to the function @var{function_name} and its children (and
20734 their children@dots{}).  More than one @samp{-f} option may be given;
20735 only one @var{function_name} may be indicated with each @samp{-f}
20736 option.
20738 @item -F @var{function_name}
20739 @cindex @option{-F} (@code{gprof})
20740 The @samp{-F @var{function}} option works like the @code{-f} option, but
20741 only time spent in the function and its children (and their
20742 children@dots{}) will be used to determine total-time and
20743 percentages-of-time for the call graph.  More than one @samp{-F} option
20744 may be given; only one @var{function_name} may be indicated with each
20745 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
20747 @end table
20749 @node Interpretation of profiling results
20750 @subsection Interpretation of profiling results
20752 @noindent
20754 The results of the profiling analysis are represented by two arrays: the
20755 'flat profile' and the 'call graph'. Full documentation of those outputs
20756 can be found in the GNU Profiler User's Guide.
20758 The flat profile shows the time spent in each function of the program, and how
20759 many time it has been called. This allows you to locate easily the most
20760 time-consuming functions.
20762 The call graph shows, for each subprogram, the subprograms that call it,
20763 and the subprograms that it calls. It also provides an estimate of the time
20764 spent in each of those callers/called subprograms.
20766 @c ******************************
20767 @node Running and Debugging Ada Programs
20768 @chapter Running and Debugging Ada Programs
20769 @cindex Debugging
20771 @noindent
20772 This chapter discusses how to debug Ada programs.
20774 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20776 @enumerate
20777 @item
20778 The illegality may be a violation of the static semantics of Ada. In
20779 that case GNAT diagnoses the constructs in the program that are illegal.
20780 It is then a straightforward matter for the user to modify those parts of
20781 the program.
20783 @item
20784 The illegality may be a violation of the dynamic semantics of Ada. In
20785 that case the program compiles and executes, but may generate incorrect
20786 results, or may terminate abnormally with some exception.
20788 @item
20789 When presented with a program that contains convoluted errors, GNAT
20790 itself may terminate abnormally without providing full diagnostics on
20791 the incorrect user program.
20792 @end enumerate
20794 @menu
20795 * The GNAT Debugger GDB::
20796 * Running GDB::
20797 * Introduction to GDB Commands::
20798 * Using Ada Expressions::
20799 * Calling User-Defined Subprograms::
20800 * Using the Next Command in a Function::
20801 * Ada Exceptions::
20802 * Ada Tasks::
20803 * Debugging Generic Units::
20804 * Remote Debugging with gdbserver::
20805 * GNAT Abnormal Termination or Failure to Terminate::
20806 * Naming Conventions for GNAT Source Files::
20807 * Getting Internal Debugging Information::
20808 * Stack Traceback::
20809 @end menu
20811 @cindex Debugger
20812 @findex gdb
20814 @node The GNAT Debugger GDB
20815 @section The GNAT Debugger GDB
20817 @noindent
20818 @code{GDB} is a general purpose, platform-independent debugger that
20819 can be used to debug mixed-language programs compiled with @command{gcc},
20820 and in particular is capable of debugging Ada programs compiled with
20821 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20822 complex Ada data structures.
20824 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20825 for full details on the usage of @code{GDB}, including a section on
20826 its usage on programs. This manual should be consulted for full
20827 details. The section that follows is a brief introduction to the
20828 philosophy and use of @code{GDB}.
20830 When GNAT programs are compiled, the compiler optionally writes debugging
20831 information into the generated object file, including information on
20832 line numbers, and on declared types and variables. This information is
20833 separate from the generated code. It makes the object files considerably
20834 larger, but it does not add to the size of the actual executable that
20835 will be loaded into memory, and has no impact on run-time performance. The
20836 generation of debug information is triggered by the use of the
20837 -g switch in the @command{gcc} or @command{gnatmake} command
20838 used to carry out the compilations. It is important to emphasize that
20839 the use of these options does not change the generated code.
20841 The debugging information is written in standard system formats that
20842 are used by many tools, including debuggers and profilers. The format
20843 of the information is typically designed to describe C types and
20844 semantics, but GNAT implements a translation scheme which allows full
20845 details about Ada types and variables to be encoded into these
20846 standard C formats. Details of this encoding scheme may be found in
20847 the file exp_dbug.ads in the GNAT source distribution. However, the
20848 details of this encoding are, in general, of no interest to a user,
20849 since @code{GDB} automatically performs the necessary decoding.
20851 When a program is bound and linked, the debugging information is
20852 collected from the object files, and stored in the executable image of
20853 the program. Again, this process significantly increases the size of
20854 the generated executable file, but it does not increase the size of
20855 the executable program itself. Furthermore, if this program is run in
20856 the normal manner, it runs exactly as if the debug information were
20857 not present, and takes no more actual memory.
20859 However, if the program is run under control of @code{GDB}, the
20860 debugger is activated.  The image of the program is loaded, at which
20861 point it is ready to run.  If a run command is given, then the program
20862 will run exactly as it would have if @code{GDB} were not present. This
20863 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
20864 entirely non-intrusive until a breakpoint is encountered.  If no
20865 breakpoint is ever hit, the program will run exactly as it would if no
20866 debugger were present. When a breakpoint is hit, @code{GDB} accesses
20867 the debugging information and can respond to user commands to inspect
20868 variables, and more generally to report on the state of execution.
20870 @c **************
20871 @node Running GDB
20872 @section Running GDB
20874 @noindent
20875 This section describes how to initiate the debugger.
20876 @c The above sentence is really just filler, but it was otherwise
20877 @c clumsy to get the first paragraph nonindented given the conditional
20878 @c nature of the description
20880 The debugger can be launched from a @code{GPS} menu or
20881 directly from the command line. The description below covers the latter use.
20882 All the commands shown can be used in the @code{GPS} debug console window,
20883 but there are usually more GUI-based ways to achieve the same effect.
20885 The command to run @code{GDB} is
20887 @smallexample
20888 $ gdb program
20889 @end smallexample
20891 @noindent
20892 where @code{program} is the name of the executable file. This
20893 activates the debugger and results in a prompt for debugger commands.
20894 The simplest command is simply @code{run}, which causes the program to run
20895 exactly as if the debugger were not present. The following section
20896 describes some of the additional commands that can be given to @code{GDB}.
20898 @c *******************************
20899 @node Introduction to GDB Commands
20900 @section Introduction to GDB Commands
20902 @noindent
20903 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
20904 Debugging with GDB, gdb, Debugging with GDB},
20905 for extensive documentation on the use
20906 of these commands, together with examples of their use. Furthermore,
20907 the command @command{help} invoked from within GDB activates a simple help
20908 facility which summarizes the available commands and their options.
20909 In this section we summarize a few of the most commonly
20910 used commands to give an idea of what @code{GDB} is about. You should create
20911 a simple program with debugging information and experiment with the use of
20912 these @code{GDB} commands on the program as you read through the
20913 following section.
20915 @table @code
20916 @item set args @var{arguments}
20917 The @var{arguments} list above is a list of arguments to be passed to
20918 the program on a subsequent run command, just as though the arguments
20919 had been entered on a normal invocation of the program. The @code{set args}
20920 command is not needed if the program does not require arguments.
20922 @item run
20923 The @code{run} command causes execution of the program to start from
20924 the beginning. If the program is already running, that is to say if
20925 you are currently positioned at a breakpoint, then a prompt will ask
20926 for confirmation that you want to abandon the current execution and
20927 restart.
20929 @item breakpoint @var{location}
20930 The breakpoint command sets a breakpoint, that is to say a point at which
20931 execution will halt and @code{GDB} will await further
20932 commands. @var{location} is
20933 either a line number within a file, given in the format @code{file:linenumber},
20934 or it is the name of a subprogram. If you request that a breakpoint be set on
20935 a subprogram that is overloaded, a prompt will ask you to specify on which of
20936 those subprograms you want to breakpoint. You can also
20937 specify that all of them should be breakpointed. If the program is run
20938 and execution encounters the breakpoint, then the program
20939 stops and @code{GDB} signals that the breakpoint was encountered by
20940 printing the line of code before which the program is halted.
20942 @item catch exception @var{name}
20943 This command causes the program execution to stop whenever exception
20944 @var{name} is raised.  If @var{name} is omitted, then the execution is
20945 suspended when any exception is raised.
20947 @item print @var{expression}
20948 This will print the value of the given expression. Most simple
20949 Ada expression formats are properly handled by @code{GDB}, so the expression
20950 can contain function calls, variables, operators, and attribute references.
20952 @item continue
20953 Continues execution following a breakpoint, until the next breakpoint or the
20954 termination of the program.
20956 @item step
20957 Executes a single line after a breakpoint. If the next statement
20958 is a subprogram call, execution continues into (the first statement of)
20959 the called subprogram.
20961 @item next
20962 Executes a single line. If this line is a subprogram call, executes and
20963 returns from the call.
20965 @item list
20966 Lists a few lines around the current source location. In practice, it
20967 is usually more convenient to have a separate edit window open with the
20968 relevant source file displayed. Successive applications of this command
20969 print subsequent lines. The command can be given an argument which is a
20970 line number, in which case it displays a few lines around the specified one.
20972 @item backtrace
20973 Displays a backtrace of the call chain. This command is typically
20974 used after a breakpoint has occurred, to examine the sequence of calls that
20975 leads to the current breakpoint. The display includes one line for each
20976 activation record (frame) corresponding to an active subprogram.
20978 @item up
20979 At a breakpoint, @code{GDB} can display the values of variables local
20980 to the current frame. The command @code{up} can be used to
20981 examine the contents of other active frames, by moving the focus up
20982 the stack, that is to say from callee to caller, one frame at a time.
20984 @item down
20985 Moves the focus of @code{GDB} down from the frame currently being
20986 examined to the frame of its callee (the reverse of the previous command),
20988 @item frame @var{n}
20989 Inspect the frame with the given number. The value 0 denotes the frame
20990 of the current breakpoint, that is to say the top of the call stack.
20992 @item kill
20993 Kills the child process in which the program is running under GDB.
20994 This may be useful for several purposes:
20995 @itemize @bullet
20996 @item
20997 It allows you to recompile and relink your program, since on many systems
20998 you cannot regenerate an executable file while it is running in a process.
20999 @item
21000 You can run your program outside the debugger, on systems that do not
21001 permit executing a program outside GDB while breakpoints are set
21002 within GDB.
21003 @item
21004 It allows you to debug a core dump rather than a running process.
21005 @end itemize
21006 @end table
21008 @noindent
21009 The above list is a very short introduction to the commands that
21010 @code{GDB} provides. Important additional capabilities, including conditional
21011 breakpoints, the ability to execute command sequences on a breakpoint,
21012 the ability to debug at the machine instruction level and many other
21013 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
21014 Debugging with GDB}.  Note that most commands can be abbreviated
21015 (for example, c for continue, bt for backtrace).
21017 @node Using Ada Expressions
21018 @section Using Ada Expressions
21019 @cindex Ada expressions
21021 @noindent
21022 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
21023 extensions. The philosophy behind the design of this subset is
21025 @itemize @bullet
21026 @item
21027 That @code{GDB} should provide basic literals and access to operations for
21028 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21029 leaving more sophisticated computations to subprograms written into the
21030 program (which therefore may be called from @code{GDB}).
21032 @item
21033 That type safety and strict adherence to Ada language restrictions
21034 are not particularly important to the @code{GDB} user.
21036 @item
21037 That brevity is important to the @code{GDB} user.
21038 @end itemize
21040 @noindent
21041 Thus, for brevity, the debugger acts as if there were
21042 implicit @code{with} and @code{use} clauses in effect for all user-written
21043 packages, thus making it unnecessary to fully qualify most names with
21044 their packages, regardless of context. Where this causes ambiguity,
21045 @code{GDB} asks the user's intent.
21047 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21048 GDB, gdb, Debugging with GDB}.
21050 @node Calling User-Defined Subprograms
21051 @section Calling User-Defined Subprograms
21053 @noindent
21054 An important capability of @code{GDB} is the ability to call user-defined
21055 subprograms while debugging. This is achieved simply by entering
21056 a subprogram call statement in the form:
21058 @smallexample
21059 call subprogram-name (parameters)
21060 @end smallexample
21062 @noindent
21063 The keyword @code{call} can be omitted in the normal case where the
21064 @code{subprogram-name} does not coincide with any of the predefined
21065 @code{GDB} commands.
21067 The effect is to invoke the given subprogram, passing it the
21068 list of parameters that is supplied. The parameters can be expressions and
21069 can include variables from the program being debugged. The
21070 subprogram must be defined
21071 at the library level within your program, and @code{GDB} will call the
21072 subprogram within the environment of your program execution (which
21073 means that the subprogram is free to access or even modify variables
21074 within your program).
21076 The most important use of this facility is in allowing the inclusion of
21077 debugging routines that are tailored to particular data structures
21078 in your program. Such debugging routines can be written to provide a suitably
21079 high-level description of an abstract type, rather than a low-level dump
21080 of its physical layout. After all, the standard
21081 @code{GDB print} command only knows the physical layout of your
21082 types, not their abstract meaning. Debugging routines can provide information
21083 at the desired semantic level and are thus enormously useful.
21085 For example, when debugging GNAT itself, it is crucial to have access to
21086 the contents of the tree nodes used to represent the program internally.
21087 But tree nodes are represented simply by an integer value (which in turn
21088 is an index into a table of nodes).
21089 Using the @code{print} command on a tree node would simply print this integer
21090 value, which is not very useful. But the PN routine (defined in file
21091 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21092 a useful high level representation of the tree node, which includes the
21093 syntactic category of the node, its position in the source, the integers
21094 that denote descendant nodes and parent node, as well as varied
21095 semantic information. To study this example in more detail, you might want to
21096 look at the body of the PN procedure in the stated file.
21098 Another useful application of this capability is to deal with situations of
21099 complex data which are not handled suitably by GDB. For example, if you specify
21100 Convention Fortran for a multi-dimensional array, GDB does not know that
21101 the ordering of array elements has been switched and will not properly
21102 address the array elements. In such a case, instead of trying to print the
21103 elements directly from GDB, you can write a callable procedure that prints
21104 the elements in the desired format.
21106 @node Using the Next Command in a Function
21107 @section Using the Next Command in a Function
21109 @noindent
21110 When you use the @code{next} command in a function, the current source
21111 location will advance to the next statement as usual. A special case
21112 arises in the case of a @code{return} statement.
21114 Part of the code for a return statement is the ``epilogue'' of the function.
21115 This is the code that returns to the caller. There is only one copy of
21116 this epilogue code, and it is typically associated with the last return
21117 statement in the function if there is more than one return. In some
21118 implementations, this epilogue is associated with the first statement
21119 of the function.
21121 The result is that if you use the @code{next} command from a return
21122 statement that is not the last return statement of the function you
21123 may see a strange apparent jump to the last return statement or to
21124 the start of the function. You should simply ignore this odd jump.
21125 The value returned is always that from the first return statement
21126 that was stepped through.
21128 @node Ada Exceptions
21129 @section Stopping when Ada Exceptions are Raised
21130 @cindex Exceptions
21132 @noindent
21133 You can set catchpoints that stop the program execution when your program
21134 raises selected exceptions.
21136 @table @code
21137 @item catch exception
21138 Set a catchpoint that stops execution whenever (any task in the) program
21139 raises any exception.
21141 @item catch exception @var{name}
21142 Set a catchpoint that stops execution whenever (any task in the) program
21143 raises the exception @var{name}.
21145 @item catch exception unhandled
21146 Set a catchpoint that stops executing whenever (any task in the) program
21147 raises an exception for which there is no handler.
21149 @item info exceptions
21150 @itemx info exceptions @var{regexp}
21151 The @code{info exceptions} command permits the user to examine all defined
21152 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21153 argument, prints out only those exceptions whose name matches @var{regexp}.
21154 @end table
21156 @node Ada Tasks
21157 @section Ada Tasks
21158 @cindex Tasks
21160 @noindent
21161 @code{GDB} allows the following task-related commands:
21163 @table @code
21164 @item info tasks
21165 This command shows a list of current Ada tasks, as in the following example:
21167 @smallexample
21168 @iftex
21169 @leftskip=0cm
21170 @end iftex
21171 (gdb) info tasks
21172   ID       TID P-ID   Thread Pri State                 Name
21173    1   8088000   0   807e000  15 Child Activation Wait main_task
21174    2   80a4000   1   80ae000  15 Accept/Select Wait    b
21175    3   809a800   1   80a4800  15 Child Activation Wait a
21176 *  4   80ae800   3   80b8000  15 Running               c
21177 @end smallexample
21179 @noindent
21180 In this listing, the asterisk before the first task indicates it to be the
21181 currently running task. The first column lists the task ID that is used
21182 to refer to tasks in the following commands.
21184 @item break @var{linespec} task @var{taskid}
21185 @itemx break @var{linespec} task @var{taskid} if @dots{}
21186 @cindex Breakpoints and tasks
21187 These commands are like the @code{break @dots{} thread @dots{}}.
21188 @var{linespec} specifies source lines.
21190 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21191 to specify that you only want @code{GDB} to stop the program when a
21192 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21193 numeric task identifiers assigned by @code{GDB}, shown in the first
21194 column of the @samp{info tasks} display.
21196 If you do not specify @samp{task @var{taskid}} when you set a
21197 breakpoint, the breakpoint applies to @emph{all} tasks of your
21198 program.
21200 You can use the @code{task} qualifier on conditional breakpoints as
21201 well; in this case, place @samp{task @var{taskid}} before the
21202 breakpoint condition (before the @code{if}).
21204 @item task @var{taskno}
21205 @cindex Task switching
21207 This command allows switching to the task referred by @var{taskno}. In
21208 particular, this allows browsing of the backtrace of the specified
21209 task. It is advisable to switch back to the original task before
21210 continuing execution otherwise the scheduling of the program may be
21211 perturbed.
21212 @end table
21214 @noindent
21215 For more detailed information on the tasking support,
21216 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21218 @node Debugging Generic Units
21219 @section Debugging Generic Units
21220 @cindex Debugging Generic Units
21221 @cindex Generics
21223 @noindent
21224 GNAT always uses code expansion for generic instantiation. This means that
21225 each time an instantiation occurs, a complete copy of the original code is
21226 made, with appropriate substitutions of formals by actuals.
21228 It is not possible to refer to the original generic entities in
21229 @code{GDB}, but it is always possible to debug a particular instance of
21230 a generic, by using the appropriate expanded names. For example, if we have
21232 @smallexample @c ada
21233 @group
21234 @cartouche
21235 @b{procedure} g @b{is}
21237    @b{generic} @b{package} k @b{is}
21238       @b{procedure} kp (v1 : @b{in} @b{out} integer);
21239    @b{end} k;
21241    @b{package} @b{body} k @b{is}
21242       @b{procedure} kp (v1 : @b{in} @b{out} integer) @b{is}
21243       @b{begin}
21244          v1 := v1 + 1;
21245       @b{end} kp;
21246    @b{end} k;
21248    @b{package} k1 @b{is} @b{new} k;
21249    @b{package} k2 @b{is} @b{new} k;
21251    var : integer := 1;
21253 @b{begin}
21254    k1.kp (var);
21255    k2.kp (var);
21256    k1.kp (var);
21257    k2.kp (var);
21258 @b{end};
21259 @end cartouche
21260 @end group
21261 @end smallexample
21263 @noindent
21264 Then to break on a call to procedure kp in the k2 instance, simply
21265 use the command:
21267 @smallexample
21268 (gdb) break g.k2.kp
21269 @end smallexample
21271 @noindent
21272 When the breakpoint occurs, you can step through the code of the
21273 instance in the normal manner and examine the values of local variables, as for
21274 other units.
21276 @node Remote Debugging with gdbserver
21277 @section Remote Debugging with gdbserver
21278 @cindex Remote Debugging with gdbserver
21280 @noindent
21281 On platforms where gdbserver is supported, it is possible to use this tool
21282 to debug your application remotely.  This can be useful in situations
21283 where the program needs to be run on a target host that is different
21284 from the host used for development, particularly when the target has
21285 a limited amount of resources (either CPU and/or memory).
21287 To do so, start your program using gdbserver on the target machine.
21288 gdbserver then automatically suspends the execution of your program
21289 at its entry point, waiting for a debugger to connect to it.  The
21290 following commands starts an application and tells gdbserver to
21291 wait for a connection with the debugger on localhost port 4444.
21293 @smallexample
21294 $ gdbserver localhost:4444 program
21295 Process program created; pid = 5685
21296 Listening on port 4444
21297 @end smallexample
21299 Once gdbserver has started listening, we can tell the debugger to establish
21300 a connection with this gdbserver, and then start the same debugging session
21301 as if the program was being debugged on the same host, directly under
21302 the control of GDB.
21304 @smallexample
21305 $ gdb program
21306 (gdb) target remote targethost:4444
21307 Remote debugging using targethost:4444
21308 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21309 (gdb) b foo.adb:3
21310 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21311 (gdb) continue
21312 Continuing.
21314 Breakpoint 1, foo () at foo.adb:4
21315 4       end foo;
21316 @end smallexample
21318 It is also possible to use gdbserver to attach to an already running
21319 program, in which case the execution of that program is simply suspended
21320 until the connection between the debugger and gdbserver is established.
21322 For more information on how to use gdbserver, @ref{Top, Server, Using
21323 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
21324 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21326 @node GNAT Abnormal Termination or Failure to Terminate
21327 @section GNAT Abnormal Termination or Failure to Terminate
21328 @cindex GNAT Abnormal Termination or Failure to Terminate
21330 @noindent
21331 When presented with programs that contain serious errors in syntax
21332 or semantics,
21333 GNAT may on rare occasions  experience problems in operation, such
21334 as aborting with a
21335 segmentation fault or illegal memory access, raising an internal
21336 exception, terminating abnormally, or failing to terminate at all.
21337 In such cases, you can activate
21338 various features of GNAT that can help you pinpoint the construct in your
21339 program that is the likely source of the problem.
21341 The following strategies are presented in increasing order of
21342 difficulty, corresponding to your experience in using GNAT and your
21343 familiarity with compiler internals.
21345 @enumerate
21346 @item
21347 Run @command{gcc} with the @option{-gnatf}. This first
21348 switch causes all errors on a given line to be reported. In its absence,
21349 only the first error on a line is displayed.
21351 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21352 are encountered, rather than after compilation is terminated. If GNAT
21353 terminates prematurely or goes into an infinite loop, the last error
21354 message displayed may help to pinpoint the culprit.
21356 @item
21357 Run @command{gcc} with the @option{-v (verbose)} switch. In this
21358 mode, @command{gcc} produces ongoing information about the progress of the
21359 compilation and provides the name of each procedure as code is
21360 generated. This switch allows you to find which Ada procedure was being
21361 compiled when it encountered a code generation problem.
21363 @item
21364 @cindex @option{-gnatdc} switch
21365 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21366 switch that does for the front-end what @option{-v} does
21367 for the back end. The system prints the name of each unit,
21368 either a compilation unit or nested unit, as it is being analyzed.
21369 @item
21370 Finally, you can start
21371 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21372 front-end of GNAT, and can be run independently (normally it is just
21373 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21374 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21375 @code{where} command is the first line of attack; the variable
21376 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21377 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21378 which the execution stopped, and @code{input_file name} indicates the name of
21379 the source file.
21380 @end enumerate
21382 @node Naming Conventions for GNAT Source Files
21383 @section Naming Conventions for GNAT Source Files
21385 @noindent
21386 In order to examine the workings of the GNAT system, the following
21387 brief description of its organization may be helpful:
21389 @itemize @bullet
21390 @item
21391 Files with prefix @file{sc} contain the lexical scanner.
21393 @item
21394 All files prefixed with @file{par} are components of the parser. The
21395 numbers correspond to chapters of the Ada Reference Manual. For example,
21396 parsing of select statements can be found in @file{par-ch9.adb}.
21398 @item
21399 All files prefixed with @file{sem} perform semantic analysis. The
21400 numbers correspond to chapters of the Ada standard. For example, all
21401 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21402 addition, some features of the language require sufficient special processing
21403 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21404 dynamic dispatching, etc.
21406 @item
21407 All files prefixed with @file{exp} perform normalization and
21408 expansion of the intermediate representation (abstract syntax tree, or AST).
21409 these files use the same numbering scheme as the parser and semantics files.
21410 For example, the construction of record initialization procedures is done in
21411 @file{exp_ch3.adb}.
21413 @item
21414 The files prefixed with @file{bind} implement the binder, which
21415 verifies the consistency of the compilation, determines an order of
21416 elaboration, and generates the bind file.
21418 @item
21419 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21420 data structures used by the front-end.
21422 @item
21423 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21424 the abstract syntax tree as produced by the parser.
21426 @item
21427 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21428 all entities, computed during semantic analysis.
21430 @item
21431 Library management issues are dealt with in files with prefix
21432 @file{lib}.
21434 @item
21435 @findex Ada
21436 @cindex Annex A
21437 Ada files with the prefix @file{a-} are children of @code{Ada}, as
21438 defined in Annex A.
21440 @item
21441 @findex Interfaces
21442 @cindex Annex B
21443 Files with prefix @file{i-} are children of @code{Interfaces}, as
21444 defined in Annex B.
21446 @item
21447 @findex System
21448 Files with prefix @file{s-} are children of @code{System}. This includes
21449 both language-defined children and GNAT run-time routines.
21451 @item
21452 @findex GNAT
21453 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
21454 general-purpose packages, fully documented in their specs. All
21455 the other @file{.c} files are modifications of common @command{gcc} files.
21456 @end itemize
21458 @node Getting Internal Debugging Information
21459 @section Getting Internal Debugging Information
21461 @noindent
21462 Most compilers have internal debugging switches and modes. GNAT
21463 does also, except GNAT internal debugging switches and modes are not
21464 secret. A summary and full description of all the compiler and binder
21465 debug flags are in the file @file{debug.adb}. You must obtain the
21466 sources of the compiler to see the full detailed effects of these flags.
21468 The switches that print the source of the program (reconstructed from
21469 the internal tree) are of general interest for user programs, as are the
21470 options to print
21471 the full internal tree, and the entity table (the symbol table
21472 information). The reconstructed source provides a readable version of the
21473 program after the front-end has completed analysis and  expansion,
21474 and is useful when studying the performance of specific constructs.
21475 For example, constraint checks are indicated, complex aggregates
21476 are replaced with loops and assignments, and tasking primitives
21477 are replaced with run-time calls.
21479 @node Stack Traceback
21480 @section Stack Traceback
21481 @cindex traceback
21482 @cindex stack traceback
21483 @cindex stack unwinding
21485 @noindent
21486 Traceback is a mechanism to display the sequence of subprogram calls that
21487 leads to a specified execution point in a program. Often (but not always)
21488 the execution point is an instruction at which an exception has been raised.
21489 This mechanism is also known as @i{stack unwinding} because it obtains
21490 its information by scanning the run-time stack and recovering the activation
21491 records of all active subprograms. Stack unwinding is one of the most
21492 important tools for program debugging.
21494 The first entry stored in traceback corresponds to the deepest calling level,
21495 that is to say the subprogram currently executing the instruction
21496 from which we want to obtain the traceback.
21498 Note that there is no runtime performance penalty when stack traceback
21499 is enabled, and no exception is raised during program execution.
21501 @menu
21502 * Non-Symbolic Traceback::
21503 * Symbolic Traceback::
21504 @end menu
21506 @node Non-Symbolic Traceback
21507 @subsection Non-Symbolic Traceback
21508 @cindex traceback, non-symbolic
21510 @noindent
21511 Note: this feature is not supported on all platforms. See
21512 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21513 platforms.
21515 @menu
21516 * Tracebacks From an Unhandled Exception::
21517 * Tracebacks From Exception Occurrences (non-symbolic)::
21518 * Tracebacks From Anywhere in a Program (non-symbolic)::
21519 @end menu
21521 @node Tracebacks From an Unhandled Exception
21522 @subsubsection Tracebacks From an Unhandled Exception
21524 @noindent
21525 A runtime non-symbolic traceback is a list of addresses of call instructions.
21526 To enable this feature you must use the @option{-E}
21527 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21528 of exception information. You can retrieve this information using the
21529 @code{addr2line} tool.
21531 Here is a simple example:
21533 @smallexample @c ada
21534 @cartouche
21535 @b{procedure} STB @b{is}
21537    @b{procedure} P1 @b{is}
21538    @b{begin}
21539       @b{raise} Constraint_Error;
21540    @b{end} P1;
21542    @b{procedure} P2 @b{is}
21543    @b{begin}
21544       P1;
21545    @b{end} P2;
21547 @b{begin}
21548    P2;
21549 @b{end} STB;
21550 @end cartouche
21551 @end smallexample
21553 @smallexample
21554 $ gnatmake stb -bargs -E
21555 $ stb
21557 Execution terminated by unhandled exception
21558 Exception name: CONSTRAINT_ERROR
21559 Message: stb.adb:5
21560 Call stack traceback locations:
21561 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21562 @end smallexample
21564 @noindent
21565 As we see the traceback lists a sequence of addresses for the unhandled
21566 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21567 guess that this exception come from procedure P1. To translate these
21568 addresses into the source lines where the calls appear, the
21569 @code{addr2line} tool, described below, is invaluable. The use of this tool
21570 requires the program to be compiled with debug information.
21572 @smallexample
21573 $ gnatmake -g stb -bargs -E
21574 $ stb
21576 Execution terminated by unhandled exception
21577 Exception name: CONSTRAINT_ERROR
21578 Message: stb.adb:5
21579 Call stack traceback locations:
21580 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21582 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21583    0x4011f1 0x77e892a4
21585 00401373 at d:/stb/stb.adb:5
21586 0040138B at d:/stb/stb.adb:10
21587 0040139C at d:/stb/stb.adb:14
21588 00401335 at d:/stb/b~stb.adb:104
21589 004011C4 at /build/@dots{}/crt1.c:200
21590 004011F1 at /build/@dots{}/crt1.c:222
21591 77E892A4 in ?? at ??:0
21592 @end smallexample
21594 @noindent
21595 The @code{addr2line} tool has several other useful options:
21597 @table @code
21598 @item --functions
21599 to get the function name corresponding to any location
21601 @item --demangle=gnat
21602 to use the gnat decoding mode for the function names. Note that
21603 for binutils version 2.9.x the option is simply @option{--demangle}.
21604 @end table
21606 @smallexample
21607 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21608    0x40139c 0x401335 0x4011c4 0x4011f1
21610 00401373 in stb.p1 at d:/stb/stb.adb:5
21611 0040138B in stb.p2 at d:/stb/stb.adb:10
21612 0040139C in stb at d:/stb/stb.adb:14
21613 00401335 in main at d:/stb/b~stb.adb:104
21614 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21615 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21616 @end smallexample
21618 @noindent
21619 From this traceback we can see that the exception was raised in
21620 @file{stb.adb} at line 5, which was reached from a procedure call in
21621 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21622 which contains the call to the main program.
21623 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21624 and the output will vary from platform to platform.
21626 It is also possible to use @code{GDB} with these traceback addresses to debug
21627 the program. For example, we can break at a given code location, as reported
21628 in the stack traceback:
21630 @smallexample
21631 $ gdb -nw stb
21632 @noindent
21633 Furthermore, this feature is not implemented inside Windows DLL. Only
21634 the non-symbolic traceback is reported in this case.
21636 (gdb) break *0x401373
21637 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21638 @end smallexample
21640 @noindent
21641 It is important to note that the stack traceback addresses
21642 do not change when debug information is included. This is particularly useful
21643 because it makes it possible to release software without debug information (to
21644 minimize object size), get a field report that includes a stack traceback
21645 whenever an internal bug occurs, and then be able to retrieve the sequence
21646 of calls with the same program compiled with debug information.
21648 @node Tracebacks From Exception Occurrences (non-symbolic)
21649 @subsubsection Tracebacks From Exception Occurrences
21651 @noindent
21652 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21653 The stack traceback is attached to the exception information string, and can
21654 be retrieved in an exception handler within the Ada program, by means of the
21655 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21657 @smallexample @c ada
21658 @b{with} Ada.Text_IO;
21659 @b{with} Ada.Exceptions;
21661 @b{procedure} STB @b{is}
21663    @b{use} Ada;
21664    @b{use} Ada.Exceptions;
21666    @b{procedure} P1 @b{is}
21667       K : Positive := 1;
21668    @b{begin}
21669       K := K - 1;
21670    @b{exception}
21671       @b{when} E : @b{others} =>
21672          Text_IO.Put_Line (Exception_Information (E));
21673    @b{end} P1;
21675    @b{procedure} P2 @b{is}
21676    @b{begin}
21677       P1;
21678    @b{end} P2;
21680 @b{begin}
21681    P2;
21682 @b{end} STB;
21683 @end smallexample
21685 @noindent
21686 This program will output:
21688 @smallexample
21689 $ stb
21691 Exception name: CONSTRAINT_ERROR
21692 Message: stb.adb:12
21693 Call stack traceback locations:
21694 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21695 @end smallexample
21697 @node Tracebacks From Anywhere in a Program (non-symbolic)
21698 @subsubsection Tracebacks From Anywhere in a Program
21700 @noindent
21701 It is also possible to retrieve a stack traceback from anywhere in a
21702 program. For this you need to
21703 use the @code{GNAT.Traceback} API. This package includes a procedure called
21704 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21705 display procedures described below. It is not necessary to use the
21706 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21707 is invoked explicitly.
21709 @noindent
21710 In the following example we compute a traceback at a specific location in
21711 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21712 convert addresses to strings:
21714 @smallexample @c ada
21715 @b{with} Ada.Text_IO;
21716 @b{with} GNAT.Traceback;
21717 @b{with} GNAT.Debug_Utilities;
21719 @b{procedure} STB @b{is}
21721    @b{use} Ada;
21722    @b{use} GNAT;
21723    @b{use} GNAT.Traceback;
21725    @b{procedure} P1 @b{is}
21726       TB  : Tracebacks_Array (1 .. 10);
21727       --@i{  We are asking for a maximum of 10 stack frames.}
21728       Len : Natural;
21729       --@i{  Len will receive the actual number of stack frames returned.}
21730    @b{begin}
21731       Call_Chain (TB, Len);
21733       Text_IO.Put ("In STB.P1 : ");
21735       @b{for} K @b{in} 1 .. Len @b{loop}
21736          Text_IO.Put (Debug_Utilities.Image (TB (K)));
21737          Text_IO.Put (' ');
21738       @b{end} @b{loop};
21740       Text_IO.New_Line;
21741    @b{end} P1;
21743    @b{procedure} P2 @b{is}
21744    @b{begin}
21745       P1;
21746    @b{end} P2;
21748 @b{begin}
21749    P2;
21750 @b{end} STB;
21751 @end smallexample
21753 @smallexample
21754 $ gnatmake -g stb
21755 $ stb
21757 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21758 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21759 @end smallexample
21761 @noindent
21762 You can then get further information by invoking the @code{addr2line}
21763 tool as described earlier (note that the hexadecimal addresses
21764 need to be specified in C format, with a leading ``0x'').
21766 @node Symbolic Traceback
21767 @subsection Symbolic Traceback
21768 @cindex traceback, symbolic
21770 @noindent
21771 A symbolic traceback is a stack traceback in which procedure names are
21772 associated with each code location.
21774 @noindent
21775 Note that this feature is not supported on all platforms. See
21776 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21777 list of currently supported platforms.
21779 @noindent
21780 Note that the symbolic traceback requires that the program be compiled
21781 with debug information. If it is not compiled with debug information
21782 only the non-symbolic information will be valid.
21784 @menu
21785 * Tracebacks From Exception Occurrences (symbolic)::
21786 * Tracebacks From Anywhere in a Program (symbolic)::
21787 @end menu
21789 @node Tracebacks From Exception Occurrences (symbolic)
21790 @subsubsection Tracebacks From Exception Occurrences
21792 @smallexample @c ada
21793 @b{with} Ada.Text_IO;
21794 @b{with} GNAT.Traceback.Symbolic;
21796 @b{procedure} STB @b{is}
21798    @b{procedure} P1 @b{is}
21799    @b{begin}
21800       @b{raise} Constraint_Error;
21801    @b{end} P1;
21803    @b{procedure} P2 @b{is}
21804    @b{begin}
21805       P1;
21806    @b{end} P2;
21808    @b{procedure} P3 @b{is}
21809    @b{begin}
21810       P2;
21811    @b{end} P3;
21813 @b{begin}
21814    P3;
21815 @b{exception}
21816    @b{when} E : @b{others} =>
21817       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21818 @b{end} STB;
21819 @end smallexample
21821 @smallexample
21822 $ gnatmake -g .\stb -bargs -E
21823 $ stb
21825 0040149F in stb.p1 at stb.adb:8
21826 004014B7 in stb.p2 at stb.adb:13
21827 004014CF in stb.p3 at stb.adb:18
21828 004015DD in ada.stb at stb.adb:22
21829 00401461 in main at b~stb.adb:168
21830 004011C4 in __mingw_CRTStartup at crt1.c:200
21831 004011F1 in mainCRTStartup at crt1.c:222
21832 77E892A4 in ?? at ??:0
21833 @end smallexample
21835 @noindent
21836 In the above example the ``.\'' syntax in the @command{gnatmake} command
21837 is currently required by @command{addr2line} for files that are in
21838 the current working directory.
21839 Moreover, the exact sequence of linker options may vary from platform
21840 to platform.
21841 The above @option{-largs} section is for Windows platforms. By contrast,
21842 under Unix there is no need for the @option{-largs} section.
21843 Differences across platforms are due to details of linker implementation.
21845 @node Tracebacks From Anywhere in a Program (symbolic)
21846 @subsubsection Tracebacks From Anywhere in a Program
21848 @noindent
21849 It is possible to get a symbolic stack traceback
21850 from anywhere in a program, just as for non-symbolic tracebacks.
21851 The first step is to obtain a non-symbolic
21852 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21853 information. Here is an example:
21855 @smallexample @c ada
21856 @b{with} Ada.Text_IO;
21857 @b{with} GNAT.Traceback;
21858 @b{with} GNAT.Traceback.Symbolic;
21860 @b{procedure} STB @b{is}
21862    @b{use} Ada;
21863    @b{use} GNAT.Traceback;
21864    @b{use} GNAT.Traceback.Symbolic;
21866    @b{procedure} P1 @b{is}
21867       TB  : Tracebacks_Array (1 .. 10);
21868       --@i{  We are asking for a maximum of 10 stack frames.}
21869       Len : Natural;
21870       --@i{  Len will receive the actual number of stack frames returned.}
21871    @b{begin}
21872       Call_Chain (TB, Len);
21873       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
21874    @b{end} P1;
21876    @b{procedure} P2 @b{is}
21877    @b{begin}
21878       P1;
21879    @b{end} P2;
21881 @b{begin}
21882    P2;
21883 @b{end} STB;
21884 @end smallexample
21886 @c ******************************
21888 @c **************************************
21889 @node Platform-Specific Information for the Run-Time Libraries
21890 @appendix Platform-Specific Information for the Run-Time Libraries
21891 @cindex Tasking and threads libraries
21892 @cindex Threads libraries and tasking
21893 @cindex Run-time libraries (platform-specific information)
21895 @noindent
21896 The GNAT run-time implementation may vary with respect to both the
21897 underlying threads library and the exception handling scheme.
21898 For threads support, one or more of the following are supplied:
21899 @itemize @bullet
21900 @item @b{native threads library}, a binding to the thread package from
21901 the underlying operating system
21903 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21904 POSIX thread package
21905 @end itemize
21907 @noindent
21908 For exception handling, either or both of two models are supplied:
21909 @itemize @bullet
21910 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21911 Most programs should experience a substantial speed improvement by
21912 being compiled with a ZCX run-time.
21913 This is especially true for
21914 tasking applications or applications with many exception handlers.}
21915 @cindex Zero-Cost Exceptions
21916 @cindex ZCX (Zero-Cost Exceptions)
21917 which uses binder-generated tables that
21918 are interrogated at run time to locate a handler
21920 @item @b{setjmp / longjmp} (``SJLJ''),
21921 @cindex setjmp/longjmp Exception Model
21922 @cindex SJLJ (setjmp/longjmp Exception Model)
21923 which uses dynamically-set data to establish
21924 the set of handlers
21925 @end itemize
21927 @noindent
21928 This appendix summarizes which combinations of threads and exception support
21929 are supplied on various GNAT platforms.
21930 It then shows how to select a particular library either
21931 permanently or temporarily,
21932 explains the properties of (and tradeoffs among) the various threads
21933 libraries, and provides some additional
21934 information about several specific platforms.
21936 @menu
21937 * Summary of Run-Time Configurations::
21938 * Specifying a Run-Time Library::
21939 * Choosing the Scheduling Policy::
21940 * Solaris-Specific Considerations::
21941 * Linux-Specific Considerations::
21942 * AIX-Specific Considerations::
21943 * RTX-Specific Considerations::
21944 * HP-UX-Specific Considerations::
21945 @end menu
21947 @node Summary of Run-Time Configurations
21948 @section Summary of Run-Time Configurations
21950 @multitable @columnfractions .30 .70
21951 @item @b{alpha-openvms}
21952 @item @code{@ @ }@i{rts-native (default)}
21953 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21954 @item @code{@ @ @ @ }Exceptions @tab ZCX
21956 @item @code{@ @ }@i{rts-sjlj}
21957 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21958 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21960 @item @b{ia64-hp_linux}
21961 @item @code{@ @ }@i{rts-native (default)}
21962 @item @code{@ @ @ @ }Tasking    @tab pthread library
21963 @item @code{@ @ @ @ }Exceptions @tab ZCX
21965 @item @b{ia64-hpux}
21966 @item @code{@ @ }@i{rts-native (default)}
21967 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21968 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21970 @item @b{ia64-openvms}
21971 @item @code{@ @ }@i{rts-native (default)}
21972 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21973 @item @code{@ @ @ @ }Exceptions @tab ZCX
21975 @item @b{ia64-sgi_linux}
21976 @item @code{@ @ }@i{rts-native (default)}
21977 @item @code{@ @ @ @ }Tasking    @tab pthread library
21978 @item @code{@ @ @ @ }Exceptions @tab ZCX
21980 @item @b{pa-hpux}
21981 @item @code{@ @ }@i{rts-native (default)}
21982 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21983 @item @code{@ @ @ @ }Exceptions @tab ZCX
21985 @item @code{@ @ }@i{rts-sjlj}
21986 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21987 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21989 @item @b{ppc-aix}
21990 @item @code{@ @ }@i{rts-native (default)}
21991 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21992 @item @code{@ @ @ @ }Exceptions @tab ZCX
21994 @item @code{@ @ }@i{rts-sjlj}
21995 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21996 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21998 @item @b{ppc-darwin}
21999 @item @code{@ @ }@i{rts-native (default)}
22000 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
22001 @item @code{@ @ @ @ }Exceptions @tab ZCX
22003 @item @b{sparc-solaris}  @tab
22004 @item @code{@ @ }@i{rts-native (default)}
22005 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22006 @item @code{@ @ @ @ }Exceptions @tab ZCX
22008 @item @code{@ @ }@i{rts-pthread}
22009 @item @code{@ @ @ @ }Tasking    @tab pthread library
22010 @item @code{@ @ @ @ }Exceptions @tab ZCX
22012 @item @code{@ @ }@i{rts-sjlj}
22013 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22014 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22016 @item @b{sparc64-solaris}  @tab
22017 @item @code{@ @ }@i{rts-native (default)}
22018 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22019 @item @code{@ @ @ @ }Exceptions @tab ZCX
22021 @item @b{x86-linux}
22022 @item @code{@ @ }@i{rts-native (default)}
22023 @item @code{@ @ @ @ }Tasking    @tab pthread library
22024 @item @code{@ @ @ @ }Exceptions @tab ZCX
22026 @item @code{@ @ }@i{rts-sjlj}
22027 @item @code{@ @ @ @ }Tasking    @tab pthread library
22028 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22030 @item @b{x86-lynx}
22031 @item @code{@ @ }@i{rts-native (default)}
22032 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22033 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22035 @item @b{x86-solaris}
22036 @item @code{@ @ }@i{rts-native (default)}
22037 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
22038 @item @code{@ @ @ @ }Exceptions @tab ZCX
22040 @item @code{@ @ }@i{rts-sjlj}
22041 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22042 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22044 @item @b{x86-windows}
22045 @item @code{@ @ }@i{rts-native (default)}
22046 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22047 @item @code{@ @ @ @ }Exceptions @tab ZCX
22049 @item @code{@ @ }@i{rts-sjlj}
22050 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22051 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22053 @item @b{x86-windows-rtx}
22054 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22055 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
22056 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22058 @item @code{@ @ }@i{rts-rtx-w32}
22059 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
22060 @item @code{@ @ @ @ }Exceptions @tab ZCX
22062 @item @b{x86_64-linux}
22063 @item @code{@ @ }@i{rts-native (default)}
22064 @item @code{@ @ @ @ }Tasking    @tab pthread library
22065 @item @code{@ @ @ @ }Exceptions @tab ZCX
22067 @item @code{@ @ }@i{rts-sjlj}
22068 @item @code{@ @ @ @ }Tasking    @tab pthread library
22069 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22071 @end multitable
22073 @node Specifying a Run-Time Library
22074 @section Specifying a Run-Time Library
22076 @noindent
22077 The @file{adainclude} subdirectory containing the sources of the GNAT
22078 run-time library, and the @file{adalib} subdirectory containing the
22079 @file{ALI} files and the static and/or shared GNAT library, are located
22080 in the gcc target-dependent area:
22082 @smallexample
22083 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22084 @end smallexample
22086 @noindent
22087 As indicated above, on some platforms several run-time libraries are supplied.
22088 These libraries are installed in the target dependent area and
22089 contain a complete source and binary subdirectory. The detailed description
22090 below explains the differences between the different libraries in terms of
22091 their thread support.
22093 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22094 This default run time is selected by the means of soft links.
22095 For example on x86-linux:
22097 @smallexample
22098 @group
22099  $(target-dir)
22100      |
22101      +--- adainclude----------+
22102      |                        |
22103      +--- adalib-----------+  |
22104      |                     |  |
22105      +--- rts-native       |  |
22106      |    |                |  |
22107      |    +--- adainclude <---+
22108      |    |                |
22109      |    +--- adalib <----+
22110      |
22111      +--- rts-sjlj
22112           |
22113           +--- adainclude
22114           |
22115           +--- adalib
22116 @end group
22117 @end smallexample
22119 @noindent
22120 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22121 these soft links can be modified with the following commands:
22123 @smallexample
22124 $ cd $target
22125 $ rm -f adainclude adalib
22126 $ ln -s rts-sjlj/adainclude adainclude
22127 $ ln -s rts-sjlj/adalib adalib
22128 @end smallexample
22130 @noindent
22131 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22132 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22133 @file{$target/ada_object_path}.
22135 Selecting another run-time library temporarily can be
22136 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22137 @cindex @option{--RTS} option
22139 @node Choosing the Scheduling Policy
22140 @section Choosing the Scheduling Policy
22142 @noindent
22143 When using a POSIX threads implementation, you have a choice of several
22144 scheduling policies: @code{SCHED_FIFO},
22145 @cindex @code{SCHED_FIFO} scheduling policy
22146 @code{SCHED_RR}
22147 @cindex @code{SCHED_RR} scheduling policy
22148 and @code{SCHED_OTHER}.
22149 @cindex @code{SCHED_OTHER} scheduling policy
22150 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22151 or @code{SCHED_RR} requires special (e.g., root) privileges.
22153 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22154 @code{SCHED_FIFO},
22155 @cindex @code{SCHED_FIFO} scheduling policy
22156 you can use one of the following:
22158 @itemize @bullet
22159 @item
22160 @code{pragma Time_Slice (0.0)}
22161 @cindex pragma Time_Slice
22162 @item
22163 the corresponding binder option @option{-T0}
22164 @cindex @option{-T0} option
22165 @item
22166 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22167 @cindex pragma Task_Dispatching_Policy
22168 @end itemize
22170 @noindent
22171 To specify @code{SCHED_RR},
22172 @cindex @code{SCHED_RR} scheduling policy
22173 you should use @code{pragma Time_Slice} with a
22174 value greater than @code{0.0}, or else use the corresponding @option{-T}
22175 binder option.
22177 @node Solaris-Specific Considerations
22178 @section Solaris-Specific Considerations
22179 @cindex Solaris Sparc threads libraries
22181 @noindent
22182 This section addresses some topics related to the various threads libraries
22183 on Sparc Solaris.
22185 @menu
22186 * Solaris Threads Issues::
22187 @end menu
22189 @node Solaris Threads Issues
22190 @subsection Solaris Threads Issues
22192 @noindent
22193 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22194 library based on POSIX threads --- @emph{rts-pthread}.
22195 @cindex rts-pthread threads library
22196 This run-time library has the advantage of being mostly shared across all
22197 POSIX-compliant thread implementations, and it also provides under
22198 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22199 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22200 and @code{PTHREAD_PRIO_PROTECT}
22201 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22202 semantics that can be selected using the predefined pragma
22203 @code{Locking_Policy}
22204 @cindex pragma Locking_Policy (under rts-pthread)
22205 with respectively
22206 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22207 @cindex @code{Inheritance_Locking} (under rts-pthread)
22208 @cindex @code{Ceiling_Locking} (under rts-pthread)
22210 As explained above, the native run-time library is based on the Solaris thread
22211 library (@code{libthread}) and is the default library.
22213 When the Solaris threads library is used (this is the default), programs
22214 compiled with GNAT can automatically take advantage of
22215 and can thus execute on multiple processors.
22216 The user can alternatively specify a processor on which the program should run
22217 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22218 is made by
22219 setting the environment variable @env{GNAT_PROCESSOR}
22220 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22221 to one of the following:
22223 @table @code
22224 @item -2
22225 Use the default configuration (run the program on all
22226 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22227 unset
22229 @item -1
22230 Let the run-time implementation choose one processor and run the program on
22231 that processor
22233 @item 0 .. Last_Proc
22234 Run the program on the specified processor.
22235 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22236 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22237 @end table
22239 @node Linux-Specific Considerations
22240 @section Linux-Specific Considerations
22241 @cindex Linux threads libraries
22243 @noindent
22244 On GNU/Linux without NPTL support (usually system with GNU C Library
22245 older than 2.3), the signal model is not POSIX compliant, which means
22246 that to send a signal to the process, you need to send the signal to all
22247 threads, e.g.@: by using @code{killpg()}.
22249 @node AIX-Specific Considerations
22250 @section AIX-Specific Considerations
22251 @cindex AIX resolver library
22253 @noindent
22254 On AIX, the resolver library initializes some internal structure on
22255 the first call to @code{get*by*} functions, which are used to implement
22256 @code{GNAT.Sockets.Get_Host_By_Name} and
22257 @code{GNAT.Sockets.Get_Host_By_Address}.
22258 If such initialization occurs within an Ada task, and the stack size for
22259 the task is the default size, a stack overflow may occur.
22261 To avoid this overflow, the user should either ensure that the first call
22262 to @code{GNAT.Sockets.Get_Host_By_Name} or
22263 @code{GNAT.Sockets.Get_Host_By_Addrss}
22264 occurs in the environment task, or use @code{pragma Storage_Size} to
22265 specify a sufficiently large size for the stack of the task that contains
22266 this call.
22268 @node RTX-Specific Considerations
22269 @section RTX-Specific Considerations
22270 @cindex RTX libraries
22272 @noindent
22273 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22274 API. Applications can be built to work in two different modes:
22276 @itemize @bullet
22277 @item
22278 Windows executables that run in Ring 3 to utilize memory protection
22279 (@emph{rts-rtx-w32}).
22281 @item
22282 Real-time subsystem (RTSS) executables that run in Ring 0, where
22283 performance can be optimized with RTSS applications taking precedent
22284 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22285 the Microsoft linker to handle RTSS libraries.
22287 @end itemize
22289 @node HP-UX-Specific Considerations
22290 @section HP-UX-Specific Considerations
22291 @cindex HP-UX Scheduling
22293 @noindent
22294 On HP-UX, appropriate privileges are required to change the scheduling
22295 parameters of a task. The calling process must have appropriate
22296 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22297 successfully change the scheduling parameters.
22299 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22300 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22301 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22303 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22304 one of the following:
22306 @itemize @bullet
22307 @item
22308 @code{pragma Time_Slice (0.0)}
22309 @cindex pragma Time_Slice
22310 @item
22311 the corresponding binder option @option{-T0}
22312 @cindex @option{-T0} option
22313 @item
22314 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22315 @cindex pragma Task_Dispatching_Policy
22316 @end itemize
22318 @noindent
22319 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22320 you should use @code{pragma Time_Slice} with a
22321 value greater than @code{0.0}, or use the corresponding @option{-T}
22322 binder option, or set the @code{pragma Task_Dispatching_Policy
22323 (Round_Robin_Within_Priorities)}.
22325 @c *******************************
22326 @node Example of Binder Output File
22327 @appendix Example of Binder Output File
22329 @noindent
22330 This Appendix displays the source code for @command{gnatbind}'s output
22331 file generated for a simple ``Hello World'' program.
22332 Comments have been added for clarification purposes.
22334 @smallexample @c adanocomment
22335 @iftex
22336 @leftskip=0cm
22337 @end iftex
22338 --  The package is called Ada_Main unless this name is actually used
22339 --  as a unit name in the partition, in which case some other unique
22340 --  name is used.
22342 @b{pragma} Ada_95;
22343 @b{with} System;
22344 @b{package} ada_main @b{is}
22345    @b{pragma} Warnings (Off);
22347    --  The main program saves the parameters (argument count,
22348    --  argument values, environment pointer) in global variables
22349    --  for later access by other units including
22350    --  Ada.Command_Line.
22352    gnat_argc : Integer;
22353    gnat_argv : System.Address;
22354    gnat_envp : System.Address;
22356    --  The actual variables are stored in a library routine. This
22357    --  is useful for some shared library situations, where there
22358    --  are problems if variables are not in the library.
22360    @b{pragma} Import (C, gnat_argc);
22361    @b{pragma} Import (C, gnat_argv);
22362    @b{pragma} Import (C, gnat_envp);
22364    --  The exit status is similarly an external location
22366    gnat_exit_status : Integer;
22367    @b{pragma} Import (C, gnat_exit_status);
22369    GNAT_Version : @b{constant} String :=
22370                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
22371    @b{pragma} Export (C, GNAT_Version, "__gnat_version");
22373    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
22374    @b{pragma} Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
22376    --  This is the generated adainit routine that performs
22377    --  initialization at the start of execution. In the case
22378    --  where Ada is the main program, this main program makes
22379    --  a call to adainit at program startup.
22381    @b{procedure} adainit;
22382    @b{pragma} Export (C, adainit, "adainit");
22384    --  This is the generated adafinal routine that performs
22385    --  finalization at the end of execution. In the case where
22386    --  Ada is the main program, this main program makes a call
22387    --  to adafinal at program termination.
22389    @b{procedure} adafinal;
22390    @b{pragma} Export (C, adafinal, "adafinal");
22392    --  This routine is called at the start of execution. It is
22393    --  a dummy routine that is used by the debugger to breakpoint
22394    --  at the start of execution.
22396    --  This is the actual generated main program (it would be
22397    --  suppressed if the no main program switch were used). As
22398    --  required by standard system conventions, this program has
22399    --  the external name main.
22401    @b{function} main
22402      (argc : Integer;
22403       argv : System.Address;
22404       envp : System.Address)
22405       @b{return} Integer;
22406    @b{pragma} Export (C, main, "main");
22408    --  The following set of constants give the version
22409    --  identification values for every unit in the bound
22410    --  partition. This identification is computed from all
22411    --  dependent semantic units, and corresponds to the
22412    --  string that would be returned by use of the
22413    --  Body_Version or Version attributes.
22415    --  The following Export pragmas export the version numbers
22416    --  with symbolic names ending in B (for body) or S
22417    --  (for spec) so that they can be located in a link. The
22418    --  information provided here is sufficient to track down
22419    --  the exact versions of units used in a given build.
22422    @b{type} Version_32 @b{is} @b{mod} 2 ** 32;
22423    u00001 : @b{constant} Version_32 := 16#8ad6e54a#;
22424    @b{pragma} Export (C, u00001, "helloB");
22425    u00002 : @b{constant} Version_32 := 16#fbff4c67#;
22426    @b{pragma} Export (C, u00002, "system__standard_libraryB");
22427    u00003 : @b{constant} Version_32 := 16#1ec6fd90#;
22428    @b{pragma} Export (C, u00003, "system__standard_libraryS");
22429    u00004 : @b{constant} Version_32 := 16#3ffc8e18#;
22430    @b{pragma} Export (C, u00004, "adaS");
22431    u00005 : @b{constant} Version_32 := 16#28f088c2#;
22432    @b{pragma} Export (C, u00005, "ada__text_ioB");
22433    u00006 : @b{constant} Version_32 := 16#f372c8ac#;
22434    @b{pragma} Export (C, u00006, "ada__text_ioS");
22435    u00007 : @b{constant} Version_32 := 16#2c143749#;
22436    @b{pragma} Export (C, u00007, "ada__exceptionsB");
22437    u00008 : @b{constant} Version_32 := 16#f4f0cce8#;
22438    @b{pragma} Export (C, u00008, "ada__exceptionsS");
22439    u00009 : @b{constant} Version_32 := 16#a46739c0#;
22440    @b{pragma} Export (C, u00009, "ada__exceptions__last_chance_handlerB");
22441    u00010 : @b{constant} Version_32 := 16#3aac8c92#;
22442    @b{pragma} Export (C, u00010, "ada__exceptions__last_chance_handlerS");
22443    u00011 : @b{constant} Version_32 := 16#1d274481#;
22444    @b{pragma} Export (C, u00011, "systemS");
22445    u00012 : @b{constant} Version_32 := 16#a207fefe#;
22446    @b{pragma} Export (C, u00012, "system__soft_linksB");
22447    u00013 : @b{constant} Version_32 := 16#467d9556#;
22448    @b{pragma} Export (C, u00013, "system__soft_linksS");
22449    u00014 : @b{constant} Version_32 := 16#b01dad17#;
22450    @b{pragma} Export (C, u00014, "system__parametersB");
22451    u00015 : @b{constant} Version_32 := 16#630d49fe#;
22452    @b{pragma} Export (C, u00015, "system__parametersS");
22453    u00016 : @b{constant} Version_32 := 16#b19b6653#;
22454    @b{pragma} Export (C, u00016, "system__secondary_stackB");
22455    u00017 : @b{constant} Version_32 := 16#b6468be8#;
22456    @b{pragma} Export (C, u00017, "system__secondary_stackS");
22457    u00018 : @b{constant} Version_32 := 16#39a03df9#;
22458    @b{pragma} Export (C, u00018, "system__storage_elementsB");
22459    u00019 : @b{constant} Version_32 := 16#30e40e85#;
22460    @b{pragma} Export (C, u00019, "system__storage_elementsS");
22461    u00020 : @b{constant} Version_32 := 16#41837d1e#;
22462    @b{pragma} Export (C, u00020, "system__stack_checkingB");
22463    u00021 : @b{constant} Version_32 := 16#93982f69#;
22464    @b{pragma} Export (C, u00021, "system__stack_checkingS");
22465    u00022 : @b{constant} Version_32 := 16#393398c1#;
22466    @b{pragma} Export (C, u00022, "system__exception_tableB");
22467    u00023 : @b{constant} Version_32 := 16#b33e2294#;
22468    @b{pragma} Export (C, u00023, "system__exception_tableS");
22469    u00024 : @b{constant} Version_32 := 16#ce4af020#;
22470    @b{pragma} Export (C, u00024, "system__exceptionsB");
22471    u00025 : @b{constant} Version_32 := 16#75442977#;
22472    @b{pragma} Export (C, u00025, "system__exceptionsS");
22473    u00026 : @b{constant} Version_32 := 16#37d758f1#;
22474    @b{pragma} Export (C, u00026, "system__exceptions__machineS");
22475    u00027 : @b{constant} Version_32 := 16#b895431d#;
22476    @b{pragma} Export (C, u00027, "system__exceptions_debugB");
22477    u00028 : @b{constant} Version_32 := 16#aec55d3f#;
22478    @b{pragma} Export (C, u00028, "system__exceptions_debugS");
22479    u00029 : @b{constant} Version_32 := 16#570325c8#;
22480    @b{pragma} Export (C, u00029, "system__img_intB");
22481    u00030 : @b{constant} Version_32 := 16#1ffca443#;
22482    @b{pragma} Export (C, u00030, "system__img_intS");
22483    u00031 : @b{constant} Version_32 := 16#b98c3e16#;
22484    @b{pragma} Export (C, u00031, "system__tracebackB");
22485    u00032 : @b{constant} Version_32 := 16#831a9d5a#;
22486    @b{pragma} Export (C, u00032, "system__tracebackS");
22487    u00033 : @b{constant} Version_32 := 16#9ed49525#;
22488    @b{pragma} Export (C, u00033, "system__traceback_entriesB");
22489    u00034 : @b{constant} Version_32 := 16#1d7cb2f1#;
22490    @b{pragma} Export (C, u00034, "system__traceback_entriesS");
22491    u00035 : @b{constant} Version_32 := 16#8c33a517#;
22492    @b{pragma} Export (C, u00035, "system__wch_conB");
22493    u00036 : @b{constant} Version_32 := 16#065a6653#;
22494    @b{pragma} Export (C, u00036, "system__wch_conS");
22495    u00037 : @b{constant} Version_32 := 16#9721e840#;
22496    @b{pragma} Export (C, u00037, "system__wch_stwB");
22497    u00038 : @b{constant} Version_32 := 16#2b4b4a52#;
22498    @b{pragma} Export (C, u00038, "system__wch_stwS");
22499    u00039 : @b{constant} Version_32 := 16#92b797cb#;
22500    @b{pragma} Export (C, u00039, "system__wch_cnvB");
22501    u00040 : @b{constant} Version_32 := 16#09eddca0#;
22502    @b{pragma} Export (C, u00040, "system__wch_cnvS");
22503    u00041 : @b{constant} Version_32 := 16#6033a23f#;
22504    @b{pragma} Export (C, u00041, "interfacesS");
22505    u00042 : @b{constant} Version_32 := 16#ece6fdb6#;
22506    @b{pragma} Export (C, u00042, "system__wch_jisB");
22507    u00043 : @b{constant} Version_32 := 16#899dc581#;
22508    @b{pragma} Export (C, u00043, "system__wch_jisS");
22509    u00044 : @b{constant} Version_32 := 16#10558b11#;
22510    @b{pragma} Export (C, u00044, "ada__streamsB");
22511    u00045 : @b{constant} Version_32 := 16#2e6701ab#;
22512    @b{pragma} Export (C, u00045, "ada__streamsS");
22513    u00046 : @b{constant} Version_32 := 16#db5c917c#;
22514    @b{pragma} Export (C, u00046, "ada__io_exceptionsS");
22515    u00047 : @b{constant} Version_32 := 16#12c8cd7d#;
22516    @b{pragma} Export (C, u00047, "ada__tagsB");
22517    u00048 : @b{constant} Version_32 := 16#ce72c228#;
22518    @b{pragma} Export (C, u00048, "ada__tagsS");
22519    u00049 : @b{constant} Version_32 := 16#c3335bfd#;
22520    @b{pragma} Export (C, u00049, "system__htableB");
22521    u00050 : @b{constant} Version_32 := 16#99e5f76b#;
22522    @b{pragma} Export (C, u00050, "system__htableS");
22523    u00051 : @b{constant} Version_32 := 16#089f5cd0#;
22524    @b{pragma} Export (C, u00051, "system__string_hashB");
22525    u00052 : @b{constant} Version_32 := 16#3bbb9c15#;
22526    @b{pragma} Export (C, u00052, "system__string_hashS");
22527    u00053 : @b{constant} Version_32 := 16#807fe041#;
22528    @b{pragma} Export (C, u00053, "system__unsigned_typesS");
22529    u00054 : @b{constant} Version_32 := 16#d27be59e#;
22530    @b{pragma} Export (C, u00054, "system__val_lluB");
22531    u00055 : @b{constant} Version_32 := 16#fa8db733#;
22532    @b{pragma} Export (C, u00055, "system__val_lluS");
22533    u00056 : @b{constant} Version_32 := 16#27b600b2#;
22534    @b{pragma} Export (C, u00056, "system__val_utilB");
22535    u00057 : @b{constant} Version_32 := 16#b187f27f#;
22536    @b{pragma} Export (C, u00057, "system__val_utilS");
22537    u00058 : @b{constant} Version_32 := 16#d1060688#;
22538    @b{pragma} Export (C, u00058, "system__case_utilB");
22539    u00059 : @b{constant} Version_32 := 16#392e2d56#;
22540    @b{pragma} Export (C, u00059, "system__case_utilS");
22541    u00060 : @b{constant} Version_32 := 16#84a27f0d#;
22542    @b{pragma} Export (C, u00060, "interfaces__c_streamsB");
22543    u00061 : @b{constant} Version_32 := 16#8bb5f2c0#;
22544    @b{pragma} Export (C, u00061, "interfaces__c_streamsS");
22545    u00062 : @b{constant} Version_32 := 16#6db6928f#;
22546    @b{pragma} Export (C, u00062, "system__crtlS");
22547    u00063 : @b{constant} Version_32 := 16#4e6a342b#;
22548    @b{pragma} Export (C, u00063, "system__file_ioB");
22549    u00064 : @b{constant} Version_32 := 16#ba56a5e4#;
22550    @b{pragma} Export (C, u00064, "system__file_ioS");
22551    u00065 : @b{constant} Version_32 := 16#b7ab275c#;
22552    @b{pragma} Export (C, u00065, "ada__finalizationB");
22553    u00066 : @b{constant} Version_32 := 16#19f764ca#;
22554    @b{pragma} Export (C, u00066, "ada__finalizationS");
22555    u00067 : @b{constant} Version_32 := 16#95817ed8#;
22556    @b{pragma} Export (C, u00067, "system__finalization_rootB");
22557    u00068 : @b{constant} Version_32 := 16#52d53711#;
22558    @b{pragma} Export (C, u00068, "system__finalization_rootS");
22559    u00069 : @b{constant} Version_32 := 16#769e25e6#;
22560    @b{pragma} Export (C, u00069, "interfaces__cB");
22561    u00070 : @b{constant} Version_32 := 16#4a38bedb#;
22562    @b{pragma} Export (C, u00070, "interfaces__cS");
22563    u00071 : @b{constant} Version_32 := 16#07e6ee66#;
22564    @b{pragma} Export (C, u00071, "system__os_libB");
22565    u00072 : @b{constant} Version_32 := 16#d7b69782#;
22566    @b{pragma} Export (C, u00072, "system__os_libS");
22567    u00073 : @b{constant} Version_32 := 16#1a817b8e#;
22568    @b{pragma} Export (C, u00073, "system__stringsB");
22569    u00074 : @b{constant} Version_32 := 16#639855e7#;
22570    @b{pragma} Export (C, u00074, "system__stringsS");
22571    u00075 : @b{constant} Version_32 := 16#e0b8de29#;
22572    @b{pragma} Export (C, u00075, "system__file_control_blockS");
22573    u00076 : @b{constant} Version_32 := 16#b5b2aca1#;
22574    @b{pragma} Export (C, u00076, "system__finalization_mastersB");
22575    u00077 : @b{constant} Version_32 := 16#69316dc1#;
22576    @b{pragma} Export (C, u00077, "system__finalization_mastersS");
22577    u00078 : @b{constant} Version_32 := 16#57a37a42#;
22578    @b{pragma} Export (C, u00078, "system__address_imageB");
22579    u00079 : @b{constant} Version_32 := 16#bccbd9bb#;
22580    @b{pragma} Export (C, u00079, "system__address_imageS");
22581    u00080 : @b{constant} Version_32 := 16#7268f812#;
22582    @b{pragma} Export (C, u00080, "system__img_boolB");
22583    u00081 : @b{constant} Version_32 := 16#e8fe356a#;
22584    @b{pragma} Export (C, u00081, "system__img_boolS");
22585    u00082 : @b{constant} Version_32 := 16#d7aac20c#;
22586    @b{pragma} Export (C, u00082, "system__ioB");
22587    u00083 : @b{constant} Version_32 := 16#8365b3ce#;
22588    @b{pragma} Export (C, u00083, "system__ioS");
22589    u00084 : @b{constant} Version_32 := 16#6d4d969a#;
22590    @b{pragma} Export (C, u00084, "system__storage_poolsB");
22591    u00085 : @b{constant} Version_32 := 16#e87cc305#;
22592    @b{pragma} Export (C, u00085, "system__storage_poolsS");
22593    u00086 : @b{constant} Version_32 := 16#e34550ca#;
22594    @b{pragma} Export (C, u00086, "system__pool_globalB");
22595    u00087 : @b{constant} Version_32 := 16#c88d2d16#;
22596    @b{pragma} Export (C, u00087, "system__pool_globalS");
22597    u00088 : @b{constant} Version_32 := 16#9d39c675#;
22598    @b{pragma} Export (C, u00088, "system__memoryB");
22599    u00089 : @b{constant} Version_32 := 16#445a22b5#;
22600    @b{pragma} Export (C, u00089, "system__memoryS");
22601    u00090 : @b{constant} Version_32 := 16#6a859064#;
22602    @b{pragma} Export (C, u00090, "system__storage_pools__subpoolsB");
22603    u00091 : @b{constant} Version_32 := 16#e3b008dc#;
22604    @b{pragma} Export (C, u00091, "system__storage_pools__subpoolsS");
22605    u00092 : @b{constant} Version_32 := 16#63f11652#;
22606    @b{pragma} Export (C, u00092, "system__storage_pools__subpools__finalizationB");
22607    u00093 : @b{constant} Version_32 := 16#fe2f4b3a#;
22608    @b{pragma} Export (C, u00093, "system__storage_pools__subpools__finalizationS");
22610    --  BEGIN ELABORATION ORDER
22611    --  ada%s
22612    --  interfaces%s
22613    --  system%s
22614    --  system.case_util%s
22615    --  system.case_util%b
22616    --  system.htable%s
22617    --  system.img_bool%s
22618    --  system.img_bool%b
22619    --  system.img_int%s
22620    --  system.img_int%b
22621    --  system.io%s
22622    --  system.io%b
22623    --  system.parameters%s
22624    --  system.parameters%b
22625    --  system.crtl%s
22626    --  interfaces.c_streams%s
22627    --  interfaces.c_streams%b
22628    --  system.standard_library%s
22629    --  system.exceptions_debug%s
22630    --  system.exceptions_debug%b
22631    --  system.storage_elements%s
22632    --  system.storage_elements%b
22633    --  system.stack_checking%s
22634    --  system.stack_checking%b
22635    --  system.string_hash%s
22636    --  system.string_hash%b
22637    --  system.htable%b
22638    --  system.strings%s
22639    --  system.strings%b
22640    --  system.os_lib%s
22641    --  system.traceback_entries%s
22642    --  system.traceback_entries%b
22643    --  ada.exceptions%s
22644    --  system.soft_links%s
22645    --  system.unsigned_types%s
22646    --  system.val_llu%s
22647    --  system.val_util%s
22648    --  system.val_util%b
22649    --  system.val_llu%b
22650    --  system.wch_con%s
22651    --  system.wch_con%b
22652    --  system.wch_cnv%s
22653    --  system.wch_jis%s
22654    --  system.wch_jis%b
22655    --  system.wch_cnv%b
22656    --  system.wch_stw%s
22657    --  system.wch_stw%b
22658    --  ada.exceptions.last_chance_handler%s
22659    --  ada.exceptions.last_chance_handler%b
22660    --  system.address_image%s
22661    --  system.exception_table%s
22662    --  system.exception_table%b
22663    --  ada.io_exceptions%s
22664    --  ada.tags%s
22665    --  ada.streams%s
22666    --  ada.streams%b
22667    --  interfaces.c%s
22668    --  system.exceptions%s
22669    --  system.exceptions%b
22670    --  system.exceptions.machine%s
22671    --  system.finalization_root%s
22672    --  system.finalization_root%b
22673    --  ada.finalization%s
22674    --  ada.finalization%b
22675    --  system.storage_pools%s
22676    --  system.storage_pools%b
22677    --  system.finalization_masters%s
22678    --  system.storage_pools.subpools%s
22679    --  system.storage_pools.subpools.finalization%s
22680    --  system.storage_pools.subpools.finalization%b
22681    --  system.memory%s
22682    --  system.memory%b
22683    --  system.standard_library%b
22684    --  system.pool_global%s
22685    --  system.pool_global%b
22686    --  system.file_control_block%s
22687    --  system.file_io%s
22688    --  system.secondary_stack%s
22689    --  system.file_io%b
22690    --  system.storage_pools.subpools%b
22691    --  system.finalization_masters%b
22692    --  interfaces.c%b
22693    --  ada.tags%b
22694    --  system.soft_links%b
22695    --  system.os_lib%b
22696    --  system.secondary_stack%b
22697    --  system.address_image%b
22698    --  system.traceback%s
22699    --  ada.exceptions%b
22700    --  system.traceback%b
22701    --  ada.text_io%s
22702    --  ada.text_io%b
22703    --  hello%b
22704    --  END ELABORATION ORDER
22706 @b{end} ada_main;
22708 @b{pragma} Ada_95;
22709 --  The following source file name pragmas allow the generated file
22710 --  names to be unique for different main programs. They are needed
22711 --  since the package name will always be Ada_Main.
22713 @b{pragma} Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22714 @b{pragma} Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22716 @b{pragma} Suppress (Overflow_Check);
22717 @b{with} Ada.Exceptions;
22719 --  Generated package body for Ada_Main starts here
22721 @b{package} @b{body} ada_main @b{is}
22722    @b{pragma} Warnings (Off);
22724    --  These values are reference counter associated to units which have
22725    --  been elaborated. It is also used to avoid elaborating the
22726    --  same unit twice.
22728    E72 : Short_Integer; @b{pragma} Import (Ada, E72, "system__os_lib_E");
22729    E13 : Short_Integer; @b{pragma} Import (Ada, E13, "system__soft_links_E");
22730    E23 : Short_Integer; @b{pragma} Import (Ada, E23, "system__exception_table_E");
22731    E46 : Short_Integer; @b{pragma} Import (Ada, E46, "ada__io_exceptions_E");
22732    E48 : Short_Integer; @b{pragma} Import (Ada, E48, "ada__tags_E");
22733    E45 : Short_Integer; @b{pragma} Import (Ada, E45, "ada__streams_E");
22734    E70 : Short_Integer; @b{pragma} Import (Ada, E70, "interfaces__c_E");
22735    E25 : Short_Integer; @b{pragma} Import (Ada, E25, "system__exceptions_E");
22736    E68 : Short_Integer; @b{pragma} Import (Ada, E68, "system__finalization_root_E");
22737    E66 : Short_Integer; @b{pragma} Import (Ada, E66, "ada__finalization_E");
22738    E85 : Short_Integer; @b{pragma} Import (Ada, E85, "system__storage_pools_E");
22739    E77 : Short_Integer; @b{pragma} Import (Ada, E77, "system__finalization_masters_E");
22740    E91 : Short_Integer; @b{pragma} Import (Ada, E91, "system__storage_pools__subpools_E");
22741    E87 : Short_Integer; @b{pragma} Import (Ada, E87, "system__pool_global_E");
22742    E75 : Short_Integer; @b{pragma} Import (Ada, E75, "system__file_control_block_E");
22743    E64 : Short_Integer; @b{pragma} Import (Ada, E64, "system__file_io_E");
22744    E17 : Short_Integer; @b{pragma} Import (Ada, E17, "system__secondary_stack_E");
22745    E06 : Short_Integer; @b{pragma} Import (Ada, E06, "ada__text_io_E");
22747    Local_Priority_Specific_Dispatching : @b{constant} String := "";
22748    Local_Interrupt_States : @b{constant} String := "";
22750    Is_Elaborated : Boolean := False;
22752 @findex finalize_library
22753    @b{procedure} finalize_library @b{is}
22754    @b{begin}
22755       E06 := E06 - 1;
22756       @b{declare}
22757          @b{procedure} F1;
22758          @b{pragma} Import (Ada, F1, "ada__text_io__finalize_spec");
22759       @b{begin}
22760          F1;
22761       @b{end};
22762       E77 := E77 - 1;
22763       E91 := E91 - 1;
22764       @b{declare}
22765          @b{procedure} F2;
22766          @b{pragma} Import (Ada, F2, "system__file_io__finalize_body");
22767       @b{begin}
22768          E64 := E64 - 1;
22769          F2;
22770       @b{end};
22771       @b{declare}
22772          @b{procedure} F3;
22773          @b{pragma} Import (Ada, F3, "system__file_control_block__finalize_spec");
22774       @b{begin}
22775          E75 := E75 - 1;
22776          F3;
22777       @b{end};
22778       E87 := E87 - 1;
22779       @b{declare}
22780          @b{procedure} F4;
22781          @b{pragma} Import (Ada, F4, "system__pool_global__finalize_spec");
22782       @b{begin}
22783          F4;
22784       @b{end};
22785       @b{declare}
22786          @b{procedure} F5;
22787          @b{pragma} Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
22788       @b{begin}
22789          F5;
22790       @b{end};
22791       @b{declare}
22792          @b{procedure} F6;
22793          @b{pragma} Import (Ada, F6, "system__finalization_masters__finalize_spec");
22794       @b{begin}
22795          F6;
22796       @b{end};
22797       @b{declare}
22798          @b{procedure} Reraise_Library_Exception_If_Any;
22799          @b{pragma} Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
22800       @b{begin}
22801          Reraise_Library_Exception_If_Any;
22802       @b{end};
22803    @b{end} finalize_library;
22805    -------------
22806    -- adainit --
22807    -------------
22809 @findex adainit
22810    @b{procedure} adainit @b{is}
22812       Main_Priority : Integer;
22813       @b{pragma} Import (C, Main_Priority, "__gl_main_priority");
22814       Time_Slice_Value : Integer;
22815       @b{pragma} Import (C, Time_Slice_Value, "__gl_time_slice_val");
22816       WC_Encoding : Character;
22817       @b{pragma} Import (C, WC_Encoding, "__gl_wc_encoding");
22818       Locking_Policy : Character;
22819       pragma Import (C, Locking_Policy, "__gl_locking_policy");
22820       Queuing_Policy : Character;
22821       @b{pragma} Import (C, Queuing_Policy, "__gl_queuing_policy");
22822       Task_Dispatching_Policy : Character;
22823       @b{pragma} Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
22824       Priority_Specific_Dispatching : System.Address;
22825       @b{pragma} Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
22826       Num_Specific_Dispatching : Integer;
22827       @b{pragma} Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
22828       Main_CPU : Integer;
22829       @b{pragma} Import (C, Main_CPU, "__gl_main_cpu");
22830       Interrupt_States : System.Address;
22831       @b{pragma} Import (C, Interrupt_States, "__gl_interrupt_states");
22832       Num_Interrupt_States : Integer;
22833       @b{pragma} Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
22834       Unreserve_All_Interrupts : Integer;
22835       @b{pragma} Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
22836       Detect_Blocking : Integer;
22837       @b{pragma} Import (C, Detect_Blocking, "__gl_detect_blocking");
22838       Default_Stack_Size : Integer;
22839       @b{pragma} Import (C, Default_Stack_Size, "__gl_default_stack_size");
22840       Leap_Seconds_Support : Integer;
22841       @b{pragma} Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
22843       procedure Runtime_Initialize;
22844       @b{pragma} Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
22846       Finalize_Library_Objects : No_Param_Proc;
22847       @b{pragma} Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
22849    --  Start of processing for adainit
22851    @b{begin}
22853       --  Record various information for this partition.  The values
22854       --  are derived by the binder from information stored in the ali
22855       --  files by the compiler.
22857       @b{if} Is_Elaborated @b{then}
22858          @b{return};
22859       @b{end if};
22860       Is_Elaborated := True;
22861       Main_Priority := -1;
22862       Time_Slice_Value := -1;
22863       WC_Encoding := 'b';
22864       Locking_Policy := ' ';
22865       Queuing_Policy := ' ';
22866       Task_Dispatching_Policy := ' ';
22867       Priority_Specific_Dispatching :=
22868         Local_Priority_Specific_Dispatching'Address;
22869       Num_Specific_Dispatching := 0;
22870       Main_CPU := -1;
22871       Interrupt_States := Local_Interrupt_States'Address;
22872       Num_Interrupt_States := 0;
22873       Unreserve_All_Interrupts := 0;
22874       Detect_Blocking := 0;
22875       Default_Stack_Size := -1;
22876       Leap_Seconds_Support := 0;
22878       Runtime_Initialize;
22880       Finalize_Library_Objects := finalize_library'access;
22882       --  Now we have the elaboration calls for all units in the partition.
22883       --  The Elab_Spec and Elab_Body attributes generate references to the
22884       --  implicit elaboration procedures generated by the compiler for
22885       --  each unit that requires elaboration. Increment a counter of
22886       --  reference for each unit.
22888       System.Soft_Links'Elab_Spec;
22889       System.Exception_Table'Elab_Body;
22890       E23 := E23 + 1;
22891       Ada.Io_Exceptions'Elab_Spec;
22892       E46 := E46 + 1;
22893       Ada.Tags'Elab_Spec;
22894       Ada.Streams'Elab_Spec;
22895       E45 := E45 + 1;
22896       Interfaces.C'Elab_Spec;
22897       System.Exceptions'Elab_Spec;
22898       E25 := E25 + 1;
22899       System.Finalization_Root'Elab_Spec;
22900       E68 := E68 + 1;
22901       Ada.Finalization'Elab_Spec;
22902       E66 := E66 + 1;
22903       System.Storage_Pools'Elab_Spec;
22904       E85 := E85 + 1;
22905       System.Finalization_Masters'Elab_Spec;
22906       System.Storage_Pools.Subpools'Elab_Spec;
22907       System.Pool_Global'Elab_Spec;
22908       E87 := E87 + 1;
22909       System.File_Control_Block'Elab_Spec;
22910       E75 := E75 + 1;
22911       System.File_Io'Elab_Body;
22912       E64 := E64 + 1;
22913       E91 := E91 + 1;
22914       System.Finalization_Masters'Elab_Body;
22915       E77 := E77 + 1;
22916       E70 := E70 + 1;
22917       Ada.Tags'Elab_Body;
22918       E48 := E48 + 1;
22919       System.Soft_Links'Elab_Body;
22920       E13 := E13 + 1;
22921       System.Os_Lib'Elab_Body;
22922       E72 := E72 + 1;
22923       System.Secondary_Stack'Elab_Body;
22924       E17 := E17 + 1;
22925       Ada.Text_Io'Elab_Spec;
22926       Ada.Text_Io'Elab_Body;
22927       E06 := E06 + 1;
22928    @b{end} adainit;
22930    --------------
22931    -- adafinal --
22932    --------------
22934 @findex adafinal
22935    @b{procedure} adafinal @b{is}
22936       @b{procedure} s_stalib_adafinal;
22937       @b{pragma} Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
22939       @b{procedure} Runtime_Finalize;
22940       @b{pragma} Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
22942    @b{begin}
22943       @b{if not} Is_Elaborated @b{then}
22944          @b{return};
22945       @b{end if};
22946       Is_Elaborated := False;
22947       Runtime_Finalize;
22948       s_stalib_adafinal;
22949    @b{end} adafinal;
22951    --  We get to the main program of the partition by using
22952    --  pragma Import because if we try to with the unit and
22953    --  call it Ada style, then not only do we waste time
22954    --  recompiling it, but also, we don't really know the right
22955    --  switches (e.g.@: identifier character set) to be used
22956    --  to compile it.
22958    @b{procedure} Ada_Main_Program;
22959    @b{pragma} Import (Ada, Ada_Main_Program, "_ada_hello");
22961    ----------
22962    -- main --
22963    ----------
22965    --  main is actually a function, as in the ANSI C standard,
22966    --  defined to return the exit status. The three parameters
22967    --  are the argument count, argument values and environment
22968    --  pointer.
22970 @findex Main Program
22971    @b{function} main
22972      (argc : Integer;
22973       argv : System.Address;
22974       envp : System.Address)
22975       @b{return} Integer
22976    @b{is}
22977       --  The initialize routine performs low level system
22978       --  initialization using a standard library routine which
22979       --  sets up signal handling and performs any other
22980       --  required setup. The routine can be found in file
22981       --  a-init.c.
22983 @findex __gnat_initialize
22984       @b{procedure} initialize;
22985       @b{pragma} Import (C, initialize, "__gnat_initialize");
22987       --  The finalize routine performs low level system
22988       --  finalization using a standard library routine. The
22989       --  routine is found in file a-final.c and in the standard
22990       --  distribution is a dummy routine that does nothing, so
22991       --  really this is a hook for special user finalization.
22993 @findex __gnat_finalize
22994       @b{procedure} finalize;
22995       @b{pragma} Import (C, finalize, "__gnat_finalize");
22997       --  The following is to initialize the SEH exceptions
22999       SEH : @b{aliased array} (1 .. 2) of Integer;
23001       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
23002       @b{pragma} Volatile (Ensure_Reference);
23004    --  Start of processing for main
23006    @b{begin}
23007       --  Save global variables
23009       gnat_argc := argc;
23010       gnat_argv := argv;
23011       gnat_envp := envp;
23013       --  Call low level system initialization
23015       Initialize (SEH'Address);
23017       --  Call our generated Ada initialization routine
23019       adainit;
23021       --  Now we call the main program of the partition
23023       Ada_Main_Program;
23025       --  Perform Ada finalization
23027       adafinal;
23029       --  Perform low level system finalization
23031       Finalize;
23033       --  Return the proper exit status
23034       @b{return} (gnat_exit_status);
23035    @b{end};
23037 --  This section is entirely comments, so it has no effect on the
23038 --  compilation of the Ada_Main package. It provides the list of
23039 --  object files and linker options, as well as some standard
23040 --  libraries needed for the link. The gnatlink utility parses
23041 --  this b~hello.adb file to read these comment lines to generate
23042 --  the appropriate command line arguments for the call to the
23043 --  system linker. The BEGIN/END lines are used for sentinels for
23044 --  this parsing operation.
23046 --  The exact file names will of course depend on the environment,
23047 --  host/target and location of files on the host system.
23049 @findex Object file list
23050 -- BEGIN Object file/option list
23051    --   ./hello.o
23052    --   -L./
23053    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23054    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23055 -- END Object file/option list
23057 @b{end} ada_main;
23058 @end smallexample
23060 @noindent
23061 The Ada code in the above example is exactly what is generated by the
23062 binder. We have added comments to more clearly indicate the function
23063 of each part of the generated @code{Ada_Main} package.
23065 The code is standard Ada in all respects, and can be processed by any
23066 tools that handle Ada. In particular, it is possible to use the debugger
23067 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23068 suppose that for reasons that you do not understand, your program is crashing
23069 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23070 you can place a breakpoint on the call:
23072 @smallexample @c ada
23073 Ada.Text_Io'Elab_Body;
23074 @end smallexample
23076 @noindent
23077 and trace the elaboration routine for this package to find out where
23078 the problem might be (more usually of course you would be debugging
23079 elaboration code in your own application).
23081 @node Elaboration Order Handling in GNAT
23082 @appendix Elaboration Order Handling in GNAT
23083 @cindex Order of elaboration
23084 @cindex Elaboration control
23086 @menu
23087 * Elaboration Code::
23088 * Checking the Elaboration Order::
23089 * Controlling the Elaboration Order::
23090 * Controlling Elaboration in GNAT - Internal Calls::
23091 * Controlling Elaboration in GNAT - External Calls::
23092 * Default Behavior in GNAT - Ensuring Safety::
23093 * Treatment of Pragma Elaborate::
23094 * Elaboration Issues for Library Tasks::
23095 * Mixing Elaboration Models::
23096 * What to Do If the Default Elaboration Behavior Fails::
23097 * Elaboration for Indirect Calls::
23098 * Summary of Procedures for Elaboration Control::
23099 * Other Elaboration Order Considerations::
23100 * Determining the Chosen Elaboration Order::
23101 @end menu
23103 @noindent
23104 This chapter describes the handling of elaboration code in Ada and
23105 in GNAT, and discusses how the order of elaboration of program units can
23106 be controlled in GNAT, either automatically or with explicit programming
23107 features.
23109 @node Elaboration Code
23110 @section Elaboration Code
23112 @noindent
23113 Ada provides rather general mechanisms for executing code at elaboration
23114 time, that is to say before the main program starts executing. Such code arises
23115 in three contexts:
23117 @table @asis
23118 @item Initializers for variables.
23119 Variables declared at the library level, in package specs or bodies, can
23120 require initialization that is performed at elaboration time, as in:
23121 @smallexample @c ada
23122 @cartouche
23123 Sqrt_Half : Float := Sqrt (0.5);
23124 @end cartouche
23125 @end smallexample
23127 @item Package initialization code
23128 Code in a @code{BEGIN-END} section at the outer level of a package body is
23129 executed as part of the package body elaboration code.
23131 @item Library level task allocators
23132 Tasks that are declared using task allocators at the library level
23133 start executing immediately and hence can execute at elaboration time.
23134 @end table
23136 @noindent
23137 Subprogram calls are possible in any of these contexts, which means that
23138 any arbitrary part of the program may be executed as part of the elaboration
23139 code. It is even possible to write a program which does all its work at
23140 elaboration time, with a null main program, although stylistically this
23141 would usually be considered an inappropriate way to structure
23142 a program.
23144 An important concern arises in the context of elaboration code:
23145 we have to be sure that it is executed in an appropriate order. What we
23146 have is a series of elaboration code sections, potentially one section
23147 for each unit in the program. It is important that these execute
23148 in the correct order. Correctness here means that, taking the above
23149 example of the declaration of @code{Sqrt_Half},
23150 if some other piece of
23151 elaboration code references @code{Sqrt_Half},
23152 then it must run after the
23153 section of elaboration code that contains the declaration of
23154 @code{Sqrt_Half}.
23156 There would never be any order of elaboration problem if we made a rule
23157 that whenever you @code{with} a unit, you must elaborate both the spec and body
23158 of that unit before elaborating the unit doing the @code{with}'ing:
23160 @smallexample @c ada
23161 @group
23162 @cartouche
23163 @b{with} Unit_1;
23164 @b{package} Unit_2 @b{is} @dots{}
23165 @end cartouche
23166 @end group
23167 @end smallexample
23169 @noindent
23170 would require that both the body and spec of @code{Unit_1} be elaborated
23171 before the spec of @code{Unit_2}. However, a rule like that would be far too
23172 restrictive. In particular, it would make it impossible to have routines
23173 in separate packages that were mutually recursive.
23175 You might think that a clever enough compiler could look at the actual
23176 elaboration code and determine an appropriate correct order of elaboration,
23177 but in the general case, this is not possible. Consider the following
23178 example.
23180 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23181 that references
23182 the variable @code{Sqrt_1}, which is declared in the elaboration code
23183 of the body of @code{Unit_1}:
23185 @smallexample @c ada
23186 @cartouche
23187 Sqrt_1 : Float := Sqrt (0.1);
23188 @end cartouche
23189 @end smallexample
23191 @noindent
23192 The elaboration code of the body of @code{Unit_1} also contains:
23194 @smallexample @c ada
23195 @group
23196 @cartouche
23197 @b{if} expression_1 = 1 @b{then}
23198    Q := Unit_2.Func_2;
23199 @b{end} @b{if};
23200 @end cartouche
23201 @end group
23202 @end smallexample
23204 @noindent
23205 @code{Unit_2} is exactly parallel,
23206 it has a procedure @code{Func_2} that references
23207 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23208 the body @code{Unit_2}:
23210 @smallexample @c ada
23211 @cartouche
23212 Sqrt_2 : Float := Sqrt (0.1);
23213 @end cartouche
23214 @end smallexample
23216 @noindent
23217 The elaboration code of the body of @code{Unit_2} also contains:
23219 @smallexample @c ada
23220 @group
23221 @cartouche
23222 @b{if} expression_2 = 2 @b{then}
23223    Q := Unit_1.Func_1;
23224 @b{end} @b{if};
23225 @end cartouche
23226 @end group
23227 @end smallexample
23229 @noindent
23230 Now the question is, which of the following orders of elaboration is
23231 acceptable:
23233 @smallexample
23234 @group
23235 Spec of Unit_1
23236 Spec of Unit_2
23237 Body of Unit_1
23238 Body of Unit_2
23239 @end group
23240 @end smallexample
23242 @noindent
23245 @smallexample
23246 @group
23247 Spec of Unit_2
23248 Spec of Unit_1
23249 Body of Unit_2
23250 Body of Unit_1
23251 @end group
23252 @end smallexample
23254 @noindent
23255 If you carefully analyze the flow here, you will see that you cannot tell
23256 at compile time the answer to this question.
23257 If @code{expression_1} is not equal to 1,
23258 and @code{expression_2} is not equal to 2,
23259 then either order is acceptable, because neither of the function calls is
23260 executed. If both tests evaluate to true, then neither order is acceptable
23261 and in fact there is no correct order.
23263 If one of the two expressions is true, and the other is false, then one
23264 of the above orders is correct, and the other is incorrect. For example,
23265 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23266 then the call to @code{Func_1}
23267 will occur, but not the call to @code{Func_2.}
23268 This means that it is essential
23269 to elaborate the body of @code{Unit_1} before
23270 the body of @code{Unit_2}, so the first
23271 order of elaboration is correct and the second is wrong.
23273 By making @code{expression_1} and @code{expression_2}
23274 depend on input data, or perhaps
23275 the time of day, we can make it impossible for the compiler or binder
23276 to figure out which of these expressions will be true, and hence it
23277 is impossible to guarantee a safe order of elaboration at run time.
23279 @node Checking the Elaboration Order
23280 @section Checking the Elaboration Order
23282 @noindent
23283 In some languages that involve the same kind of elaboration problems,
23284 e.g.@: Java and C++, the programmer is expected to worry about these
23285 ordering problems himself, and it is common to
23286 write a program in which an incorrect elaboration order  gives
23287 surprising results, because it references variables before they
23288 are initialized.
23289 Ada is designed to be a safe language, and a programmer-beware approach is
23290 clearly not sufficient. Consequently, the language provides three lines
23291 of defense:
23293 @table @asis
23294 @item Standard rules
23295 Some standard rules restrict the possible choice of elaboration
23296 order. In particular, if you @code{with} a unit, then its spec is always
23297 elaborated before the unit doing the @code{with}. Similarly, a parent
23298 spec is always elaborated before the child spec, and finally
23299 a spec is always elaborated before its corresponding body.
23301 @item Dynamic elaboration checks
23302 @cindex Elaboration checks
23303 @cindex Checks, elaboration
23304 Dynamic checks are made at run time, so that if some entity is accessed
23305 before it is elaborated (typically  by means of a subprogram call)
23306 then the exception (@code{Program_Error}) is raised.
23308 @item Elaboration control
23309 Facilities are provided for the programmer to specify the desired order
23310 of elaboration.
23311 @end table
23313 Let's look at these facilities in more detail. First, the rules for
23314 dynamic checking. One possible rule would be simply to say that the
23315 exception is raised if you access a variable which has not yet been
23316 elaborated. The trouble with this approach is that it could require
23317 expensive checks on every variable reference. Instead Ada has two
23318 rules which are a little more restrictive, but easier to check, and
23319 easier to state:
23321 @table @asis
23322 @item Restrictions on calls
23323 A subprogram can only be called at elaboration time if its body
23324 has been elaborated. The rules for elaboration given above guarantee
23325 that the spec of the subprogram has been elaborated before the
23326 call, but not the body. If this rule is violated, then the
23327 exception @code{Program_Error} is raised.
23329 @item Restrictions on instantiations
23330 A generic unit can only be instantiated if the body of the generic
23331 unit has been elaborated. Again, the rules for elaboration given above
23332 guarantee that the spec of the generic unit has been elaborated
23333 before the instantiation, but not the body. If this rule is
23334 violated, then the exception @code{Program_Error} is raised.
23335 @end table
23337 @noindent
23338 The idea is that if the body has been elaborated, then any variables
23339 it references must have been elaborated; by checking for the body being
23340 elaborated we guarantee that none of its references causes any
23341 trouble. As we noted above, this is a little too restrictive, because a
23342 subprogram that has no non-local references in its body may in fact be safe
23343 to call. However, it really would be unsafe to rely on this, because
23344 it would mean that the caller was aware of details of the implementation
23345 in the body. This goes against the basic tenets of Ada.
23347 A plausible implementation can be described as follows.
23348 A Boolean variable is associated with each subprogram
23349 and each generic unit. This variable is initialized to False, and is set to
23350 True at the point body is elaborated. Every call or instantiation checks the
23351 variable, and raises @code{Program_Error} if the variable is False.
23353 Note that one might think that it would be good enough to have one Boolean
23354 variable for each package, but that would not deal with cases of trying
23355 to call a body in the same package as the call
23356 that has not been elaborated yet.
23357 Of course a compiler may be able to do enough analysis to optimize away
23358 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23359 does such optimizations, but still the easiest conceptual model is to
23360 think of there being one variable per subprogram.
23362 @node Controlling the Elaboration Order
23363 @section Controlling the Elaboration Order
23365 @noindent
23366 In the previous section we discussed the rules in Ada which ensure
23367 that @code{Program_Error} is raised if an incorrect elaboration order is
23368 chosen. This prevents erroneous executions, but we need mechanisms to
23369 specify a correct execution and avoid the exception altogether.
23370 To achieve this, Ada provides a number of features for controlling
23371 the order of elaboration. We discuss these features in this section.
23373 First, there are several ways of indicating to the compiler that a given
23374 unit has no elaboration problems:
23376 @table @asis
23377 @item packages that do not require a body
23378 A library package that does not require a body does not permit
23379 a body (this rule was introduced in Ada 95).
23380 Thus if we have a such a package, as in:
23382 @smallexample @c ada
23383 @group
23384 @cartouche
23385 @b{package} Definitions @b{is}
23386    @b{generic}
23387       @b{type} m @b{is} @b{new} integer;
23388    @b{package} Subp @b{is}
23389       @b{type} a @b{is} @b{array} (1 .. 10) @b{of} m;
23390       @b{type} b @b{is} @b{array} (1 .. 20) @b{of} m;
23391    @b{end} Subp;
23392 @b{end} Definitions;
23393 @end cartouche
23394 @end group
23395 @end smallexample
23397 @noindent
23398 A package that @code{with}'s @code{Definitions} may safely instantiate
23399 @code{Definitions.Subp} because the compiler can determine that there
23400 definitely is no package body to worry about in this case
23402 @item pragma Pure
23403 @cindex pragma Pure
23404 @findex Pure
23405 Places sufficient restrictions on a unit to guarantee that
23406 no call to any subprogram in the unit can result in an
23407 elaboration problem. This means that the compiler does not need
23408 to worry about the point of elaboration of such units, and in
23409 particular, does not need to check any calls to any subprograms
23410 in this unit.
23412 @item pragma Preelaborate
23413 @findex Preelaborate
23414 @cindex pragma Preelaborate
23415 This pragma places slightly less stringent restrictions on a unit than
23416 does pragma Pure,
23417 but these restrictions are still sufficient to ensure that there
23418 are no elaboration problems with any calls to the unit.
23420 @item pragma Elaborate_Body
23421 @findex Elaborate_Body
23422 @cindex pragma Elaborate_Body
23423 This pragma requires that the body of a unit be elaborated immediately
23424 after its spec. Suppose a unit @code{A} has such a pragma,
23425 and unit @code{B} does
23426 a @code{with} of unit @code{A}. Recall that the standard rules require
23427 the spec of unit @code{A}
23428 to be elaborated before the @code{with}'ing unit; given the pragma in
23429 @code{A}, we also know that the body of @code{A}
23430 will be elaborated before @code{B}, so
23431 that calls to @code{A} are safe and do not need a check.
23432 @end table
23434 @noindent
23435 Note that,
23436 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23437 the use of
23438 @code{Elaborate_Body} does not guarantee that the program is
23439 free of elaboration problems, because it may not be possible
23440 to satisfy the requested elaboration order.
23441 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23442 If a programmer
23443 marks @code{Unit_1} as @code{Elaborate_Body},
23444 and not @code{Unit_2,} then the order of
23445 elaboration will be:
23447 @smallexample
23448 @group
23449 Spec of Unit_2
23450 Spec of Unit_1
23451 Body of Unit_1
23452 Body of Unit_2
23453 @end group
23454 @end smallexample
23456 @noindent
23457 Now that means that the call to @code{Func_1} in @code{Unit_2}
23458 need not be checked,
23459 it must be safe. But the call to @code{Func_2} in
23460 @code{Unit_1} may still fail if
23461 @code{Expression_1} is equal to 1,
23462 and the programmer must still take
23463 responsibility for this not being the case.
23465 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23466 eliminated, except for calls entirely within a body, which are
23467 in any case fully under programmer control. However, using the pragma
23468 everywhere is not always possible.
23469 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23470 we marked both of them as having pragma @code{Elaborate_Body}, then
23471 clearly there would be no possible elaboration order.
23473 The above pragmas allow a server to guarantee safe use by clients, and
23474 clearly this is the preferable approach. Consequently a good rule
23475 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23476 and if this is not possible,
23477 mark them as @code{Elaborate_Body} if possible.
23478 As we have seen, there are situations where neither of these
23479 three pragmas can be used.
23480 So we also provide methods for clients to control the
23481 order of elaboration of the servers on which they depend:
23483 @table @asis
23484 @item pragma Elaborate (unit)
23485 @findex Elaborate
23486 @cindex pragma Elaborate
23487 This pragma is placed in the context clause, after a @code{with} clause,
23488 and it requires that the body of the named unit be elaborated before
23489 the unit in which the pragma occurs. The idea is to use this pragma
23490 if the current unit calls at elaboration time, directly or indirectly,
23491 some subprogram in the named unit.
23493 @item pragma Elaborate_All (unit)
23494 @findex Elaborate_All
23495 @cindex pragma Elaborate_All
23496 This is a stronger version of the Elaborate pragma. Consider the
23497 following example:
23499 @smallexample
23500 Unit A @code{with}'s unit B and calls B.Func in elab code
23501 Unit B @code{with}'s unit C, and B.Func calls C.Func
23502 @end smallexample
23504 @noindent
23505 Now if we put a pragma @code{Elaborate (B)}
23506 in unit @code{A}, this ensures that the
23507 body of @code{B} is elaborated before the call, but not the
23508 body of @code{C}, so
23509 the call to @code{C.Func} could still cause @code{Program_Error} to
23510 be raised.
23512 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23513 not only that the body of the named unit be elaborated before the
23514 unit doing the @code{with}, but also the bodies of all units that the
23515 named unit uses, following @code{with} links transitively. For example,
23516 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23517 then it requires
23518 not only that the body of @code{B} be elaborated before @code{A},
23519 but also the
23520 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23521 @end table
23523 @noindent
23524 We are now in a position to give a usage rule in Ada for avoiding
23525 elaboration problems, at least if dynamic dispatching and access to
23526 subprogram values are not used. We will handle these cases separately
23527 later.
23529 The rule is simple. If a unit has elaboration code that can directly or
23530 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23531 a generic package in a @code{with}'ed unit,
23532 then if the @code{with}'ed unit does not have
23533 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23534 a pragma @code{Elaborate_All}
23535 for the @code{with}'ed unit. By following this rule a client is
23536 assured that calls can be made without risk of an exception.
23538 For generic subprogram instantiations, the rule can be relaxed to
23539 require only a pragma @code{Elaborate} since elaborating the body
23540 of a subprogram cannot cause any transitive elaboration (we are
23541 not calling the subprogram in this case, just elaborating its
23542 declaration).
23544 If this rule is not followed, then a program may be in one of four
23545 states:
23547 @table @asis
23548 @item No order exists
23549 No order of elaboration exists which follows the rules, taking into
23550 account any @code{Elaborate}, @code{Elaborate_All},
23551 or @code{Elaborate_Body} pragmas. In
23552 this case, an Ada compiler must diagnose the situation at bind
23553 time, and refuse to build an executable program.
23555 @item One or more orders exist, all incorrect
23556 One or more acceptable elaboration orders exist, and all of them
23557 generate an elaboration order problem. In this case, the binder
23558 can build an executable program, but @code{Program_Error} will be raised
23559 when the program is run.
23561 @item Several orders exist, some right, some incorrect
23562 One or more acceptable elaboration orders exists, and some of them
23563 work, and some do not. The programmer has not controlled
23564 the order of elaboration, so the binder may or may not pick one of
23565 the correct orders, and the program may or may not raise an
23566 exception when it is run. This is the worst case, because it means
23567 that the program may fail when moved to another compiler, or even
23568 another version of the same compiler.
23570 @item One or more orders exists, all correct
23571 One ore more acceptable elaboration orders exist, and all of them
23572 work. In this case the program runs successfully. This state of
23573 affairs can be guaranteed by following the rule we gave above, but
23574 may be true even if the rule is not followed.
23575 @end table
23577 @noindent
23578 Note that one additional advantage of following our rules on the use
23579 of @code{Elaborate} and @code{Elaborate_All}
23580 is that the program continues to stay in the ideal (all orders OK) state
23581 even if maintenance
23582 changes some bodies of some units. Conversely, if a program that does
23583 not follow this rule happens to be safe at some point, this state of affairs
23584 may deteriorate silently as a result of maintenance changes.
23586 You may have noticed that the above discussion did not mention
23587 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23588 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23589 code in the body makes calls to some other unit, so it is still necessary
23590 to use @code{Elaborate_All} on such units.
23592 @node Controlling Elaboration in GNAT - Internal Calls
23593 @section Controlling Elaboration in GNAT - Internal Calls
23595 @noindent
23596 In the case of internal calls, i.e., calls within a single package, the
23597 programmer has full control over the order of elaboration, and it is up
23598 to the programmer to elaborate declarations in an appropriate order. For
23599 example writing:
23601 @smallexample @c ada
23602 @group
23603 @cartouche
23604 @b{function} One @b{return} Float;
23606 Q : Float := One;
23608 @b{function} One @b{return} Float @b{is}
23609 @b{begin}
23610      @b{return} 1.0;
23611 @b{end} One;
23612 @end cartouche
23613 @end group
23614 @end smallexample
23616 @noindent
23617 will obviously raise @code{Program_Error} at run time, because function
23618 One will be called before its body is elaborated. In this case GNAT will
23619 generate a warning that the call will raise @code{Program_Error}:
23621 @smallexample
23622 @group
23623 @cartouche
23624  1. procedure y is
23625  2.    function One return Float;
23626  3.
23627  4.    Q : Float := One;
23628                     |
23629     >>> warning: cannot call "One" before body is elaborated
23630     >>> warning: Program_Error will be raised at run time
23632  5.
23633  6.    function One return Float is
23634  7.    begin
23635  8.         return 1.0;
23636  9.    end One;
23638 11. begin
23639 12.    null;
23640 13. end;
23641 @end cartouche
23642 @end group
23643 @end smallexample
23645 @noindent
23646 Note that in this particular case, it is likely that the call is safe, because
23647 the function @code{One} does not access any global variables.
23648 Nevertheless in Ada, we do not want the validity of the check to depend on
23649 the contents of the body (think about the separate compilation case), so this
23650 is still wrong, as we discussed in the previous sections.
23652 The error is easily corrected by rearranging the declarations so that the
23653 body of @code{One} appears before the declaration containing the call
23654 (note that in Ada 95 and Ada 2005,
23655 declarations can appear in any order, so there is no restriction that
23656 would prevent this reordering, and if we write:
23658 @smallexample @c ada
23659 @group
23660 @cartouche
23661 @b{function} One @b{return} Float;
23663 @b{function} One @b{return} Float @b{is}
23664 @b{begin}
23665      @b{return} 1.0;
23666 @b{end} One;
23668 Q : Float := One;
23669 @end cartouche
23670 @end group
23671 @end smallexample
23673 @noindent
23674 then all is well, no warning is generated, and no
23675 @code{Program_Error} exception
23676 will be raised.
23677 Things are more complicated when a chain of subprograms is executed:
23679 @smallexample @c ada
23680 @group
23681 @cartouche
23682 @b{function} A @b{return} Integer;
23683 @b{function} B @b{return} Integer;
23684 @b{function} C @b{return} Integer;
23686 @b{function} B @b{return} Integer @b{is} @b{begin} @b{return} A; @b{end};
23687 @b{function} C @b{return} Integer @b{is} @b{begin} @b{return} B; @b{end};
23689 X : Integer := C;
23691 @b{function} A @b{return} Integer @b{is} @b{begin} @b{return} 1; @b{end};
23692 @end cartouche
23693 @end group
23694 @end smallexample
23696 @noindent
23697 Now the call to @code{C}
23698 at elaboration time in the declaration of @code{X} is correct, because
23699 the body of @code{C} is already elaborated,
23700 and the call to @code{B} within the body of
23701 @code{C} is correct, but the call
23702 to @code{A} within the body of @code{B} is incorrect, because the body
23703 of @code{A} has not been elaborated, so @code{Program_Error}
23704 will be raised on the call to @code{A}.
23705 In this case GNAT will generate a
23706 warning that @code{Program_Error} may be
23707 raised at the point of the call. Let's look at the warning:
23709 @smallexample
23710 @group
23711 @cartouche
23712  1. procedure x is
23713  2.    function A return Integer;
23714  3.    function B return Integer;
23715  4.    function C return Integer;
23716  5.
23717  6.    function B return Integer is begin return A; end;
23718                                                     |
23719     >>> warning: call to "A" before body is elaborated may
23720                  raise Program_Error
23721     >>> warning: "B" called at line 7
23722     >>> warning: "C" called at line 9
23724  7.    function C return Integer is begin return B; end;
23725  8.
23726  9.    X : Integer := C;
23728 11.    function A return Integer is begin return 1; end;
23730 13. begin
23731 14.    null;
23732 15. end;
23733 @end cartouche
23734 @end group
23735 @end smallexample
23737 @noindent
23738 Note that the message here says ``may raise'', instead of the direct case,
23739 where the message says ``will be raised''. That's because whether
23740 @code{A} is
23741 actually called depends in general on run-time flow of control.
23742 For example, if the body of @code{B} said
23744 @smallexample @c ada
23745 @group
23746 @cartouche
23747 @b{function} B @b{return} Integer @b{is}
23748 @b{begin}
23749    @b{if} some-condition-depending-on-input-data @b{then}
23750       @b{return} A;
23751    @b{else}
23752       @b{return} 1;
23753    @b{end} @b{if};
23754 @b{end} B;
23755 @end cartouche
23756 @end group
23757 @end smallexample
23759 @noindent
23760 then we could not know until run time whether the incorrect call to A would
23761 actually occur, so @code{Program_Error} might
23762 or might not be raised. It is possible for a compiler to
23763 do a better job of analyzing bodies, to
23764 determine whether or not @code{Program_Error}
23765 might be raised, but it certainly
23766 couldn't do a perfect job (that would require solving the halting problem
23767 and is provably impossible), and because this is a warning anyway, it does
23768 not seem worth the effort to do the analysis. Cases in which it
23769 would be relevant are rare.
23771 In practice, warnings of either of the forms given
23772 above will usually correspond to
23773 real errors, and should be examined carefully and eliminated.
23774 In the rare case where a warning is bogus, it can be suppressed by any of
23775 the following methods:
23777 @itemize @bullet
23778 @item
23779 Compile with the @option{-gnatws} switch set
23781 @item
23782 Suppress @code{Elaboration_Check} for the called subprogram
23784 @item
23785 Use pragma @code{Warnings_Off} to turn warnings off for the call
23786 @end itemize
23788 @noindent
23789 For the internal elaboration check case,
23790 GNAT by default generates the
23791 necessary run-time checks to ensure
23792 that @code{Program_Error} is raised if any
23793 call fails an elaboration check. Of course this can only happen if a
23794 warning has been issued as described above. The use of pragma
23795 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23796 some of these checks, meaning that it may be possible (but is not
23797 guaranteed) for a program to be able to call a subprogram whose body
23798 is not yet elaborated, without raising a @code{Program_Error} exception.
23800 @node Controlling Elaboration in GNAT - External Calls
23801 @section Controlling Elaboration in GNAT - External Calls
23803 @noindent
23804 The previous section discussed the case in which the execution of a
23805 particular thread of elaboration code occurred entirely within a
23806 single unit. This is the easy case to handle, because a programmer
23807 has direct and total control over the order of elaboration, and
23808 furthermore, checks need only be generated in cases which are rare
23809 and which the compiler can easily detect.
23810 The situation is more complex when separate compilation is taken into account.
23811 Consider the following:
23813 @smallexample @c ada
23814 @cartouche
23815 @group
23816 @b{package} Math @b{is}
23817    @b{function} Sqrt (Arg : Float) @b{return} Float;
23818 @b{end} Math;
23820 @b{package} @b{body} Math @b{is}
23821    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
23822    @b{begin}
23823          @dots{}
23824    @b{end} Sqrt;
23825 @b{end} Math;
23826 @end group
23827 @group
23828 @b{with} Math;
23829 @b{package} Stuff @b{is}
23830    X : Float := Math.Sqrt (0.5);
23831 @b{end} Stuff;
23833 @b{with} Stuff;
23834 @b{procedure} Main @b{is}
23835 @b{begin}
23836    @dots{}
23837 @b{end} Main;
23838 @end group
23839 @end cartouche
23840 @end smallexample
23842 @noindent
23843 where @code{Main} is the main program. When this program is executed, the
23844 elaboration code must first be executed, and one of the jobs of the
23845 binder is to determine the order in which the units of a program are
23846 to be elaborated. In this case we have four units: the spec and body
23847 of @code{Math},
23848 the spec of @code{Stuff} and the body of @code{Main}).
23849 In what order should the four separate sections of elaboration code
23850 be executed?
23852 There are some restrictions in the order of elaboration that the binder
23853 can choose. In particular, if unit U has a @code{with}
23854 for a package @code{X}, then you
23855 are assured that the spec of @code{X}
23856 is elaborated before U , but you are
23857 not assured that the body of @code{X}
23858 is elaborated before U.
23859 This means that in the above case, the binder is allowed to choose the
23860 order:
23862 @smallexample
23863 spec of Math
23864 spec of Stuff
23865 body of Math
23866 body of Main
23867 @end smallexample
23869 @noindent
23870 but that's not good, because now the call to @code{Math.Sqrt}
23871 that happens during
23872 the elaboration of the @code{Stuff}
23873 spec happens before the body of @code{Math.Sqrt} is
23874 elaborated, and hence causes @code{Program_Error} exception to be raised.
23875 At first glance, one might say that the binder is misbehaving, because
23876 obviously you want to elaborate the body of something you @code{with}
23877 first, but
23878 that is not a general rule that can be followed in all cases. Consider
23880 @smallexample @c ada
23881 @group
23882 @cartouche
23883 @b{package} X @b{is} @dots{}
23885 @b{package} Y @b{is} @dots{}
23887 @b{with} X;
23888 @b{package} @b{body} Y @b{is} @dots{}
23890 @b{with} Y;
23891 @b{package} @b{body} X @b{is} @dots{}
23892 @end cartouche
23893 @end group
23894 @end smallexample
23896 @noindent
23897 This is a common arrangement, and, apart from the order of elaboration
23898 problems that might arise in connection with elaboration code, this works fine.
23899 A rule that says that you must first elaborate the body of anything you
23900 @code{with} cannot work in this case:
23901 the body of @code{X} @code{with}'s @code{Y},
23902 which means you would have to
23903 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23904 which means
23905 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23906 loop that cannot be broken.
23908 It is true that the binder can in many cases guess an order of elaboration
23909 that is unlikely to cause a @code{Program_Error}
23910 exception to be raised, and it tries to do so (in the
23911 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23912 by default
23913 elaborate the body of @code{Math} right after its spec, so all will be well).
23915 However, a program that blindly relies on the binder to be helpful can
23916 get into trouble, as we discussed in the previous sections, so
23917 GNAT
23918 provides a number of facilities for assisting the programmer in
23919 developing programs that are robust with respect to elaboration order.
23921 @node Default Behavior in GNAT - Ensuring Safety
23922 @section Default Behavior in GNAT - Ensuring Safety
23924 @noindent
23925 The default behavior in GNAT ensures elaboration safety. In its
23926 default mode GNAT implements the
23927 rule we previously described as the right approach. Let's restate it:
23929 @itemize
23930 @item
23931 @emph{If a unit has elaboration code that can directly or indirectly make a
23932 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23933 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23934 does not have pragma @code{Pure} or
23935 @code{Preelaborate}, then the client should have an
23936 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23938 @emph{In the case of instantiating a generic subprogram, it is always
23939 sufficient to have only an @code{Elaborate} pragma for the
23940 @code{with}'ed unit.}
23941 @end itemize
23943 @noindent
23944 By following this rule a client is assured that calls and instantiations
23945 can be made without risk of an exception.
23947 In this mode GNAT traces all calls that are potentially made from
23948 elaboration code, and puts in any missing implicit @code{Elaborate}
23949 and @code{Elaborate_All} pragmas.
23950 The advantage of this approach is that no elaboration problems
23951 are possible if the binder can find an elaboration order that is
23952 consistent with these implicit @code{Elaborate} and
23953 @code{Elaborate_All} pragmas. The
23954 disadvantage of this approach is that no such order may exist.
23956 If the binder does not generate any diagnostics, then it means that it has
23957 found an elaboration order that is guaranteed to be safe. However, the binder
23958 may still be relying on implicitly generated @code{Elaborate} and
23959 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23960 guaranteed.
23962 If it is important to guarantee portability, then the compilations should
23963 use the
23964 @option{-gnatel}
23965 (info messages for elaboration prag mas) switch. This will cause info messages
23966 to be generated indicating the missing @code{Elaborate} and
23967 @code{Elaborate_All} pragmas.
23968 Consider the following source program:
23970 @smallexample @c ada
23971 @group
23972 @cartouche
23973 @b{with} k;
23974 @b{package} j @b{is}
23975   m : integer := k.r;
23976 @b{end};
23977 @end cartouche
23978 @end group
23979 @end smallexample
23981 @noindent
23982 where it is clear that there
23983 should be a pragma @code{Elaborate_All}
23984 for unit @code{k}. An implicit pragma will be generated, and it is
23985 likely that the binder will be able to honor it. However, if you want
23986 to port this program to some other Ada compiler than GNAT.
23987 it is safer to include the pragma explicitly in the source. If this
23988 unit is compiled with the
23989 @option{-gnatel}
23990 switch, then the compiler outputs an information message:
23992 @smallexample
23993 @group
23994 @cartouche
23995 1. with k;
23996 2. package j is
23997 3.   m : integer := k.r;
23998                      |
23999    >>> info: call to "r" may raise Program_Error
24000    >>> info: missing pragma Elaborate_All for "k"
24002 4. end;
24003 @end cartouche
24004 @end group
24005 @end smallexample
24007 @noindent
24008 and these messages can be used as a guide for supplying manually
24009 the missing pragmas. It is usually a bad idea to use this
24010 option during development. That's because it will tell you when
24011 you need to put in a pragma, but cannot tell you when it is time
24012 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24013 unnecessary dependencies and even false circularities.
24015 This default mode is more restrictive than the Ada Reference
24016 Manual, and it is possible to construct programs which will compile
24017 using the dynamic model described there, but will run into a
24018 circularity using the safer static model we have described.
24020 Of course any Ada compiler must be able to operate in a mode
24021 consistent with the requirements of the Ada Reference Manual,
24022 and in particular must have the capability of implementing the
24023 standard dynamic model of elaboration with run-time checks.
24025 In GNAT, this standard mode can be achieved either by the use of
24026 the @option{-gnatE} switch on the compiler (@command{gcc} or
24027 @command{gnatmake}) command, or by the use of the configuration pragma:
24029 @smallexample @c ada
24030 @b{pragma} Elaboration_Checks (DYNAMIC);
24031 @end smallexample
24033 @noindent
24034 Either approach will cause the unit affected to be compiled using the
24035 standard dynamic run-time elaboration checks described in the Ada
24036 Reference Manual. The static model is generally preferable, since it
24037 is clearly safer to rely on compile and link time checks rather than
24038 run-time checks. However, in the case of legacy code, it may be
24039 difficult to meet the requirements of the static model. This
24040 issue is further discussed in
24041 @ref{What to Do If the Default Elaboration Behavior Fails}.
24043 Note that the static model provides a strict subset of the allowed
24044 behavior and programs of the Ada Reference Manual, so if you do
24045 adhere to the static model and no circularities exist,
24046 then you are assured that your program will
24047 work using the dynamic model, providing that you remove any
24048 pragma Elaborate statements from the source.
24050 @node Treatment of Pragma Elaborate
24051 @section Treatment of Pragma Elaborate
24052 @cindex Pragma Elaborate
24054 @noindent
24055 The use of @code{pragma Elaborate}
24056 should generally be avoided in Ada 95 and Ada 2005 programs,
24057 since there is no guarantee that transitive calls
24058 will be properly handled. Indeed at one point, this pragma was placed
24059 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24061 Now that's a bit restrictive. In practice, the case in which
24062 @code{pragma Elaborate} is useful is when the caller knows that there
24063 are no transitive calls, or that the called unit contains all necessary
24064 transitive @code{pragma Elaborate} statements, and legacy code often
24065 contains such uses.
24067 Strictly speaking the static mode in GNAT should ignore such pragmas,
24068 since there is no assurance at compile time that the necessary safety
24069 conditions are met. In practice, this would cause GNAT to be incompatible
24070 with correctly written Ada 83 code that had all necessary
24071 @code{pragma Elaborate} statements in place. Consequently, we made the
24072 decision that GNAT in its default mode will believe that if it encounters
24073 a @code{pragma Elaborate} then the programmer knows what they are doing,
24074 and it will trust that no elaboration errors can occur.
24076 The result of this decision is two-fold. First to be safe using the
24077 static mode, you should remove all @code{pragma Elaborate} statements.
24078 Second, when fixing circularities in existing code, you can selectively
24079 use @code{pragma Elaborate} statements to convince the static mode of
24080 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24081 statement.
24083 When using the static mode with @option{-gnatwl}, any use of
24084 @code{pragma Elaborate} will generate a warning about possible
24085 problems.
24087 @node Elaboration Issues for Library Tasks
24088 @section Elaboration Issues for Library Tasks
24089 @cindex Library tasks, elaboration issues
24090 @cindex Elaboration of library tasks
24092 @noindent
24093 In this section we examine special elaboration issues that arise for
24094 programs that declare library level tasks.
24096 Generally the model of execution of an Ada program is that all units are
24097 elaborated, and then execution of the program starts. However, the
24098 declaration of library tasks definitely does not fit this model. The
24099 reason for this is that library tasks start as soon as they are declared
24100 (more precisely, as soon as the statement part of the enclosing package
24101 body is reached), that is to say before elaboration
24102 of the program is complete. This means that if such a task calls a
24103 subprogram, or an entry in another task, the callee may or may not be
24104 elaborated yet, and in the standard
24105 Reference Manual model of dynamic elaboration checks, you can even
24106 get timing dependent Program_Error exceptions, since there can be
24107 a race between the elaboration code and the task code.
24109 The static model of elaboration in GNAT seeks to avoid all such
24110 dynamic behavior, by being conservative, and the conservative
24111 approach in this particular case is to assume that all the code
24112 in a task body is potentially executed at elaboration time if
24113 a task is declared at the library level.
24115 This can definitely result in unexpected circularities. Consider
24116 the following example
24118 @smallexample @c ada
24119 @b{package} Decls @b{is}
24120   @b{task} Lib_Task @b{is}
24121      @b{entry} Start;
24122   @b{end} Lib_Task;
24124   @b{type} My_Int @b{is} @b{new} Integer;
24126   @b{function} Ident (M : My_Int) @b{return} My_Int;
24127 @b{end} Decls;
24129 @b{with} Utils;
24130 @b{package} @b{body} Decls @b{is}
24131   @b{task} @b{body} Lib_Task @b{is}
24132   @b{begin}
24133      @b{accept} Start;
24134      Utils.Put_Val (2);
24135   @b{end} Lib_Task;
24137   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24138   @b{begin}
24139      @b{return} M;
24140   @b{end} Ident;
24141 @b{end} Decls;
24143 @b{with} Decls;
24144 @b{package} Utils @b{is}
24145   @b{procedure} Put_Val (Arg : Decls.My_Int);
24146 @b{end} Utils;
24148 @b{with} Text_IO;
24149 @b{package} @b{body} Utils @b{is}
24150   @b{procedure} Put_Val (Arg : Decls.My_Int) @b{is}
24151   @b{begin}
24152      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24153   @b{end} Put_Val;
24154 @b{end} Utils;
24156 @b{with} Decls;
24157 @b{procedure} Main @b{is}
24158 @b{begin}
24159    Decls.Lib_Task.Start;
24160 @b{end};
24161 @end smallexample
24163 @noindent
24164 If the above example is compiled in the default static elaboration
24165 mode, then a circularity occurs. The circularity comes from the call
24166 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24167 this call occurs in elaboration code, we need an implicit pragma
24168 @code{Elaborate_All} for @code{Utils}. This means that not only must
24169 the spec and body of @code{Utils} be elaborated before the body
24170 of @code{Decls}, but also the spec and body of any unit that is
24171 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24172 the body of @code{Decls}. This is the transitive implication of
24173 pragma @code{Elaborate_All} and it makes sense, because in general
24174 the body of @code{Put_Val} might have a call to something in a
24175 @code{with'ed} unit.
24177 In this case, the body of Utils (actually its spec) @code{with's}
24178 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24179 must be elaborated before itself, in case there is a call from the
24180 body of @code{Utils}.
24182 Here is the exact chain of events we are worrying about:
24184 @enumerate
24185 @item
24186 In the body of @code{Decls} a call is made from within the body of a library
24187 task to a subprogram in the package @code{Utils}. Since this call may
24188 occur at elaboration time (given that the task is activated at elaboration
24189 time), we have to assume the worst, i.e., that the
24190 call does happen at elaboration time.
24192 @item
24193 This means that the body and spec of @code{Util} must be elaborated before
24194 the body of @code{Decls} so that this call does not cause an access before
24195 elaboration.
24197 @item
24198 Within the body of @code{Util}, specifically within the body of
24199 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24200 by this package.
24202 @item
24203 One such @code{with}'ed package is package @code{Decls}, so there
24204 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24205 In fact there is such a call in this example, but we would have to
24206 assume that there was such a call even if it were not there, since
24207 we are not supposed to write the body of @code{Decls} knowing what
24208 is in the body of @code{Utils}; certainly in the case of the
24209 static elaboration model, the compiler does not know what is in
24210 other bodies and must assume the worst.
24212 @item
24213 This means that the spec and body of @code{Decls} must also be
24214 elaborated before we elaborate the unit containing the call, but
24215 that unit is @code{Decls}! This means that the body of @code{Decls}
24216 must be elaborated before itself, and that's a circularity.
24217 @end enumerate
24219 @noindent
24220 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24221 the body of @code{Decls} you will get a true Ada Reference Manual
24222 circularity that makes the program illegal.
24224 In practice, we have found that problems with the static model of
24225 elaboration in existing code often arise from library tasks, so
24226 we must address this particular situation.
24228 Note that if we compile and run the program above, using the dynamic model of
24229 elaboration (that is to say use the @option{-gnatE} switch),
24230 then it compiles, binds,
24231 links, and runs, printing the expected result of 2. Therefore in some sense
24232 the circularity here is only apparent, and we need to capture
24233 the properties of this program that  distinguish it from other library-level
24234 tasks that have real elaboration problems.
24236 We have four possible answers to this question:
24238 @itemize @bullet
24240 @item
24241 Use the dynamic model of elaboration.
24243 If we use the @option{-gnatE} switch, then as noted above, the program works.
24244 Why is this? If we examine the task body, it is apparent that the task cannot
24245 proceed past the
24246 @code{accept} statement until after elaboration has been completed, because
24247 the corresponding entry call comes from the main program, not earlier.
24248 This is why the dynamic model works here. But that's really giving
24249 up on a precise analysis, and we prefer to take this approach only if we cannot
24250 solve the
24251 problem in any other manner. So let us examine two ways to reorganize
24252 the program to avoid the potential elaboration problem.
24254 @item
24255 Split library tasks into separate packages.
24257 Write separate packages, so that library tasks are isolated from
24258 other declarations as much as possible. Let us look at a variation on
24259 the above program.
24261 @smallexample @c ada
24262 @b{package} Decls1 @b{is}
24263   @b{task} Lib_Task @b{is}
24264      @b{entry} Start;
24265   @b{end} Lib_Task;
24266 @b{end} Decls1;
24268 @b{with} Utils;
24269 @b{package} @b{body} Decls1 @b{is}
24270   @b{task} @b{body} Lib_Task @b{is}
24271   @b{begin}
24272      @b{accept} Start;
24273      Utils.Put_Val (2);
24274   @b{end} Lib_Task;
24275 @b{end} Decls1;
24277 @b{package} Decls2 @b{is}
24278   @b{type} My_Int @b{is} @b{new} Integer;
24279   @b{function} Ident (M : My_Int) @b{return} My_Int;
24280 @b{end} Decls2;
24282 @b{with} Utils;
24283 @b{package} @b{body} Decls2 @b{is}
24284   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24285   @b{begin}
24286      @b{return} M;
24287   @b{end} Ident;
24288 @b{end} Decls2;
24290 @b{with} Decls2;
24291 @b{package} Utils @b{is}
24292   @b{procedure} Put_Val (Arg : Decls2.My_Int);
24293 @b{end} Utils;
24295 @b{with} Text_IO;
24296 @b{package} @b{body} Utils @b{is}
24297   @b{procedure} Put_Val (Arg : Decls2.My_Int) @b{is}
24298   @b{begin}
24299      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24300   @b{end} Put_Val;
24301 @b{end} Utils;
24303 @b{with} Decls1;
24304 @b{procedure} Main @b{is}
24305 @b{begin}
24306    Decls1.Lib_Task.Start;
24307 @b{end};
24308 @end smallexample
24310 @noindent
24311 All we have done is to split @code{Decls} into two packages, one
24312 containing the library task, and one containing everything else. Now
24313 there is no cycle, and the program compiles, binds, links and executes
24314 using the default static model of elaboration.
24316 @item
24317 Declare separate task types.
24319 A significant part of the problem arises because of the use of the
24320 single task declaration form. This means that the elaboration of
24321 the task type, and the elaboration of the task itself (i.e.@: the
24322 creation of the task) happen at the same time. A good rule
24323 of style in Ada is to always create explicit task types. By
24324 following the additional step of placing task objects in separate
24325 packages from the task type declaration, many elaboration problems
24326 are avoided. Here is another modified example of the example program:
24328 @smallexample @c ada
24329 @b{package} Decls @b{is}
24330   @b{task} @b{type} Lib_Task_Type @b{is}
24331      @b{entry} Start;
24332   @b{end} Lib_Task_Type;
24334   @b{type} My_Int @b{is} @b{new} Integer;
24336   @b{function} Ident (M : My_Int) @b{return} My_Int;
24337 @b{end} Decls;
24339 @b{with} Utils;
24340 @b{package} @b{body} Decls @b{is}
24341   @b{task} @b{body} Lib_Task_Type @b{is}
24342   @b{begin}
24343      @b{accept} Start;
24344      Utils.Put_Val (2);
24345   @b{end} Lib_Task_Type;
24347   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24348   @b{begin}
24349      @b{return} M;
24350   @b{end} Ident;
24351 @b{end} Decls;
24353 @b{with} Decls;
24354 @b{package} Utils @b{is}
24355   @b{procedure} Put_Val (Arg : Decls.My_Int);
24356 @b{end} Utils;
24358 @b{with} Text_IO;
24359 @b{package} @b{body} Utils @b{is}
24360   @b{procedure} Put_Val (Arg : Decls.My_Int) @b{is}
24361   @b{begin}
24362      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24363   @b{end} Put_Val;
24364 @b{end} Utils;
24366 @b{with} Decls;
24367 @b{package} Declst @b{is}
24368    Lib_Task : Decls.Lib_Task_Type;
24369 @b{end} Declst;
24371 @b{with} Declst;
24372 @b{procedure} Main @b{is}
24373 @b{begin}
24374    Declst.Lib_Task.Start;
24375 @b{end};
24376 @end smallexample
24378 @noindent
24379 What we have done here is to replace the @code{task} declaration in
24380 package @code{Decls} with a @code{task type} declaration. Then we
24381 introduce a separate package @code{Declst} to contain the actual
24382 task object. This separates the elaboration issues for
24383 the @code{task type}
24384 declaration, which causes no trouble, from the elaboration issues
24385 of the task object, which is also unproblematic, since it is now independent
24386 of the elaboration of  @code{Utils}.
24387 This separation of concerns also corresponds to
24388 a generally sound engineering principle of separating declarations
24389 from instances. This version of the program also compiles, binds, links,
24390 and executes, generating the expected output.
24392 @item
24393 Use No_Entry_Calls_In_Elaboration_Code restriction.
24394 @cindex No_Entry_Calls_In_Elaboration_Code
24396 The previous two approaches described how a program can be restructured
24397 to avoid the special problems caused by library task bodies. in practice,
24398 however, such restructuring may be difficult to apply to existing legacy code,
24399 so we must consider solutions that do not require massive rewriting.
24401 Let us consider more carefully why our original sample program works
24402 under the dynamic model of elaboration. The reason is that the code
24403 in the task body blocks immediately on the @code{accept}
24404 statement. Now of course there is nothing to prohibit elaboration
24405 code from making entry calls (for example from another library level task),
24406 so we cannot tell in isolation that
24407 the task will not execute the accept statement  during elaboration.
24409 However, in practice it is very unusual to see elaboration code
24410 make any entry calls, and the pattern of tasks starting
24411 at elaboration time and then immediately blocking on @code{accept} or
24412 @code{select} statements is very common. What this means is that
24413 the compiler is being too pessimistic when it analyzes the
24414 whole package body as though it might be executed at elaboration
24415 time.
24417 If we know that the elaboration code contains no entry calls, (a very safe
24418 assumption most of the time, that could almost be made the default
24419 behavior), then we can compile all units of the program under control
24420 of the following configuration pragma:
24422 @smallexample
24423 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24424 @end smallexample
24426 @noindent
24427 This pragma can be placed in the @file{gnat.adc} file in the usual
24428 manner. If we take our original unmodified program and compile it
24429 in the presence of a @file{gnat.adc} containing the above pragma,
24430 then once again, we can compile, bind, link, and execute, obtaining
24431 the expected result. In the presence of this pragma, the compiler does
24432 not trace calls in a task body, that appear after the first @code{accept}
24433 or @code{select} statement, and therefore does not report a potential
24434 circularity in the original program.
24436 The compiler will check to the extent it can that the above
24437 restriction is not violated, but it is not always possible to do a
24438 complete check at compile time, so it is important to use this
24439 pragma only if the stated restriction is in fact met, that is to say
24440 no task receives an entry call before elaboration of all units is completed.
24442 @end itemize
24444 @node Mixing Elaboration Models
24445 @section Mixing Elaboration Models
24446 @noindent
24447 So far, we have assumed that the entire program is either compiled
24448 using the dynamic model or static model, ensuring consistency. It
24449 is possible to mix the two models, but rules have to be followed
24450 if this mixing is done to ensure that elaboration checks are not
24451 omitted.
24453 The basic rule is that @emph{a unit compiled with the static model cannot
24454 be @code{with'ed} by a unit compiled with the dynamic model}. The
24455 reason for this is that in the static model, a unit assumes that
24456 its clients guarantee to use (the equivalent of) pragma
24457 @code{Elaborate_All} so that no elaboration checks are required
24458 in inner subprograms, and this assumption is violated if the
24459 client is compiled with dynamic checks.
24461 The precise rule is as follows. A unit that is compiled with dynamic
24462 checks can only @code{with} a unit that meets at least one of the
24463 following criteria:
24465 @itemize @bullet
24467 @item
24468 The @code{with'ed} unit is itself compiled with dynamic elaboration
24469 checks (that is with the @option{-gnatE} switch.
24471 @item
24472 The @code{with'ed} unit is an internal GNAT implementation unit from
24473 the System, Interfaces, Ada, or GNAT hierarchies.
24475 @item
24476 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24478 @item
24479 The @code{with'ing} unit (that is the client) has an explicit pragma
24480 @code{Elaborate_All} for the @code{with'ed} unit.
24482 @end itemize
24484 @noindent
24485 If this rule is violated, that is if a unit with dynamic elaboration
24486 checks @code{with's} a unit that does not meet one of the above four
24487 criteria, then the binder (@code{gnatbind}) will issue a warning
24488 similar to that in the following example:
24490 @smallexample
24491 warning: "x.ads" has dynamic elaboration checks and with's
24492 warning:   "y.ads" which has static elaboration checks
24493 @end smallexample
24495 @noindent
24496 These warnings indicate that the rule has been violated, and that as a result
24497 elaboration checks may be missed in the resulting executable file.
24498 This warning may be suppressed using the @option{-ws} binder switch
24499 in the usual manner.
24501 One useful application of this mixing rule is in the case of a subsystem
24502 which does not itself @code{with} units from the remainder of the
24503 application. In this case, the entire subsystem can be compiled with
24504 dynamic checks to resolve a circularity in the subsystem, while
24505 allowing the main application that uses this subsystem to be compiled
24506 using the more reliable default static model.
24508 @node What to Do If the Default Elaboration Behavior Fails
24509 @section What to Do If the Default Elaboration Behavior Fails
24511 @noindent
24512 If the binder cannot find an acceptable order, it outputs detailed
24513 diagnostics. For example:
24514 @smallexample
24515 @group
24516 @iftex
24517 @leftskip=0cm
24518 @end iftex
24519 error: elaboration circularity detected
24520 info:   "proc (body)" must be elaborated before "pack (body)"
24521 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24522 info:     recompile "pack (body)" with -gnatel
24523 info:                             for full details
24524 info:       "proc (body)"
24525 info:         is needed by its spec:
24526 info:       "proc (spec)"
24527 info:         which is withed by:
24528 info:       "pack (body)"
24529 info:  "pack (body)" must be elaborated before "proc (body)"
24530 info:     reason: pragma Elaborate in unit "proc (body)"
24531 @end group
24533 @end smallexample
24535 @noindent
24536 In this case we have a cycle that the binder cannot break. On the one
24537 hand, there is an explicit pragma Elaborate in @code{proc} for
24538 @code{pack}. This means that the body of @code{pack} must be elaborated
24539 before the body of @code{proc}. On the other hand, there is elaboration
24540 code in @code{pack} that calls a subprogram in @code{proc}. This means
24541 that for maximum safety, there should really be a pragma
24542 Elaborate_All in @code{pack} for @code{proc} which would require that
24543 the body of @code{proc} be elaborated before the body of
24544 @code{pack}. Clearly both requirements cannot be satisfied.
24545 Faced with a circularity of this kind, you have three different options.
24547 @table @asis
24548 @item Fix the program
24549 The most desirable option from the point of view of long-term maintenance
24550 is to rearrange the program so that the elaboration problems are avoided.
24551 One useful technique is to place the elaboration code into separate
24552 child packages. Another is to move some of the initialization code to
24553 explicitly called subprograms, where the program controls the order
24554 of initialization explicitly. Although this is the most desirable option,
24555 it may be impractical and involve too much modification, especially in
24556 the case of complex legacy code.
24558 @item Perform dynamic checks
24559 If the compilations are done using the
24560 @option{-gnatE}
24561 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24562 manner. Dynamic checks are generated for all calls that could possibly result
24563 in raising an exception. With this switch, the compiler does not generate
24564 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24565 exactly as specified in the @cite{Ada Reference Manual}.
24566 The binder will generate
24567 an executable program that may or may not raise @code{Program_Error}, and then
24568 it is the programmer's job to ensure that it does not raise an exception. Note
24569 that it is important to compile all units with the switch, it cannot be used
24570 selectively.
24572 @item Suppress checks
24573 The drawback of dynamic checks is that they generate a
24574 significant overhead at run time, both in space and time. If you
24575 are absolutely sure that your program cannot raise any elaboration
24576 exceptions, and you still want to use the dynamic elaboration model,
24577 then you can use the configuration pragma
24578 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24579 example this pragma could be placed in the @file{gnat.adc} file.
24581 @item Suppress checks selectively
24582 When you know that certain calls or instantiations in elaboration code cannot
24583 possibly lead to an elaboration error, and the binder nevertheless complains
24584 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24585 elaboration circularities, it is possible to remove those warnings locally and
24586 obtain a program that will bind. Clearly this can be unsafe, and it is the
24587 responsibility of the programmer to make sure that the resulting program has no
24588 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24589 used with different granularity to suppress warnings and break elaboration
24590 circularities:
24592 @itemize @bullet
24593 @item
24594 Place the pragma that names the called subprogram in the declarative part
24595 that contains the call.
24597 @item
24598 Place the pragma in the declarative part, without naming an entity. This
24599 disables warnings on all calls in the corresponding  declarative region.
24601 @item
24602 Place the pragma in the package spec that declares the called subprogram,
24603 and name the subprogram. This disables warnings on all elaboration calls to
24604 that subprogram.
24606 @item
24607 Place the pragma in the package spec that declares the called subprogram,
24608 without naming any entity. This disables warnings on all elaboration calls to
24609 all subprograms declared in this spec.
24611 @item Use Pragma Elaborate
24612 As previously described in section @xref{Treatment of Pragma Elaborate},
24613 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24614 that no elaboration checks are required on calls to the designated unit.
24615 There may be cases in which the caller knows that no transitive calls
24616 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24617 case where @code{pragma Elaborate_All} would cause a circularity.
24618 @end itemize
24620 @noindent
24621 These five cases are listed in order of decreasing safety, and therefore
24622 require increasing programmer care in their application. Consider the
24623 following program:
24625 @smallexample @c adanocomment
24626 @b{package} Pack1 @b{is}
24627   @b{function} F1 @b{return} Integer;
24628   X1 : Integer;
24629 @b{end} Pack1;
24631 @b{package} Pack2 @b{is}
24632   @b{function} F2 @b{return} Integer;
24633   @b{function} Pure (x : integer) @b{return} integer;
24634   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24635   --  pragma Suppress (Elaboration_Check);              -- (4)
24636 @b{end} Pack2;
24638 @b{with} Pack2;
24639 @b{package} @b{body} Pack1 @b{is}
24640   @b{function} F1 @b{return} Integer @b{is}
24641   @b{begin}
24642     @b{return} 100;
24643   @b{end} F1;
24644   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24645 @b{begin}
24646   @b{declare}
24647     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24648     --  pragma Suppress(Elaboration_Check);             -- (2)
24649   @b{begin}
24650     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24651   @b{end};
24652 @b{end} Pack1;
24654 @b{with} Pack1;
24655 @b{package} @b{body} Pack2 @b{is}
24656   @b{function} F2 @b{return} Integer @b{is}
24657   @b{begin}
24658      @b{return} Pack1.F1;
24659   @b{end} F2;
24660   @b{function} Pure (x : integer) @b{return} integer @b{is}
24661   @b{begin}
24662      @b{return} x ** 3 - 3 * x;
24663   @b{end};
24664 @b{end} Pack2;
24666 @b{with} Pack1, Ada.Text_IO;
24667 @b{procedure} Proc3 @b{is}
24668 @b{begin}
24669   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24670 @b{end} Proc3;
24671 @end smallexample
24672 In the absence of any pragmas, an attempt to bind this program produces
24673 the following diagnostics:
24674 @smallexample
24675 @group
24676 @iftex
24677 @leftskip=.5cm
24678 @end iftex
24679 error: elaboration circularity detected
24680 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24681 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24682 info:       recompile "pack1 (body)" with -gnatel for full details
24683 info:          "pack1 (body)"
24684 info:             must be elaborated along with its spec:
24685 info:          "pack1 (spec)"
24686 info:             which is withed by:
24687 info:          "pack2 (body)"
24688 info:             which must be elaborated along with its spec:
24689 info:          "pack2 (spec)"
24690 info:             which is withed by:
24691 info:          "pack1 (body)"
24692 @end group
24693 @end smallexample
24694 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24695 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24696 F2 is safe, even though F2 calls F1, because the call appears after the
24697 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24698 remove the warning on the call. It is also possible to use pragma (2)
24699 because there are no other potentially unsafe calls in the block.
24701 @noindent
24702 The call to @code{Pure} is safe because this function does not depend on the
24703 state of @code{Pack2}. Therefore any call to this function is safe, and it
24704 is correct to place pragma (3) in the corresponding package spec.
24706 @noindent
24707 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24708 warnings on all calls to functions declared therein. Note that this is not
24709 necessarily safe, and requires more detailed examination of the subprogram
24710 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24711 be already elaborated.
24712 @end table
24714 @noindent
24715 It is hard to generalize on which of these four approaches should be
24716 taken. Obviously if it is possible to fix the program so that the default
24717 treatment works, this is preferable, but this may not always be practical.
24718 It is certainly simple enough to use
24719 @option{-gnatE}
24720 but the danger in this case is that, even if the GNAT binder
24721 finds a correct elaboration order, it may not always do so,
24722 and certainly a binder from another Ada compiler might not. A
24723 combination of testing and analysis (for which the
24724 information messages generated with the
24725 @option{-gnatel}
24726 switch can be useful) must be used to ensure that the program is free
24727 of errors. One switch that is useful in this testing is the
24728 @option{-p (pessimistic elaboration order)}
24729 switch for
24730 @code{gnatbind}.
24731 Normally the binder tries to find an order that has the best chance
24732 of avoiding elaboration problems. However, if this switch is used, the binder
24733 plays a devil's advocate role, and tries to choose the order that
24734 has the best chance of failing. If your program works even with this
24735 switch, then it has a better chance of being error free, but this is still
24736 not a guarantee.
24738 For an example of this approach in action, consider the C-tests (executable
24739 tests) from the ACVC suite. If these are compiled and run with the default
24740 treatment, then all but one of them succeed without generating any error
24741 diagnostics from the binder. However, there is one test that fails, and
24742 this is not surprising, because the whole point of this test is to ensure
24743 that the compiler can handle cases where it is impossible to determine
24744 a correct order statically, and it checks that an exception is indeed
24745 raised at run time.
24747 This one test must be compiled and run using the
24748 @option{-gnatE}
24749 switch, and then it passes. Alternatively, the entire suite can
24750 be run using this switch. It is never wrong to run with the dynamic
24751 elaboration switch if your code is correct, and we assume that the
24752 C-tests are indeed correct (it is less efficient, but efficiency is
24753 not a factor in running the ACVC tests.)
24755 @node Elaboration for Indirect Calls
24756 @section Elaboration for Indirect Calls
24757 @cindex Dispatching calls
24758 @cindex Indirect calls
24760 @noindent
24761 In rare cases, the static elaboration model fails to prevent
24762 dispatching calls to not-yet-elaborated subprograms. In such cases, we
24763 fall back to run-time checks; premature calls to any primitive
24764 operation of a tagged type before the body of the operation has been
24765 elaborated will raise @code{Program_Error}.
24767 Access-to-subprogram types, however, are handled conservatively, and
24768 do not require run-time checks. This was not true in earlier versions
24769 of the compiler; you can use the @option{-gnatd.U} debug switch to
24770 revert to the old behavior if the new conservative behavior causes
24771 elaboration cycles. Here, ``conservative'' means that if you do
24772 @code{P'Access} during elaboration, the compiler will assume that you
24773 might call @code{P} indirectly during elaboration, so it adds an
24774 implicit @code{pragma Elaborate_All} on the library unit containing
24775 @code{P}. The @option{-gnatd.U} switch is safe if you know there are
24776 no such calls. If the program worked before, it will continue to work
24777 with @option{-gnatd.U}. But beware that code modifications such as
24778 adding an indirect call can cause erroneous behavior in the presence
24779 of @option{-gnatd.U}.
24781 @node Summary of Procedures for Elaboration Control
24782 @section Summary of Procedures for Elaboration Control
24783 @cindex Elaboration control
24785 @noindent
24786 First, compile your program with the default options, using none of
24787 the special elaboration control switches. If the binder successfully
24788 binds your program, then you can be confident that, apart from issues
24789 raised by the use of access-to-subprogram types and dynamic dispatching,
24790 the program is free of elaboration errors. If it is important that the
24791 program be portable to other compilers than GNAT, then use the
24792 @option{-gnatel}
24793 switch to generate messages about missing @code{Elaborate} or
24794 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24796 If the program fails to bind using the default static elaboration
24797 handling, then you can fix the program to eliminate the binder
24798 message, or recompile the entire program with the
24799 @option{-gnatE} switch to generate dynamic elaboration checks,
24800 and, if you are sure there really are no elaboration problems,
24801 use a global pragma @code{Suppress (Elaboration_Check)}.
24803 @node Other Elaboration Order Considerations
24804 @section Other Elaboration Order Considerations
24805 @noindent
24806 This section has been entirely concerned with the issue of finding a valid
24807 elaboration order, as defined by the Ada Reference Manual. In a case
24808 where several elaboration orders are valid, the task is to find one
24809 of the possible valid elaboration orders (and the static model in GNAT
24810 will ensure that this is achieved).
24812 The purpose of the elaboration rules in the Ada Reference Manual is to
24813 make sure that no entity is accessed before it has been elaborated. For
24814 a subprogram, this means that the spec and body must have been elaborated
24815 before the subprogram is called. For an object, this means that the object
24816 must have been elaborated before its value is read or written. A violation
24817 of either of these two requirements is an access before elaboration order,
24818 and this section has been all about avoiding such errors.
24820 In the case where more than one order of elaboration is possible, in the
24821 sense that access before elaboration errors are avoided, then any one of
24822 the orders is ``correct'' in the sense that it meets the requirements of
24823 the Ada Reference Manual, and no such error occurs.
24825 However, it may be the case for a given program, that there are
24826 constraints on the order of elaboration that come not from consideration
24827 of avoiding elaboration errors, but rather from extra-lingual logic
24828 requirements. Consider this example:
24830 @smallexample @c ada
24831 @b{with} Init_Constants;
24832 @b{package} Constants @b{is}
24833    X : Integer := 0;
24834    Y : Integer := 0;
24835 @b{end} Constants;
24837 @b{package} Init_Constants @b{is}
24838    @b{procedure} P; --@i{ require a body}
24839 @b{end} Init_Constants;
24841 @b{with} Constants;
24842 @b{package} @b{body} Init_Constants @b{is}
24843    @b{procedure} P @b{is} @b{begin} @b{null}; @b{end};
24844 @b{begin}
24845    Constants.X := 3;
24846    Constants.Y := 4;
24847 @b{end} Init_Constants;
24849 @b{with} Constants;
24850 @b{package} Calc @b{is}
24851    Z : Integer := Constants.X + Constants.Y;
24852 @b{end} Calc;
24854 @b{with} Calc;
24855 @b{with} Text_IO; @b{use} Text_IO;
24856 @b{procedure} Main @b{is}
24857 @b{begin}
24858    Put_Line (Calc.Z'Img);
24859 @b{end} Main;
24860 @end smallexample
24862 @noindent
24863 In this example, there is more than one valid order of elaboration. For
24864 example both the following are correct orders:
24866 @smallexample
24867 Init_Constants spec
24868 Constants spec
24869 Calc spec
24870 Init_Constants body
24871 Main body
24873   and
24875 Init_Constants spec
24876 Init_Constants body
24877 Constants spec
24878 Calc spec
24879 Main body
24880 @end smallexample
24882 @noindent
24883 There is no language rule to prefer one or the other, both are correct
24884 from an order of elaboration point of view. But the programmatic effects
24885 of the two orders are very different. In the first, the elaboration routine
24886 of @code{Calc} initializes @code{Z} to zero, and then the main program
24887 runs with this value of zero. But in the second order, the elaboration
24888 routine of @code{Calc} runs after the body of Init_Constants has set
24889 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24890 runs.
24892 One could perhaps by applying pretty clever non-artificial intelligence
24893 to the situation guess that it is more likely that the second order of
24894 elaboration is the one desired, but there is no formal linguistic reason
24895 to prefer one over the other. In fact in this particular case, GNAT will
24896 prefer the second order, because of the rule that bodies are elaborated
24897 as soon as possible, but it's just luck that this is what was wanted
24898 (if indeed the second order was preferred).
24900 If the program cares about the order of elaboration routines in a case like
24901 this, it is important to specify the order required. In this particular
24902 case, that could have been achieved by adding to the spec of Calc:
24904 @smallexample @c ada
24905 @b{pragma} Elaborate_All (Constants);
24906 @end smallexample
24908 @noindent
24909 which requires that the body (if any) and spec of @code{Constants},
24910 as well as the body and spec of any unit @code{with}'ed by
24911 @code{Constants} be elaborated before @code{Calc} is elaborated.
24913 Clearly no automatic method can always guess which alternative you require,
24914 and if you are working with legacy code that had constraints of this kind
24915 which were not properly specified by adding @code{Elaborate} or
24916 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24917 compilers can choose different orders.
24919 However, GNAT does attempt to diagnose the common situation where there
24920 are uninitialized variables in the visible part of a package spec, and the
24921 corresponding package body has an elaboration block that directly or
24922 indirectly initialized one or more of these variables. This is the situation
24923 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24924 a warning that suggests this addition if it detects this situation.
24926 The @code{gnatbind}
24927 @option{-p} switch may be useful in smoking
24928 out problems. This switch causes bodies to be elaborated as late as possible
24929 instead of as early as possible. In the example above, it would have forced
24930 the choice of the first elaboration order. If you get different results
24931 when using this switch, and particularly if one set of results is right,
24932 and one is wrong as far as you are concerned, it shows that you have some
24933 missing @code{Elaborate} pragmas. For the example above, we have the
24934 following output:
24936 @smallexample
24937 gnatmake -f -q main
24938 main
24940 gnatmake -f -q main -bargs -p
24941 main
24943 @end smallexample
24945 @noindent
24946 It is of course quite unlikely that both these results are correct, so
24947 it is up to you in a case like this to investigate the source of the
24948 difference, by looking at the two elaboration orders that are chosen,
24949 and figuring out which is correct, and then adding the necessary
24950 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24952 @node Determining the Chosen Elaboration Order
24953 @section Determining the Chosen Elaboration Order
24954 @noindent
24956 To see the elaboration order that the binder chooses, you can look at
24957 the last part of the b~xxx.adb binder output file. Here is an example:
24959 @smallexample @c ada
24960 System.Soft_Links'Elab_Body;
24961 E14 := True;
24962 System.Secondary_Stack'Elab_Body;
24963 E18 := True;
24964 System.Exception_Table'Elab_Body;
24965 E24 := True;
24966 Ada.Io_Exceptions'Elab_Spec;
24967 E67 := True;
24968 Ada.Tags'Elab_Spec;
24969 Ada.Streams'Elab_Spec;
24970 E43 := True;
24971 Interfaces.C'Elab_Spec;
24972 E69 := True;
24973 System.Finalization_Root'Elab_Spec;
24974 E60 := True;
24975 System.Os_Lib'Elab_Body;
24976 E71 := True;
24977 System.Finalization_Implementation'Elab_Spec;
24978 System.Finalization_Implementation'Elab_Body;
24979 E62 := True;
24980 Ada.Finalization'Elab_Spec;
24981 E58 := True;
24982 Ada.Finalization.List_Controller'Elab_Spec;
24983 E76 := True;
24984 System.File_Control_Block'Elab_Spec;
24985 E74 := True;
24986 System.File_Io'Elab_Body;
24987 E56 := True;
24988 Ada.Tags'Elab_Body;
24989 E45 := True;
24990 Ada.Text_Io'Elab_Spec;
24991 Ada.Text_Io'Elab_Body;
24992 E07 := True;
24993 @end smallexample
24995 @noindent
24996 Here Elab_Spec elaborates the spec
24997 and Elab_Body elaborates the body. The assignments to the Exx flags
24998 flag that the corresponding body is now elaborated.
25000 You can also ask the binder to generate a more
25001 readable list of the elaboration order using the
25002 @code{-l} switch when invoking the binder. Here is
25003 an example of the output generated by this switch:
25005 @smallexample
25006 ada (spec)
25007 interfaces (spec)
25008 system (spec)
25009 system.case_util (spec)
25010 system.case_util (body)
25011 system.concat_2 (spec)
25012 system.concat_2 (body)
25013 system.concat_3 (spec)
25014 system.concat_3 (body)
25015 system.htable (spec)
25016 system.parameters (spec)
25017 system.parameters (body)
25018 system.crtl (spec)
25019 interfaces.c_streams (spec)
25020 interfaces.c_streams (body)
25021 system.restrictions (spec)
25022 system.restrictions (body)
25023 system.standard_library (spec)
25024 system.exceptions (spec)
25025 system.exceptions (body)
25026 system.storage_elements (spec)
25027 system.storage_elements (body)
25028 system.secondary_stack (spec)
25029 system.stack_checking (spec)
25030 system.stack_checking (body)
25031 system.string_hash (spec)
25032 system.string_hash (body)
25033 system.htable (body)
25034 system.strings (spec)
25035 system.strings (body)
25036 system.traceback (spec)
25037 system.traceback (body)
25038 system.traceback_entries (spec)
25039 system.traceback_entries (body)
25040 ada.exceptions (spec)
25041 ada.exceptions.last_chance_handler (spec)
25042 system.soft_links (spec)
25043 system.soft_links (body)
25044 ada.exceptions.last_chance_handler (body)
25045 system.secondary_stack (body)
25046 system.exception_table (spec)
25047 system.exception_table (body)
25048 ada.io_exceptions (spec)
25049 ada.tags (spec)
25050 ada.streams (spec)
25051 interfaces.c (spec)
25052 interfaces.c (body)
25053 system.finalization_root (spec)
25054 system.finalization_root (body)
25055 system.memory (spec)
25056 system.memory (body)
25057 system.standard_library (body)
25058 system.os_lib (spec)
25059 system.os_lib (body)
25060 system.unsigned_types (spec)
25061 system.stream_attributes (spec)
25062 system.stream_attributes (body)
25063 system.finalization_implementation (spec)
25064 system.finalization_implementation (body)
25065 ada.finalization (spec)
25066 ada.finalization (body)
25067 ada.finalization.list_controller (spec)
25068 ada.finalization.list_controller (body)
25069 system.file_control_block (spec)
25070 system.file_io (spec)
25071 system.file_io (body)
25072 system.val_uns (spec)
25073 system.val_util (spec)
25074 system.val_util (body)
25075 system.val_uns (body)
25076 system.wch_con (spec)
25077 system.wch_con (body)
25078 system.wch_cnv (spec)
25079 system.wch_jis (spec)
25080 system.wch_jis (body)
25081 system.wch_cnv (body)
25082 system.wch_stw (spec)
25083 system.wch_stw (body)
25084 ada.tags (body)
25085 ada.exceptions (body)
25086 ada.text_io (spec)
25087 ada.text_io (body)
25088 text_io (spec)
25089 gdbstr (body)
25090 @end smallexample
25092 @c **********************************
25093 @node Overflow Check Handling in GNAT
25094 @appendix Overflow Check Handling in GNAT
25095 @cindex Overflow checks
25096 @cindex Checks (overflow)
25097 @c **********************************
25099 @menu
25100 * Background::
25101 * Overflow Checking Modes in GNAT::
25102 * Specifying the Desired Mode::
25103 * Default Settings::
25104 * Implementation Notes::
25105 @end menu
25108 @node Background
25109 @section Background
25111 @noindent
25112 Overflow checks are checks that the compiler may make to ensure
25113 that intermediate results are not out of range. For example:
25115 @smallexample @c ada
25116    A : Integer;
25117    ...
25118    A := A + 1;
25119 @end smallexample
25121 @noindent
25122 if @code{A} has the value @code{Integer'Last}, then the addition may cause
25123 overflow since the result is out of range of the type @code{Integer}.
25124 In this case @code{Constraint_Error} will be raised if checks are
25125 enabled.
25127 A trickier situation arises in examples like the following:
25129 @smallexample @c ada
25130   A, C : Integer;
25131   ...
25132   A := (A + 1) + C;
25133 @end smallexample
25135 @noindent
25136 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
25137 Now the final result of the expression on the right hand side is
25138 @code{Integer'Last} which is in range, but the question arises whether the
25139 intermediate addition of @code{(A + 1)} raises an overflow error.
25141 The (perhaps surprising) answer is that the Ada language
25142 definition does not answer this question. Instead it leaves
25143 it up to the implementation to do one of two things if overflow
25144 checks are enabled.
25146 @itemize @bullet
25147 @item
25148 raise an exception (@code{Constraint_Error}), or
25150 @item
25151 yield the correct mathematical result which is then used in
25152 subsequent operations.
25153 @end itemize
25155 @noindent
25156 If the compiler chooses the first approach, then the assignment of this
25157 example will indeed raise @code{Constraint_Error} if overflow checking is
25158 enabled, or result in erroneous execution if overflow checks are suppressed.
25160 But if the compiler
25161 chooses the second approach, then it can perform both additions yielding
25162 the correct mathematical result, which is in range, so no exception
25163 will be raised, and the right result is obtained, regardless of whether
25164 overflow checks are suppressed.
25166 Note that in the first example an
25167 exception will be raised in either case, since if the compiler
25168 gives the correct mathematical result for the addition, it will
25169 be out of range of the target type of the assignment, and thus
25170 fails the range check.
25172 This lack of specified behavior in the handling of overflow for
25173 intermediate results is a source of non-portability, and can thus
25174 be problematic when programs are ported. Most typically this arises
25175 in a situation where the original compiler did not raise an exception,
25176 and then the application is moved to a compiler where the check is
25177 performed on the intermediate result and an unexpected exception is
25178 raised.
25180 Furthermore, when using Ada 2012's preconditions and other
25181 assertion forms, another issue arises. Consider:
25183 @smallexample @c ada
25184      @b{procedure} P (A, B : Integer) @b{with}
25185        Pre => A + B <= Integer'Last;
25186 @end smallexample
25188 @noindent
25189 One often wants to regard arithmetic in a context like this from
25190 a mathematical point of view. So for example, if the two actual parameters
25191 for a call to @code{P} are both @code{Integer'Last}, then
25192 the precondition should be regarded as False. If we are executing
25193 in a mode with run-time checks enabled for preconditions, then we would
25194 like this precondition to fail, rather than raising an exception
25195 because of the intermediate overflow.
25197 However, the language definition leaves the specification of
25198 whether the above condition fails (raising @code{Assert_Error}) or
25199 causes an intermediate overflow (raising @code{Constraint_Error})
25200 up to the implementation.
25202 The situation is worse in a case such as the following:
25204 @smallexample @c ada
25205      @b{procedure} Q (A, B, C : Integer) @b{with}
25206        Pre => A + B + C <= Integer'Last;
25207 @end smallexample
25209 @noindent
25210 Consider the call
25212 @smallexample @c ada
25213      Q (A => Integer'Last, B => 1, C => -1);
25214 @end smallexample
25216 @noindent
25217 From a mathematical point of view the precondition
25218 is True, but at run time we may (but are not guaranteed to) get an
25219 exception raised because of the intermediate overflow (and we really
25220 would prefer this precondition to be considered True at run time).
25222 @node Overflow Checking Modes in GNAT
25223 @section Overflow Checking Modes in GNAT
25225 @noindent
25226 To deal with the portability issue, and with the problem of
25227 mathematical versus run-time interpretation of the expressions in
25228 assertions, GNAT provides comprehensive control over the handling
25229 of intermediate overflow. GNAT can operate in three modes, and
25230 furthemore, permits separate selection of operating modes for
25231 the expressions within assertions (here the term ``assertions''
25232 is used in the technical sense, which includes preconditions and so forth)
25233 and for expressions appearing outside assertions.
25235 The three modes are:
25237 @itemize @bullet
25238 @item   @i{Use base type for intermediate operations} (@code{STRICT})
25240      In this mode, all intermediate results for predefined arithmetic
25241      operators are computed using the base type, and the result must
25242      be in range of the base type. If this is not the
25243      case then either an exception is raised (if overflow checks are
25244      enabled) or the execution is erroneous (if overflow checks are suppressed).
25245      This is the normal default mode.
25247 @item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
25249      In this mode, the compiler attempts to avoid intermediate overflows by
25250      using a larger integer type, typically @code{Long_Long_Integer},
25251      as the type in which arithmetic is
25252      performed for predefined arithmetic operators. This may be slightly more
25253      expensive at
25254      run time (compared to suppressing intermediate overflow checks), though
25255      the cost is negligible on modern 64-bit machines. For the examples given
25256      earlier, no intermediate overflows would have resulted in exceptions,
25257      since the intermediate results are all in the range of
25258      @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
25259      of GNAT). In addition, if checks are enabled, this reduces the number of
25260      checks that must be made, so this choice may actually result in an
25261      improvement in space and time behavior.
25263      However, there are cases where @code{Long_Long_Integer} is not large
25264      enough, consider the following example:
25266 @smallexample @c ada
25267        @b{procedure} R (A, B, C, D : Integer) @b{with}
25268          Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
25269 @end smallexample
25271      where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
25272      Now the intermediate results are
25273      out of the range of @code{Long_Long_Integer} even though the final result
25274      is in range and the precondition is True (from a mathematical point
25275      of view). In such a case, operating in this mode, an overflow occurs
25276      for the intermediate computation (which is why this mode
25277      says @i{most} intermediate overflows are avoided). In this case,
25278      an exception is raised if overflow checks are enabled, and the
25279      execution is erroneous if overflow checks are suppressed.
25281 @item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
25283      In this mode, the compiler  avoids all intermediate overflows
25284      by using arbitrary precision arithmetic as required. In this
25285      mode, the above example with @code{A**2 * B**2} would
25286      not cause intermediate overflow, because the intermediate result
25287      would be evaluated using sufficient precision, and the result
25288      of evaluating the precondition would be True.
25290      This mode has the advantage of avoiding any intermediate
25291      overflows, but at the expense of significant run-time overhead,
25292      including the use of a library (included automatically in this
25293      mode) for multiple-precision arithmetic.
25295      This mode provides cleaner semantics for assertions, since now
25296      the run-time behavior emulates true arithmetic behavior for the
25297      predefined arithmetic operators, meaning that there is never a
25298      conflict between the mathematical view of the assertion, and its
25299      run-time behavior.
25301      Note that in this mode, the behavior is unaffected by whether or
25302      not overflow checks are suppressed, since overflow does not occur.
25303      It is possible for gigantic intermediate expressions to raise
25304      @code{Storage_Error} as a result of attempting to compute the
25305      results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
25306      but overflow is impossible.
25309 @end itemize
25311 @noindent
25312   Note that these modes apply only to the evaluation of predefined
25313   arithmetic, membership, and comparison operators for signed integer
25314   aritmetic.
25316   For fixed-point arithmetic, checks can be suppressed. But if checks
25317   are enabled
25318   then fixed-point values are always checked for overflow against the
25319   base type for intermediate expressions (that is such checks always
25320   operate in the equivalent of @code{STRICT} mode).
25322   For floating-point, on nearly all architectures, @code{Machine_Overflows}
25323   is False, and IEEE infinities are generated, so overflow exceptions
25324   are never raised. If you want to avoid infinities, and check that
25325   final results of expressions are in range, then you can declare a
25326   constrained floating-point type, and range checks will be carried
25327   out in the normal manner (with infinite values always failing all
25328   range checks).
25331 @c -------------------------
25332 @node Specifying the Desired Mode
25333 @section Specifying the Desired Mode
25335 @noindent
25336 The desired mode of for handling intermediate overflow can be specified using
25337 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
25338 The pragma has the form
25339 @cindex pragma @code{Overflow_Mode}
25341 @smallexample @c ada
25342     @b{pragma} Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
25343 @end smallexample
25345 @noindent
25346 where @code{MODE} is one of
25348 @itemize @bullet
25349 @item   @code{STRICT}:  intermediate overflows checked (using base type)
25350 @item   @code{MINIMIZED}: minimize intermediate overflows
25351 @item   @code{ELIMINATED}: eliminate intermediate overflows
25352 @end itemize
25354 @noindent
25355 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
25356 @code{minimized} all have the same effect.
25358 If only the @code{General} parameter is present, then the given @code{MODE}
25359 applies
25360 to expressions both within and outside assertions. If both arguments
25361 are present, then @code{General} applies to expressions outside assertions,
25362 and @code{Assertions} applies to expressions within assertions. For example:
25364 @smallexample @c ada
25365    @b{pragma} Overflow_Mode
25366      (General => Minimized, Assertions => Eliminated);
25367 @end smallexample
25369 @noindent
25370 specifies that general expressions outside assertions be evaluated
25371 in ``minimize intermediate overflows'' mode, and expressions within
25372 assertions be evaluated in ``eliminate intermediate overflows'' mode.
25373 This is often a reasonable choice, avoiding excessive overhead
25374 outside assertions, but assuring a high degree of portability
25375 when importing code from another compiler, while incurring
25376 the extra overhead for assertion expressions to ensure that
25377 the behavior at run time matches the expected mathematical
25378 behavior.
25380 The @code{Overflow_Mode} pragma has the same scoping and placement
25381 rules as pragma @code{Suppress}, so it can occur either as a
25382 configuration pragma, specifying a default for the whole
25383 program, or in a declarative scope, where it applies to the
25384 remaining declarations and statements in that scope.
25386 Note that pragma @code{Overflow_Mode} does not affect whether
25387 overflow checks are enabled or suppressed. It only controls the
25388 method used to compute intermediate values. To control whether
25389 overflow checking is enabled or suppressed, use pragma @code{Suppress}
25390 or @code{Unsuppress} in the usual manner
25392 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
25393 can be used to control the checking mode default (which can be subsequently
25394 overridden using pragmas).
25395 @cindex @option{-gnato?} (gcc)
25396 @cindex @option{-gnato??} (gcc)
25398 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
25400 @itemize @bullet
25401 @item   @code{1}:
25402 use base type for intermediate operations (@code{STRICT})
25403 @item   @code{2}:
25404 minimize intermediate overflows (@code{MINIMIZED})
25405 @item   @code{3}:
25406 eliminate intermediate overflows (@code{ELIMINATED})
25407 @end itemize
25409 @noindent
25410 As with the pragma, if only one digit appears then it applies to all
25411 cases; if two digits are given, then the first applies outside
25412 assertions, and the second within assertions. Thus the equivalent
25413 of the example pragma above would be
25414 @option{-gnato23}.
25416 If no digits follow the @option{-gnato}, then it is equivalent to
25417 @option{-gnato11},
25418 causing all intermediate operations to be computed using the base
25419 type (@code{STRICT} mode).
25421 In addition to setting the mode used for computation of intermediate
25422 results, the @code{-gnato} switch also enables overflow checking (which
25423 is suppressed by default). It thus combines the effect of using
25424 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
25427 @c -------------------------
25428 @node Default Settings
25429 @section Default Settings
25431 The default mode for overflow checks is
25433 @smallexample
25434    General => Strict
25435 @end smallexample
25437 @noindent
25438 which causes all computations both inside and outside assertions to use
25439 the base type. In addition overflow checks are suppressed.
25441 This retains compatibility with previous versions of
25442 GNAT which suppressed overflow checks by default and always
25443 used the base type for computation of intermediate results.
25445 The switch @option{-gnato} (with no digits following) is equivalent to
25446 @cindex @option{-gnato} (gcc)
25448 @smallexample
25449    General => Strict
25450 @end smallexample
25452 @noindent
25453 which causes overflow checking of all intermediate overflows
25454 both inside and outside assertions against the base type.
25455 This provides compatibility
25456 with this switch as implemented in previous versions of GNAT.
25458 The pragma @code{Suppress (Overflow_Check)} disables overflow
25459 checking, but it has no effect on the method used for computing
25460 intermediate results.
25462 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
25463 checking, but it has no effect on the method used for computing
25464 intermediate results.
25466 @c -------------------------
25467 @node Implementation Notes
25468 @section Implementation Notes
25470 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
25471 reasonably efficient, and can be generally used. It also helps
25472 to ensure compatibility with code imported from some other
25473 compiler to GNAT.
25475 Setting all intermediate overflows checking (@code{CHECKED} mode)
25476 makes sense if you want to
25477 make sure that your code is compatible with any other possible
25478 Ada implementation. This may be useful in ensuring portability
25479 for code that is to be exported to some other compiler than GNAT.
25482 The Ada standard allows the reassociation of expressions at
25483 the same precedence level if no parentheses are present. For
25484 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
25485 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
25486 introducing or eliminating an overflow exception. The GNAT
25487 compiler never takes advantage of this freedom, and the
25488 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
25489 If you need the other order, you can write the parentheses
25490 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
25492 The use of @code{ELIMINATED} mode will cause the compiler to
25493 automatically include an appropriate arbitrary precision
25494 integer arithmetic package. The compiler will make calls
25495 to this package, though only in cases where it cannot be
25496 sure that @code{Long_Long_Integer} is sufficient to guard against
25497 intermediate overflows. This package does not use dynamic
25498 alllocation, but it does use the secondary stack, so an
25499 appropriate secondary stack package must be present (this
25500 is always true for standard full Ada, but may require
25501 specific steps for restricted run times such as ZFP).
25503 Although @code{ELIMINATED} mode causes expressions to use arbitrary
25504 precision arithmetic, avoiding overflow, the final result
25505 must be in an appropriate range. This is true even if the
25506 final result is of type @code{[Long_[Long_]]Integer'Base}, which
25507 still has the same bounds as its associated constrained
25508 type at run-time.
25510 Currently, the @code{ELIMINATED} mode is only available on target
25511 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
25512 platforms).
25514 @c *******************************
25515 @node Conditional Compilation
25516 @appendix Conditional Compilation
25517 @c *******************************
25518 @cindex Conditional compilation
25520 @noindent
25521 It is often necessary to arrange for a single source program
25522 to serve multiple purposes, where it is compiled in different
25523 ways to achieve these different goals. Some examples of the
25524 need for this feature are
25526 @itemize @bullet
25527 @item  Adapting a program to a different hardware environment
25528 @item  Adapting a program to a different target architecture
25529 @item  Turning debugging features on and off
25530 @item  Arranging for a program to compile with different compilers
25531 @end itemize
25533 @noindent
25534 In C, or C++, the typical approach would be to use the preprocessor
25535 that is defined as part of the language. The Ada language does not
25536 contain such a feature. This is not an oversight, but rather a very
25537 deliberate design decision, based on the experience that overuse of
25538 the preprocessing features in C and C++ can result in programs that
25539 are extremely difficult to maintain. For example, if we have ten
25540 switches that can be on or off, this means that there are a thousand
25541 separate programs, any one of which might not even be syntactically
25542 correct, and even if syntactically correct, the resulting program
25543 might not work correctly. Testing all combinations can quickly become
25544 impossible.
25546 Nevertheless, the need to tailor programs certainly exists, and in
25547 this Appendix we will discuss how this can
25548 be achieved using Ada in general, and GNAT in particular.
25550 @menu
25551 * Use of Boolean Constants::
25552 * Debugging - A Special Case::
25553 * Conditionalizing Declarations::
25554 * Use of Alternative Implementations::
25555 * Preprocessing::
25556 @end menu
25558 @node Use of Boolean Constants
25559 @section Use of Boolean Constants
25561 @noindent
25562 In the case where the difference is simply which code
25563 sequence is executed, the cleanest solution is to use Boolean
25564 constants to control which code is executed.
25566 @smallexample @c ada
25567 @group
25568 FP_Initialize_Required : @b{constant} Boolean := True;
25569 @dots{}
25570 @b{if} FP_Initialize_Required @b{then}
25571 @dots{}
25572 @b{end} @b{if};
25573 @end group
25574 @end smallexample
25576 @noindent
25577 Not only will the code inside the @code{if} statement not be executed if
25578 the constant Boolean is @code{False}, but it will also be completely
25579 deleted from the program.
25580 However, the code is only deleted after the @code{if} statement
25581 has been checked for syntactic and semantic correctness.
25582 (In contrast, with preprocessors the code is deleted before the
25583 compiler ever gets to see it, so it is not checked until the switch
25584 is turned on.)
25585 @cindex Preprocessors (contrasted with conditional compilation)
25587 Typically the Boolean constants will be in a separate package,
25588 something like:
25590 @smallexample @c ada
25591 @group
25592 @b{package} Config @b{is}
25593    FP_Initialize_Required : @b{constant} Boolean := True;
25594    Reset_Available        : @b{constant} Boolean := False;
25595    @dots{}
25596 @b{end} Config;
25597 @end group
25598 @end smallexample
25600 @noindent
25601 The @code{Config} package exists in multiple forms for the various targets,
25602 with an appropriate script selecting the version of @code{Config} needed.
25603 Then any other unit requiring conditional compilation can do a @code{with}
25604 of @code{Config} to make the constants visible.
25607 @node Debugging - A Special Case
25608 @section Debugging - A Special Case
25610 @noindent
25611 A common use of conditional code is to execute statements (for example
25612 dynamic checks, or output of intermediate results) under control of a
25613 debug switch, so that the debugging behavior can be turned on and off.
25614 This can be done using a Boolean constant to control whether the code
25615 is active:
25617 @smallexample @c ada
25618 @group
25619 @b{if} Debugging @b{then}
25620    Put_Line ("got to the first stage!");
25621 @b{end} @b{if};
25622 @end group
25623 @end smallexample
25625 @noindent
25628 @smallexample @c ada
25629 @group
25630 @b{if} Debugging @b{and} @b{then} Temperature > 999.0 @b{then}
25631    @b{raise} Temperature_Crazy;
25632 @b{end} @b{if};
25633 @end group
25634 @end smallexample
25636 @noindent
25637 Since this is a common case, there are special features to deal with
25638 this in a convenient manner. For the case of tests, Ada 2005 has added
25639 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25640 @cindex pragma @code{Assert}
25641 on the @code{Assert} pragma that has always been available in GNAT, so this
25642 feature may be used with GNAT even if you are not using Ada 2005 features.
25643 The use of pragma @code{Assert} is described in
25644 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25645 example, the last test could be written:
25647 @smallexample @c ada
25648 @b{pragma} Assert (Temperature <= 999.0, "Temperature Crazy");
25649 @end smallexample
25651 @noindent
25652 or simply
25654 @smallexample @c ada
25655 @b{pragma} Assert (Temperature <= 999.0);
25656 @end smallexample
25658 @noindent
25659 In both cases, if assertions are active and the temperature is excessive,
25660 the exception @code{Assert_Failure} will be raised, with the given string in
25661 the first case or a string indicating the location of the pragma in the second
25662 case used as the exception message.
25664 You can turn assertions on and off by using the @code{Assertion_Policy}
25665 pragma.
25666 @cindex pragma @code{Assertion_Policy}
25667 This is an Ada 2005 pragma which is implemented in all modes by
25668 GNAT, but only in the latest versions of GNAT which include Ada 2005
25669 capability. Alternatively, you can use the @option{-gnata} switch
25670 @cindex @option{-gnata} switch
25671 to enable assertions from the command line (this is recognized by all versions
25672 of GNAT).
25674 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25675 @code{Debug} can be used:
25676 @cindex pragma @code{Debug}
25678 @smallexample @c ada
25679 @b{pragma} Debug (Put_Line ("got to the first stage!"));
25680 @end smallexample
25682 @noindent
25683 If debug pragmas are enabled, the argument, which must be of the form of
25684 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25685 Only one call can be present, but of course a special debugging procedure
25686 containing any code you like can be included in the program and then
25687 called in a pragma @code{Debug} argument as needed.
25689 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25690 construct is that pragma @code{Debug} can appear in declarative contexts,
25691 such as at the very beginning of a procedure, before local declarations have
25692 been elaborated.
25694 Debug pragmas are enabled using either the @option{-gnata} switch that also
25695 controls assertions, or with a separate Debug_Policy pragma.
25696 @cindex pragma @code{Debug_Policy}
25697 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25698 in Ada 95 and Ada 83 programs as well), and is analogous to
25699 pragma @code{Assertion_Policy} to control assertions.
25701 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25702 and thus they can appear in @file{gnat.adc} if you are not using a
25703 project file, or in the file designated to contain configuration pragmas
25704 in a project file.
25705 They then apply to all subsequent compilations. In practice the use of
25706 the @option{-gnata} switch is often the most convenient method of controlling
25707 the status of these pragmas.
25709 Note that a pragma is not a statement, so in contexts where a statement
25710 sequence is required, you can't just write a pragma on its own. You have
25711 to add a @code{null} statement.
25713 @smallexample @c ada
25714 @group
25715 @b{if} @dots{} @b{then}
25716    @dots{} -- some statements
25717 @b{else}
25718    @b{pragma} Assert (Num_Cases < 10);
25719    @b{null};
25720 @b{end} @b{if};
25721 @end group
25722 @end smallexample
25725 @node Conditionalizing Declarations
25726 @section Conditionalizing Declarations
25728 @noindent
25729 In some cases, it may be necessary to conditionalize declarations to meet
25730 different requirements. For example we might want a bit string whose length
25731 is set to meet some hardware message requirement.
25733 In some cases, it may be possible to do this using declare blocks controlled
25734 by conditional constants:
25736 @smallexample @c ada
25737 @group
25738 @b{if} Small_Machine @b{then}
25739    @b{declare}
25740       X : Bit_String (1 .. 10);
25741    @b{begin}
25742       @dots{}
25743    @b{end};
25744 @b{else}
25745    @b{declare}
25746       X : Large_Bit_String (1 .. 1000);
25747    @b{begin}
25748       @dots{}
25749    @b{end};
25750 @b{end} @b{if};
25751 @end group
25752 @end smallexample
25754 @noindent
25755 Note that in this approach, both declarations are analyzed by the
25756 compiler so this can only be used where both declarations are legal,
25757 even though one of them will not be used.
25759 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25760 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25761 that are parameterized by these constants. For example
25763 @smallexample @c ada
25764 @group
25765 @b{for} Rec @b{use}
25766   Field1 @b{at} 0 @b{range} Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25767 @b{end} @b{record};
25768 @end group
25769 @end smallexample
25771 @noindent
25772 If @code{Bits_Per_Word} is set to 32, this generates either
25774 @smallexample @c ada
25775 @group
25776 @b{for} Rec @b{use}
25777   Field1 @b{at} 0 @b{range} 0 .. 32;
25778 @b{end} @b{record};
25779 @end group
25780 @end smallexample
25782 @noindent
25783 for the big endian case, or
25785 @smallexample @c ada
25786 @group
25787 @b{for} Rec @b{use} @b{record}
25788   Field1 @b{at} 0 @b{range} 10 .. 32;
25789 @b{end} @b{record};
25790 @end group
25791 @end smallexample
25793 @noindent
25794 for the little endian case. Since a powerful subset of Ada expression
25795 notation is usable for creating static constants, clever use of this
25796 feature can often solve quite difficult problems in conditionalizing
25797 compilation (note incidentally that in Ada 95, the little endian
25798 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25799 need to define this one yourself).
25802 @node Use of Alternative Implementations
25803 @section Use of Alternative Implementations
25805 @noindent
25806 In some cases, none of the approaches described above are adequate. This
25807 can occur for example if the set of declarations required is radically
25808 different for two different configurations.
25810 In this situation, the official Ada way of dealing with conditionalizing
25811 such code is to write separate units for the different cases. As long as
25812 this does not result in excessive duplication of code, this can be done
25813 without creating maintenance problems. The approach is to share common
25814 code as far as possible, and then isolate the code and declarations
25815 that are different. Subunits are often a convenient method for breaking
25816 out a piece of a unit that is to be conditionalized, with separate files
25817 for different versions of the subunit for different targets, where the
25818 build script selects the right one to give to the compiler.
25819 @cindex Subunits (and conditional compilation)
25821 As an example, consider a situation where a new feature in Ada 2005
25822 allows something to be done in a really nice way. But your code must be able
25823 to compile with an Ada 95 compiler. Conceptually you want to say:
25825 @smallexample @c ada
25826 @group
25827 @b{if} Ada_2005 @b{then}
25828    @dots{} neat Ada 2005 code
25829 @b{else}
25830    @dots{} not quite as neat Ada 95 code
25831 @b{end} @b{if};
25832 @end group
25833 @end smallexample
25835 @noindent
25836 where @code{Ada_2005} is a Boolean constant.
25838 But this won't work when @code{Ada_2005} is set to @code{False},
25839 since the @code{then} clause will be illegal for an Ada 95 compiler.
25840 (Recall that although such unreachable code would eventually be deleted
25841 by the compiler, it still needs to be legal.  If it uses features
25842 introduced in Ada 2005, it will be illegal in Ada 95.)
25844 So instead we write
25846 @smallexample @c ada
25847 @b{procedure} Insert @b{is} @b{separate};
25848 @end smallexample
25850 @noindent
25851 Then we have two files for the subunit @code{Insert}, with the two sets of
25852 code.
25853 If the package containing this is called @code{File_Queries}, then we might
25854 have two files
25856 @itemize @bullet
25857 @item    @file{file_queries-insert-2005.adb}
25858 @item    @file{file_queries-insert-95.adb}
25859 @end itemize
25861 @noindent
25862 and the build script renames the appropriate file to
25864 @smallexample
25865 file_queries-insert.adb
25866 @end smallexample
25868 @noindent
25869 and then carries out the compilation.
25871 This can also be done with project files' naming schemes. For example:
25873 @smallexample @c project
25874 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25875 @end smallexample
25877 @noindent
25878 Note also that with project files it is desirable to use a different extension
25879 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25880 conflict may arise through another commonly used feature: to declare as part
25881 of the project a set of directories containing all the sources obeying the
25882 default naming scheme.
25884 The use of alternative units is certainly feasible in all situations,
25885 and for example the Ada part of the GNAT run-time is conditionalized
25886 based on the target architecture using this approach. As a specific example,
25887 consider the implementation of the AST feature in VMS. There is one
25888 spec:
25890 @smallexample
25891 s-asthan.ads
25892 @end smallexample
25894 @noindent
25895 which is the same for all architectures, and three bodies:
25897 @table @file
25898 @item    s-asthan.adb
25899 used for all non-VMS operating systems
25900 @item    s-asthan-vms-alpha.adb
25901 used for VMS on the Alpha
25902 @item    s-asthan-vms-ia64.adb
25903 used for VMS on the ia64
25904 @end table
25906 @noindent
25907 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25908 this operating system feature is not available, and the two remaining
25909 versions interface with the corresponding versions of VMS to provide
25910 VMS-compatible AST handling. The GNAT build script knows the architecture
25911 and operating system, and automatically selects the right version,
25912 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25914 Another style for arranging alternative implementations is through Ada's
25915 access-to-subprogram facility.
25916 In case some functionality is to be conditionally included,
25917 you can declare an access-to-procedure variable @code{Ref} that is initialized
25918 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25919 when appropriate.
25920 In some library package, set @code{Ref} to @code{Proc'Access} for some
25921 procedure @code{Proc} that performs the relevant processing.
25922 The initialization only occurs if the library package is included in the
25923 program.
25924 The same idea can also be implemented using tagged types and dispatching
25925 calls.
25928 @node Preprocessing
25929 @section Preprocessing
25930 @cindex Preprocessing
25932 @noindent
25933 Although it is quite possible to conditionalize code without the use of
25934 C-style preprocessing, as described earlier in this section, it is
25935 nevertheless convenient in some cases to use the C approach. Moreover,
25936 older Ada compilers have often provided some preprocessing capability,
25937 so legacy code may depend on this approach, even though it is not
25938 standard.
25940 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25941 extent on the various preprocessors that have been used
25942 with legacy code on other compilers, to enable easier transition).
25944 The preprocessor may be used in two separate modes. It can be used quite
25945 separately from the compiler, to generate a separate output source file
25946 that is then fed to the compiler as a separate step. This is the
25947 @code{gnatprep} utility, whose use is fully described in
25948 @ref{Preprocessing with gnatprep}.
25949 @cindex @code{gnatprep}
25951 The preprocessing language allows such constructs as
25953 @smallexample
25954 @group
25955 #if DEBUG or else (PRIORITY > 4) then
25956    bunch of declarations
25957 #else
25958    completely different bunch of declarations
25959 #end if;
25960 @end group
25961 @end smallexample
25963 @noindent
25964 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25965 defined either on the command line or in a separate file.
25967 The other way of running the preprocessor is even closer to the C style and
25968 often more convenient. In this approach the preprocessing is integrated into
25969 the compilation process. The compiler is fed the preprocessor input which
25970 includes @code{#if} lines etc, and then the compiler carries out the
25971 preprocessing internally and processes the resulting output.
25972 For more details on this approach, see @ref{Integrated Preprocessing}.
25975 @c *******************************
25976 @node Inline Assembler
25977 @appendix Inline Assembler
25978 @c *******************************
25980 @noindent
25981 If you need to write low-level software that interacts directly
25982 with the hardware, Ada provides two ways to incorporate assembly
25983 language code into your program.  First, you can import and invoke
25984 external routines written in assembly language, an Ada feature fully
25985 supported by GNAT@.  However, for small sections of code it may be simpler
25986 or more efficient to include assembly language statements directly
25987 in your Ada source program, using the facilities of the implementation-defined
25988 package @code{System.Machine_Code}, which incorporates the gcc
25989 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25990 including the following:
25992 @itemize @bullet
25993 @item No need to use non-Ada tools
25994 @item Consistent interface over different targets
25995 @item Automatic usage of the proper calling conventions
25996 @item Access to Ada constants and variables
25997 @item Definition of intrinsic routines
25998 @item Possibility of inlining a subprogram comprising assembler code
25999 @item Code optimizer can take Inline Assembler code into account
26000 @end itemize
26002 This chapter presents a series of examples to show you how to use
26003 the Inline Assembler.  Although it focuses on the Intel x86,
26004 the general approach applies also to other processors.
26005 It is assumed that you are familiar with Ada
26006 and with assembly language programming.
26008 @menu
26009 * Basic Assembler Syntax::
26010 * A Simple Example of Inline Assembler::
26011 * Output Variables in Inline Assembler::
26012 * Input Variables in Inline Assembler::
26013 * Inlining Inline Assembler Code::
26014 * Other Asm Functionality::
26015 @end menu
26017 @c ---------------------------------------------------------------------------
26018 @node Basic Assembler Syntax
26019 @section Basic Assembler Syntax
26021 @noindent
26022 The assembler used by GNAT and gcc is based not on the Intel assembly
26023 language, but rather on a language that descends from the AT&T Unix
26024 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
26025 The following table summarizes the main features of @emph{as} syntax
26026 and points out the differences from the Intel conventions.
26027 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
26028 pre-processor) documentation for further information.
26030 @table @asis
26031 @item Register names
26032 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
26034 Intel: No extra punctuation; for example @code{eax}
26036 @item Immediate operand
26037 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
26039 Intel: No extra punctuation; for example @code{4}
26041 @item Address
26042 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
26044 Intel: No extra punctuation; for example @code{loc}
26046 @item Memory contents
26047 gcc / @emph{as}: No extra punctuation; for example @code{loc}
26049 Intel: Square brackets; for example @code{[loc]}
26051 @item Register contents
26052 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
26054 Intel: Square brackets; for example @code{[eax]}
26056 @item Hexadecimal numbers
26057 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
26059 Intel: Trailing ``h''; for example @code{A0h}
26061 @item Operand size
26062 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
26063 a 16-bit word
26065 Intel: Implicit, deduced by assembler; for example @code{mov}
26067 @item Instruction repetition
26068 gcc / @emph{as}: Split into two lines; for example
26070 @code{rep}
26072 @code{stosl}
26074 Intel: Keep on one line; for example @code{rep stosl}
26076 @item Order of operands
26077 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
26079 Intel: Destination first; for example @code{mov eax, 4}
26080 @end table
26082 @c ---------------------------------------------------------------------------
26083 @node A Simple Example of Inline Assembler
26084 @section A Simple Example of Inline Assembler
26086 @noindent
26087 The following example will generate a single assembly language statement,
26088 @code{nop}, which does nothing.  Despite its lack of run-time effect,
26089 the example will be useful in illustrating the basics of
26090 the Inline Assembler facility.
26092 @smallexample @c ada
26093 @group
26094 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26095 @b{procedure} Nothing @b{is}
26096 @b{begin}
26097    Asm ("nop");
26098 @b{end} Nothing;
26099 @end group
26100 @end smallexample
26102 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
26103 here it takes one parameter, a @emph{template string} that must be a static
26104 expression and that will form the generated instruction.
26105 @code{Asm} may be regarded as a compile-time procedure that parses
26106 the template string and additional parameters (none here),
26107 from which it generates a sequence of assembly language instructions.
26109 The examples in this chapter will illustrate several of the forms
26110 for invoking @code{Asm}; a complete specification of the syntax
26111 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
26112 Manual}.
26114 Under the standard GNAT conventions, the @code{Nothing} procedure
26115 should be in a file named @file{nothing.adb}.
26116 You can build the executable in the usual way:
26117 @smallexample
26118 gnatmake nothing
26119 @end smallexample
26120 However, the interesting aspect of this example is not its run-time behavior
26121 but rather the generated assembly code.
26122 To see this output, invoke the compiler as follows:
26123 @smallexample
26124    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
26125 @end smallexample
26126 where the options are:
26128 @table @code
26129 @item -c
26130 compile only (no bind or link)
26131 @item -S
26132 generate assembler listing
26133 @item -fomit-frame-pointer
26134 do not set up separate stack frames
26135 @item -gnatp
26136 do not add runtime checks
26137 @end table
26139 This gives a human-readable assembler version of the code. The resulting
26140 file will have the same name as the Ada source file, but with a @code{.s}
26141 extension. In our example, the file @file{nothing.s} has the following
26142 contents:
26144 @smallexample
26145 @group
26146 .file "nothing.adb"
26147 gcc2_compiled.:
26148 ___gnu_compiled_ada:
26149 .text
26150    .align 4
26151 .globl __ada_nothing
26152 __ada_nothing:
26153 #APP
26154    nop
26155 #NO_APP
26156    jmp L1
26157    .align 2,0x90
26159    ret
26160 @end group
26161 @end smallexample
26163 The assembly code you included is clearly indicated by
26164 the compiler, between the @code{#APP} and @code{#NO_APP}
26165 delimiters. The character before the 'APP' and 'NOAPP'
26166 can differ on different targets. For example, GNU/Linux uses '#APP' while
26167 on NT you will see '/APP'.
26169 If you make a mistake in your assembler code (such as using the
26170 wrong size modifier, or using a wrong operand for the instruction) GNAT
26171 will report this error in a temporary file, which will be deleted when
26172 the compilation is finished.  Generating an assembler file will help
26173 in such cases, since you can assemble this file separately using the
26174 @emph{as} assembler that comes with gcc.
26176 Assembling the file using the command
26178 @smallexample
26179 as @file{nothing.s}
26180 @end smallexample
26181 @noindent
26182 will give you error messages whose lines correspond to the assembler
26183 input file, so you can easily find and correct any mistakes you made.
26184 If there are no errors, @emph{as} will generate an object file
26185 @file{nothing.out}.
26187 @c ---------------------------------------------------------------------------
26188 @node Output Variables in Inline Assembler
26189 @section Output Variables in Inline Assembler
26191 @noindent
26192 The examples in this section, showing how to access the processor flags,
26193 illustrate how to specify the destination operands for assembly language
26194 statements.
26196 @smallexample @c ada
26197 @group
26198 @b{with} Interfaces; @b{use} Interfaces;
26199 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26200 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26201 @b{procedure} Get_Flags @b{is}
26202    Flags : Unsigned_32;
26203    @b{use} ASCII;
26204 @b{begin}
26205    Asm ("pushfl"          & LF & HT & --@i{ push flags on stack}
26206         "popl %%eax"      & LF & HT & --@i{ load eax with flags}
26207         "movl %%eax, %0",             --@i{ store flags in variable}
26208         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26209    Put_Line ("Flags register:" & Flags'Img);
26210 @b{end} Get_Flags;
26211 @end group
26212 @end smallexample
26214 In order to have a nicely aligned assembly listing, we have separated
26215 multiple assembler statements in the Asm template string with linefeed
26216 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
26217 The resulting section of the assembly output file is:
26219 @smallexample
26220 @group
26221 #APP
26222    pushfl
26223    popl %eax
26224    movl %eax, -40(%ebp)
26225 #NO_APP
26226 @end group
26227 @end smallexample
26229 It would have been legal to write the Asm invocation as:
26231 @smallexample
26232 Asm ("pushfl popl %%eax movl %%eax, %0")
26233 @end smallexample
26235 but in the generated assembler file, this would come out as:
26237 @smallexample
26238 #APP
26239    pushfl popl %eax movl %eax, -40(%ebp)
26240 #NO_APP
26241 @end smallexample
26243 which is not so convenient for the human reader.
26245 We use Ada comments
26246 at the end of each line to explain what the assembler instructions
26247 actually do.  This is a useful convention.
26249 When writing Inline Assembler instructions, you need to precede each register
26250 and variable name with a percent sign.  Since the assembler already requires
26251 a percent sign at the beginning of a register name, you need two consecutive
26252 percent signs for such names in the Asm template string, thus @code{%%eax}.
26253 In the generated assembly code, one of the percent signs will be stripped off.
26255 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
26256 variables: operands you later define using @code{Input} or @code{Output}
26257 parameters to @code{Asm}.
26258 An output variable is illustrated in
26259 the third statement in the Asm template string:
26260 @smallexample
26261 movl %%eax, %0
26262 @end smallexample
26263 The intent is to store the contents of the eax register in a variable that can
26264 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
26265 necessarily work, since the compiler might optimize by using a register
26266 to hold Flags, and the expansion of the @code{movl} instruction would not be
26267 aware of this optimization.  The solution is not to store the result directly
26268 but rather to advise the compiler to choose the correct operand form;
26269 that is the purpose of the @code{%0} output variable.
26271 Information about the output variable is supplied in the @code{Outputs}
26272 parameter to @code{Asm}:
26273 @smallexample
26274 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26275 @end smallexample
26277 The output is defined by the @code{Asm_Output} attribute of the target type;
26278 the general format is
26279 @smallexample
26280 Type'Asm_Output (constraint_string, variable_name)
26281 @end smallexample
26283 The constraint string directs the compiler how
26284 to store/access the associated variable.  In the example
26285 @smallexample
26286 Unsigned_32'Asm_Output ("=m", Flags);
26287 @end smallexample
26288 the @code{"m"} (memory) constraint tells the compiler that the variable
26289 @code{Flags} should be stored in a memory variable, thus preventing
26290 the optimizer from keeping it in a register.  In contrast,
26291 @smallexample
26292 Unsigned_32'Asm_Output ("=r", Flags);
26293 @end smallexample
26294 uses the @code{"r"} (register) constraint, telling the compiler to
26295 store the variable in a register.
26297 If the constraint is preceded by the equal character (@strong{=}), it tells
26298 the compiler that the variable will be used to store data into it.
26300 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
26301 allowing the optimizer to choose whatever it deems best.
26303 There are a fairly large number of constraints, but the ones that are
26304 most useful (for the Intel x86 processor) are the following:
26306 @table @code
26307 @item =
26308 output constraint
26309 @item g
26310 global (i.e.@: can be stored anywhere)
26311 @item m
26312 in memory
26313 @item I
26314 a constant
26315 @item a
26316 use eax
26317 @item b
26318 use ebx
26319 @item c
26320 use ecx
26321 @item d
26322 use edx
26323 @item S
26324 use esi
26325 @item D
26326 use edi
26327 @item r
26328 use one of eax, ebx, ecx or edx
26329 @item q
26330 use one of eax, ebx, ecx, edx, esi or edi
26331 @end table
26333 The full set of constraints is described in the gcc and @emph{as}
26334 documentation; note that it is possible to combine certain constraints
26335 in one constraint string.
26337 You specify the association of an output variable with an assembler operand
26338 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
26339 integer.  Thus in
26340 @smallexample @c ada
26341 @group
26342 Asm ("pushfl"          & LF & HT & --@i{ push flags on stack}
26343      "popl %%eax"      & LF & HT & --@i{ load eax with flags}
26344      "movl %%eax, %0",             --@i{ store flags in variable}
26345      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26346 @end group
26347 @end smallexample
26348 @noindent
26349 @code{%0} will be replaced in the expanded code by the appropriate operand,
26350 whatever
26351 the compiler decided for the @code{Flags} variable.
26353 In general, you may have any number of output variables:
26354 @itemize @bullet
26355 @item
26356 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26357 @item
26358 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26359 of @code{Asm_Output} attributes
26360 @end itemize
26362 For example:
26363 @smallexample @c ada
26364 @group
26365 Asm ("movl %%eax, %0" & LF & HT &
26366      "movl %%ebx, %1" & LF & HT &
26367      "movl %%ecx, %2",
26368      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --@i{  %0 = Var_A}
26369                  Unsigned_32'Asm_Output ("=g", Var_B),   --@i{  %1 = Var_B}
26370                  Unsigned_32'Asm_Output ("=g", Var_C))); --@i{  %2 = Var_C}
26371 @end group
26372 @end smallexample
26373 @noindent
26374 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26375 in the Ada program.
26377 As a variation on the @code{Get_Flags} example, we can use the constraints
26378 string to direct the compiler to store the eax register into the @code{Flags}
26379 variable, instead of including the store instruction explicitly in the
26380 @code{Asm} template string:
26382 @smallexample @c ada
26383 @group
26384 @b{with} Interfaces; @b{use} Interfaces;
26385 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26386 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26387 @b{procedure} Get_Flags_2 @b{is}
26388    Flags : Unsigned_32;
26389    @b{use} ASCII;
26390 @b{begin}
26391    Asm ("pushfl"      & LF & HT & --@i{ push flags on stack}
26392         "popl %%eax",             --@i{ save flags in eax}
26393         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26394    Put_Line ("Flags register:" & Flags'Img);
26395 @b{end} Get_Flags_2;
26396 @end group
26397 @end smallexample
26399 @noindent
26400 The @code{"a"} constraint tells the compiler that the @code{Flags}
26401 variable will come from the eax register. Here is the resulting code:
26403 @smallexample
26404 @group
26405 #APP
26406    pushfl
26407    popl %eax
26408 #NO_APP
26409    movl %eax,-40(%ebp)
26410 @end group
26411 @end smallexample
26413 @noindent
26414 The compiler generated the store of eax into Flags after
26415 expanding the assembler code.
26417 Actually, there was no need to pop the flags into the eax register;
26418 more simply, we could just pop the flags directly into the program variable:
26420 @smallexample @c ada
26421 @group
26422 @b{with} Interfaces; @b{use} Interfaces;
26423 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26424 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26425 @b{procedure} Get_Flags_3 @b{is}
26426    Flags : Unsigned_32;
26427    @b{use} ASCII;
26428 @b{begin}
26429    Asm ("pushfl"  & LF & HT & --@i{ push flags on stack}
26430         "pop %0",             --@i{ save flags in Flags}
26431         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26432    Put_Line ("Flags register:" & Flags'Img);
26433 @b{end} Get_Flags_3;
26434 @end group
26435 @end smallexample
26437 @c ---------------------------------------------------------------------------
26438 @node Input Variables in Inline Assembler
26439 @section Input Variables in Inline Assembler
26441 @noindent
26442 The example in this section illustrates how to specify the source operands
26443 for assembly language statements.
26444 The program simply increments its input value by 1:
26446 @smallexample @c ada
26447 @group
26448 @b{with} Interfaces; @b{use} Interfaces;
26449 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26450 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26451 @b{procedure} Increment @b{is}
26453    @b{function} Incr (Value : Unsigned_32) @b{return} Unsigned_32 @b{is}
26454       Result : Unsigned_32;
26455    @b{begin}
26456       Asm ("incl %0",
26457            Outputs => Unsigned_32'Asm_Output ("=a", Result),
26458            Inputs  => Unsigned_32'Asm_Input ("a", Value));
26459       @b{return} Result;
26460    @b{end} Incr;
26462    Value : Unsigned_32;
26464 @b{begin}
26465    Value := 5;
26466    Put_Line ("Value before is" & Value'Img);
26467    Value := Incr (Value);
26468    Put_Line ("Value after is" & Value'Img);
26469 @b{end} Increment;
26470 @end group
26471 @end smallexample
26473 The @code{Outputs} parameter to @code{Asm} specifies
26474 that the result will be in the eax register and that it is to be stored
26475 in the @code{Result} variable.
26477 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26478 but with an @code{Asm_Input} attribute.
26479 The @code{"="} constraint, indicating an output value, is not present.
26481 You can have multiple input variables, in the same way that you can have more
26482 than one output variable.
26484 The parameter count (%0, %1) etc, still starts at the first output statement,
26485 and continues with the input statements.
26487 Just as the @code{Outputs} parameter causes the register to be stored into the
26488 target variable after execution of the assembler statements, so does the
26489 @code{Inputs} parameter cause its variable to be loaded into the register
26490 before execution of the assembler statements.
26492 Thus the effect of the @code{Asm} invocation is:
26493 @enumerate
26494 @item load the 32-bit value of @code{Value} into eax
26495 @item execute the @code{incl %eax} instruction
26496 @item store the contents of eax into the @code{Result} variable
26497 @end enumerate
26499 The resulting assembler file (with @option{-O2} optimization) contains:
26500 @smallexample
26501 @group
26502 _increment__incr.1:
26503    subl $4,%esp
26504    movl 8(%esp),%eax
26505 #APP
26506    incl %eax
26507 #NO_APP
26508    movl %eax,%edx
26509    movl %ecx,(%esp)
26510    addl $4,%esp
26511    ret
26512 @end group
26513 @end smallexample
26515 @c ---------------------------------------------------------------------------
26516 @node Inlining Inline Assembler Code
26517 @section Inlining Inline Assembler Code
26519 @noindent
26520 For a short subprogram such as the @code{Incr} function in the previous
26521 section, the overhead of the call and return (creating / deleting the stack
26522 frame) can be significant, compared to the amount of code in the subprogram
26523 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26524 which directs the compiler to expand invocations of the subprogram at the
26525 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26526 Here is the resulting program:
26528 @smallexample @c ada
26529 @group
26530 @b{with} Interfaces; @b{use} Interfaces;
26531 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26532 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26533 @b{procedure} Increment_2 @b{is}
26535    @b{function} Incr (Value : Unsigned_32) @b{return} Unsigned_32 @b{is}
26536       Result : Unsigned_32;
26537    @b{begin}
26538       Asm ("incl %0",
26539            Outputs => Unsigned_32'Asm_Output ("=a", Result),
26540            Inputs  => Unsigned_32'Asm_Input ("a", Value));
26541       @b{return} Result;
26542    @b{end} Incr;
26543    @b{pragma} Inline (Increment);
26545    Value : Unsigned_32;
26547 @b{begin}
26548    Value := 5;
26549    Put_Line ("Value before is" & Value'Img);
26550    Value := Increment (Value);
26551    Put_Line ("Value after is" & Value'Img);
26552 @b{end} Increment_2;
26553 @end group
26554 @end smallexample
26556 Compile the program with both optimization (@option{-O2}) and inlining
26557 (@option{-gnatn}) enabled.
26559 The @code{Incr} function is still compiled as usual, but at the
26560 point in @code{Increment} where our function used to be called:
26562 @smallexample
26563 @group
26564 pushl %edi
26565 call _increment__incr.1
26566 @end group
26567 @end smallexample
26569 @noindent
26570 the code for the function body directly appears:
26572 @smallexample
26573 @group
26574 movl %esi,%eax
26575 #APP
26576    incl %eax
26577 #NO_APP
26578    movl %eax,%edx
26579 @end group
26580 @end smallexample
26582 @noindent
26583 thus saving the overhead of stack frame setup and an out-of-line call.
26585 @c ---------------------------------------------------------------------------
26586 @node Other Asm Functionality
26587 @section Other @code{Asm} Functionality
26589 @noindent
26590 This section describes two important parameters to the @code{Asm}
26591 procedure: @code{Clobber}, which identifies register usage;
26592 and @code{Volatile}, which inhibits unwanted optimizations.
26594 @menu
26595 * The Clobber Parameter::
26596 * The Volatile Parameter::
26597 @end menu
26599 @c ---------------------------------------------------------------------------
26600 @node The Clobber Parameter
26601 @subsection The @code{Clobber} Parameter
26603 @noindent
26604 One of the dangers of intermixing assembly language and a compiled language
26605 such as Ada is that the compiler needs to be aware of which registers are
26606 being used by the assembly code.  In some cases, such as the earlier examples,
26607 the constraint string is sufficient to indicate register usage (e.g.,
26608 @code{"a"} for
26609 the eax register).  But more generally, the compiler needs an explicit
26610 identification of the registers that are used by the Inline Assembly
26611 statements.
26613 Using a register that the compiler doesn't know about
26614 could be a side effect of an instruction (like @code{mull}
26615 storing its result in both eax and edx).
26616 It can also arise from explicit register usage in your
26617 assembly code; for example:
26618 @smallexample
26619 @group
26620 Asm ("movl %0, %%ebx" & LF & HT &
26621      "movl %%ebx, %1",
26622      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26623      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
26624 @end group
26625 @end smallexample
26626 @noindent
26627 where the compiler (since it does not analyze the @code{Asm} template string)
26628 does not know you are using the ebx register.
26630 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26631 to identify the registers that will be used by your assembly code:
26633 @smallexample
26634 @group
26635 Asm ("movl %0, %%ebx" & LF & HT &
26636      "movl %%ebx, %1",
26637      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26638      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26639      Clobber => "ebx");
26640 @end group
26641 @end smallexample
26643 The Clobber parameter is a static string expression specifying the
26644 register(s) you are using.  Note that register names are @emph{not} prefixed
26645 by a percent sign. Also, if more than one register is used then their names
26646 are separated by commas; e.g., @code{"eax, ebx"}
26648 The @code{Clobber} parameter has several additional uses:
26649 @enumerate
26650 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26651 @item Use ``register'' name @code{memory} if you changed a memory location
26652 @end enumerate
26654 @c ---------------------------------------------------------------------------
26655 @node The Volatile Parameter
26656 @subsection The @code{Volatile} Parameter
26657 @cindex Volatile parameter
26659 @noindent
26660 Compiler optimizations in the presence of Inline Assembler may sometimes have
26661 unwanted effects.  For example, when an @code{Asm} invocation with an input
26662 variable is inside a loop, the compiler might move the loading of the input
26663 variable outside the loop, regarding it as a one-time initialization.
26665 If this effect is not desired, you can disable such optimizations by setting
26666 the @code{Volatile} parameter to @code{True}; for example:
26668 @smallexample @c ada
26669 @group
26670 Asm ("movl %0, %%ebx" & LF & HT &
26671      "movl %%ebx, %1",
26672      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26673      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26674      Clobber  => "ebx",
26675      Volatile => True);
26676 @end group
26677 @end smallexample
26679 By default, @code{Volatile} is set to @code{False} unless there is no
26680 @code{Outputs} parameter.
26682 Although setting @code{Volatile} to @code{True} prevents unwanted
26683 optimizations, it will also disable other optimizations that might be
26684 important for efficiency. In general, you should set @code{Volatile}
26685 to @code{True} only if the compiler's optimizations have created
26686 problems.
26687 @c END OF INLINE ASSEMBLER CHAPTER
26688 @c ===============================
26691 @c *****************************************
26692 @c Writing Portable Fixed-Point Declarations
26693 @c *****************************************
26694 @node Writing Portable Fixed-Point Declarations
26695 @appendix Writing Portable Fixed-Point Declarations
26696 @cindex Fixed-point types (writing portable declarations)
26698 @noindent
26699 The Ada Reference Manual gives an implementation freedom to choose bounds
26700 that are narrower by @code{Small} from the given bounds.
26701 For example, if we write
26703 @smallexample @c ada
26704    type F1 is delta 1.0 range -128.0 .. +128.0;
26705 @end smallexample
26707 @noindent
26708 then the implementation is allowed to choose -128.0 .. +127.0 if it
26709 likes, but is not required to do so.
26711 This leads to possible portability problems, so let's have a closer
26712 look at this, and figure out how to avoid these problems.
26714 First, why does this freedom exist, and why would an implementation
26715 take advantage of it? To answer this, take a closer look at the type
26716 declaration for @code{F1} above. If the compiler uses the given bounds,
26717 it would need 9 bits to hold the largest positive value (and typically
26718 that means 16 bits on all machines). But if the implementation chooses
26719 the +127.0 bound then it can fit values of the type in 8 bits.
26721 Why not make the user write +127.0 if that's what is wanted?
26722 The rationale is that if you are thinking of fixed point
26723 as a kind of ``poor man's floating-point'', then you don't want
26724 to be thinking about the scaled integers that are used in its
26725 representation. Let's take another example:
26727 @smallexample @c ada
26728    type F2 is delta 2.0**(-15) range -1.0 .. +1.0;
26729 @end smallexample
26731 @noindent
26732 Looking at this declaration, it seems casually as though
26733 it should fit in 16 bits, but again that extra positive value
26734 +1.0 has the scaled integer equivalent of 2**15 which is one too
26735 big for signed 16 bits. The implementation can treat this as:
26737 @smallexample @c ada
26738    type F2 is delta 2.0**(-15) range -1.0 .. +1.0-(2.0**(-15));
26739 @end smallexample
26741 @noindent
26742 and the Ada language design team felt that this was too annoying
26743 to require. We don't need to debate this decision at this point,
26744 since it is well established (the rule about narrowing the ranges
26745 dates to Ada 83).
26747 But the important point is that an implementation is not required
26748 to do this narrowing, so we have a potential portability problem.
26749 We could imagine three types of implementation:
26751 @enumerate a
26752 @item
26753 those that narrow the range automatically if they can figure
26754 out that the narrower range will allow storage in a smaller machine unit,
26756 @item
26757 those that will narrow only if forced to by a @code{'Size} clause, and
26759 @item
26760 those that will never narrow.
26761 @end enumerate
26763 @noindent
26764 Now if we are language theoreticians, we can imagine a fourth
26765 approach: is to narrow all the time, e.g. to treat
26767 @smallexample @c ada
26768    type F3 is delta 1.0 range -10.0 .. +23.0;
26769 @end smallexample
26771 @noindent
26772 as though it had been written:
26774 @smallexample @c ada
26775    type F3 is delta 1.0 range -9.0 .. +22.0;
26776 @end smallexample
26778 @noindent
26779 But although technically allowed, such a behavior would be hostile and silly,
26780 and no real compiler would do this. All real compilers will fall into one of
26781 the categories (a), (b) or (c) above.
26783 So, how do you get the compiler to do what you want? The answer is give the
26784 actual bounds you want, and then use a @code{'Small} clause and a
26785 @code{'Size} clause to absolutely pin down what the compiler does.
26786 E.g., for @code{F2} above, we will write:
26788 @smallexample @c ada
26789 @group
26790    My_Small : constant := 2.0**(-15);
26791    My_First : constant := -1.0;
26792    My_Last  : constant := +1.0 - My_Small;
26794    type F2 is delta My_Small range My_First .. My_Last;
26795 @end group
26796 @end smallexample
26798 @noindent
26799 and then add
26801 @smallexample @c ada
26802 @group
26803    for F2'Small use my_Small;
26804    for F2'Size  use 16;
26805 @end group
26806 @end smallexample
26808 @noindent
26809 In practice all compilers will do the same thing here and will give you
26810 what you want, so the above declarations are fully portable. If you really
26811 want to play language lawyer and guard against ludicrous behavior by the
26812 compiler you could add
26814 @smallexample @c ada
26815 @group
26816    Test1 : constant := 1 / Boolean'Pos (F2'First = My_First);
26817    Test2 : constant := 1 / Boolean'Pos (F2'Last  = My_Last);
26818 @end group
26819 @end smallexample
26821 @noindent
26822 One or other or both are allowed to be illegal if the compiler is
26823 behaving in a silly manner, but at least the silly compiler will not
26824 get away with silently messing with your (very clear) intentions.
26826 If you follow this scheme you will be guaranteed that your fixed-point
26827 types will be portable.
26830 @c ***********************************
26831 @c * Compatibility and Porting Guide *
26832 @c ***********************************
26833 @node Compatibility and Porting Guide
26834 @appendix Compatibility and Porting Guide
26836 @noindent
26837 This chapter describes the compatibility issues that may arise between
26838 GNAT and other Ada compilation systems (including those for Ada 83),
26839 and shows how GNAT can expedite porting
26840 applications developed in other Ada environments.
26842 @menu
26843 * Compatibility with Ada 83::
26844 * Compatibility between Ada 95 and Ada 2005::
26845 * Implementation-dependent characteristics::
26846 * Compatibility with Other Ada Systems::
26847 * Representation Clauses::
26848 @c Brief section is only in non-VMS version
26849 @c Full chapter is in VMS version
26850 * Compatibility with HP Ada 83::
26851 @end menu
26853 @node Compatibility with Ada 83
26854 @section Compatibility with Ada 83
26855 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26857 @noindent
26858 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
26859 particular, the design intention was that the difficulties associated
26860 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26861 that occur when moving from one Ada 83 system to another.
26863 However, there are a number of points at which there are minor
26864 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26865 full details of these issues,
26866 and should be consulted for a complete treatment.
26867 In practice the
26868 following subsections treat the most likely issues to be encountered.
26870 @menu
26871 * Legal Ada 83 programs that are illegal in Ada 95::
26872 * More deterministic semantics::
26873 * Changed semantics::
26874 * Other language compatibility issues::
26875 @end menu
26877 @node Legal Ada 83 programs that are illegal in Ada 95
26878 @subsection Legal Ada 83 programs that are illegal in Ada 95
26880 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26881 Ada 95 and thus also in Ada 2005:
26883 @table @emph
26884 @item Character literals
26885 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26886 @code{Wide_Character} as a new predefined character type, some uses of
26887 character literals that were legal in Ada 83 are illegal in Ada 95.
26888 For example:
26889 @smallexample @c ada
26890    @b{for} Char @b{in} 'A' .. 'Z' @b{loop} @dots{} @b{end} @b{loop};
26891 @end smallexample
26893 @noindent
26894 The problem is that @code{'A'} and @code{'Z'} could be from either
26895 @code{Character} or @code{Wide_Character}.  The simplest correction
26896 is to make the type explicit; e.g.:
26897 @smallexample @c ada
26898    @b{for} Char @b{in} Character @b{range} 'A' .. 'Z' @b{loop} @dots{} @b{end} @b{loop};
26899 @end smallexample
26901 @item New reserved words
26902 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26903 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26904 Existing Ada 83 code using any of these identifiers must be edited to
26905 use some alternative name.
26907 @item Freezing rules
26908 The rules in Ada 95 are slightly different with regard to the point at
26909 which entities are frozen, and representation pragmas and clauses are
26910 not permitted past the freeze point.  This shows up most typically in
26911 the form of an error message complaining that a representation item
26912 appears too late, and the appropriate corrective action is to move
26913 the item nearer to the declaration of the entity to which it refers.
26915 A particular case is that representation pragmas
26916 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26917 declaration must be introduced to which the pragma can be applied.
26919 @item Optional bodies for library packages
26920 In Ada 83, a package that did not require a package body was nevertheless
26921 allowed to have one.  This lead to certain surprises in compiling large
26922 systems (situations in which the body could be unexpectedly ignored by the
26923 binder).  In Ada 95, if a package does not require a body then it is not
26924 permitted to have a body.  To fix this problem, simply remove a redundant
26925 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26926 into the spec that makes the body required.  One approach is to add a private
26927 part to the package declaration (if necessary), and define a parameterless
26928 procedure called @code{Requires_Body}, which must then be given a dummy
26929 procedure body in the package body, which then becomes required.
26930 Another approach (assuming that this does not introduce elaboration
26931 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26932 since one effect of this pragma is to require the presence of a package body.
26934 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26935 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26936 @code{Constraint_Error}.
26937 This means that it is illegal to have separate exception handlers for
26938 the two exceptions.  The fix is simply to remove the handler for the
26939 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26940 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26942 @item Indefinite subtypes in generics
26943 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26944 as the actual for a generic formal private type, but then the instantiation
26945 would be illegal if there were any instances of declarations of variables
26946 of this type in the generic body.  In Ada 95, to avoid this clear violation
26947 of the methodological principle known as the ``contract model'',
26948 the generic declaration explicitly indicates whether
26949 or not such instantiations are permitted.  If a generic formal parameter
26950 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26951 subtype name, then it can be instantiated with indefinite types, but no
26952 stand-alone variables can be declared of this type.  Any attempt to declare
26953 such a variable will result in an illegality at the time the generic is
26954 declared.  If the @code{(<>)} notation is not used, then it is illegal
26955 to instantiate the generic with an indefinite type.
26956 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26957 It will show up as a compile time error, and
26958 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26959 @end table
26961 @node More deterministic semantics
26962 @subsection More deterministic semantics
26964 @table @emph
26965 @item Conversions
26966 Conversions from real types to integer types round away from 0.  In Ada 83
26967 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26968 implementation freedom was intended to support unbiased rounding in
26969 statistical applications, but in practice it interfered with portability.
26970 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26971 is required.  Numeric code may be affected by this change in semantics.
26972 Note, though, that this issue is no worse than already existed in Ada 83
26973 when porting code from one vendor to another.
26975 @item Tasking
26976 The Real-Time Annex introduces a set of policies that define the behavior of
26977 features that were implementation dependent in Ada 83, such as the order in
26978 which open select branches are executed.
26979 @end table
26981 @node Changed semantics
26982 @subsection Changed semantics
26984 @noindent
26985 The worst kind of incompatibility is one where a program that is legal in
26986 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26987 possible in Ada 83.  Fortunately this is extremely rare, but the one
26988 situation that you should be alert to is the change in the predefined type
26989 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26991 @table @emph
26992 @item Range of type @code{Character}
26993 The range of @code{Standard.Character} is now the full 256 characters
26994 of Latin-1, whereas in most Ada 83 implementations it was restricted
26995 to 128 characters. Although some of the effects of
26996 this change will be manifest in compile-time rejection of legal
26997 Ada 83 programs it is possible for a working Ada 83 program to have
26998 a different effect in Ada 95, one that was not permitted in Ada 83.
26999 As an example, the expression
27000 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
27001 delivers @code{255} as its value.
27002 In general, you should look at the logic of any
27003 character-processing Ada 83 program and see whether it needs to be adapted
27004 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
27005 character handling package that may be relevant if code needs to be adapted
27006 to account for the additional Latin-1 elements.
27007 The desirable fix is to
27008 modify the program to accommodate the full character set, but in some cases
27009 it may be convenient to define a subtype or derived type of Character that
27010 covers only the restricted range.
27011 @cindex Latin-1
27012 @end table
27014 @node Other language compatibility issues
27015 @subsection Other language compatibility issues
27017 @table @emph
27018 @item @option{-gnat83} switch
27019 All implementations of GNAT provide a switch that causes GNAT to operate
27020 in Ada 83 mode.  In this mode, some but not all compatibility problems
27021 of the type described above are handled automatically.  For example, the
27022 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
27023 as identifiers as in Ada 83.
27024 However,
27025 in practice, it is usually advisable to make the necessary modifications
27026 to the program to remove the need for using this switch.
27027 See @ref{Compiling Different Versions of Ada}.
27029 @item Support for removed Ada 83 pragmas and attributes
27030 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
27031 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
27032 compilers are allowed, but not required, to implement these missing
27033 elements.  In contrast with some other compilers, GNAT implements all
27034 such pragmas and attributes, eliminating this compatibility concern.  These
27035 include @code{pragma Interface} and the floating point type attributes
27036 (@code{Emax}, @code{Mantissa}, etc.), among other items.
27037 @end table
27040 @node Compatibility between Ada 95 and Ada 2005
27041 @section Compatibility between Ada 95 and Ada 2005
27042 @cindex Compatibility between Ada 95 and Ada 2005
27044 @noindent
27045 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
27046 a number of incompatibilities. Several are enumerated below;
27047 for a complete description please see the
27048 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
27049 @cite{Rationale for Ada 2005}.
27051 @table @emph
27052 @item New reserved words.
27053 The words @code{interface}, @code{overriding} and @code{synchronized} are
27054 reserved in Ada 2005.
27055 A pre-Ada 2005 program that uses any of these as an identifier will be
27056 illegal.
27058 @item New declarations in predefined packages.
27059 A number of packages in the predefined environment contain new declarations:
27060 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
27061 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
27062 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
27063 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
27064 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
27065 If an Ada 95 program does a @code{with} and @code{use} of any of these
27066 packages, the new declarations may cause name clashes.
27068 @item Access parameters.
27069 A nondispatching subprogram with an access parameter cannot be renamed
27070 as a dispatching operation.  This was permitted in Ada 95.
27072 @item Access types, discriminants, and constraints.
27073 Rule changes in this area have led to some incompatibilities; for example,
27074 constrained subtypes of some access types are not permitted in Ada 2005.
27076 @item Aggregates for limited types.
27077 The allowance of aggregates for limited types in Ada 2005 raises the
27078 possibility of ambiguities in legal Ada 95 programs, since additional types
27079 now need to be considered in expression resolution.
27081 @item Fixed-point multiplication and division.
27082 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
27083 were legal in Ada 95 and invoked the predefined versions of these operations,
27084 are now ambiguous.
27085 The ambiguity may be resolved either by applying a type conversion to the
27086 expression, or by explicitly invoking the operation from package
27087 @code{Standard}.
27089 @item Return-by-reference types.
27090 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
27091 can declare a function returning a value from an anonymous access type.
27092 @end table
27095 @node Implementation-dependent characteristics
27096 @section Implementation-dependent characteristics
27097 @noindent
27098 Although the Ada language defines the semantics of each construct as
27099 precisely as practical, in some situations (for example for reasons of
27100 efficiency, or where the effect is heavily dependent on the host or target
27101 platform) the implementation is allowed some freedom.  In porting Ada 83
27102 code to GNAT, you need to be aware of whether / how the existing code
27103 exercised such implementation dependencies.  Such characteristics fall into
27104 several categories, and GNAT offers specific support in assisting the
27105 transition from certain Ada 83 compilers.
27107 @menu
27108 * Implementation-defined pragmas::
27109 * Implementation-defined attributes::
27110 * Libraries::
27111 * Elaboration order::
27112 * Target-specific aspects::
27113 @end menu
27115 @node Implementation-defined pragmas
27116 @subsection Implementation-defined pragmas
27118 @noindent
27119 Ada compilers are allowed to supplement the language-defined pragmas, and
27120 these are a potential source of non-portability.  All GNAT-defined pragmas
27121 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
27122 Reference Manual}, and these include several that are specifically
27123 intended to correspond to other vendors' Ada 83 pragmas.
27124 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
27125 For compatibility with HP Ada 83, GNAT supplies the pragmas
27126 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
27127 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
27128 and @code{Volatile}.
27129 Other relevant pragmas include @code{External} and @code{Link_With}.
27130 Some vendor-specific
27131 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
27132 recognized, thus
27133 avoiding compiler rejection of units that contain such pragmas; they are not
27134 relevant in a GNAT context and hence are not otherwise implemented.
27136 @node Implementation-defined attributes
27137 @subsection Implementation-defined attributes
27139 Analogous to pragmas, the set of attributes may be extended by an
27140 implementation.  All GNAT-defined attributes are described in
27141 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
27142 Manual}, and these include several that are specifically intended
27143 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
27144 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
27145 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
27146 @code{Type_Class}.
27148 @node Libraries
27149 @subsection Libraries
27150 @noindent
27151 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
27152 code uses vendor-specific libraries then there are several ways to manage
27153 this in Ada 95 or Ada 2005:
27154 @enumerate
27155 @item
27156 If the source code for the libraries (specs and bodies) are
27157 available, then the libraries can be migrated in the same way as the
27158 application.
27159 @item
27160 If the source code for the specs but not the bodies are
27161 available, then you can reimplement the bodies.
27162 @item
27163 Some features introduced by Ada 95 obviate the need for library support.  For
27164 example most Ada 83 vendors supplied a package for unsigned integers.  The
27165 Ada 95 modular type feature is the preferred way to handle this need, so
27166 instead of migrating or reimplementing the unsigned integer package it may
27167 be preferable to retrofit the application using modular types.
27168 @end enumerate
27170 @node Elaboration order
27171 @subsection Elaboration order
27172 @noindent
27173 The implementation can choose any elaboration order consistent with the unit
27174 dependency relationship.  This freedom means that some orders can result in
27175 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
27176 to invoke a subprogram its body has been elaborated, or to instantiate a
27177 generic before the generic body has been elaborated.  By default GNAT
27178 attempts to choose a safe order (one that will not encounter access before
27179 elaboration problems) by implicitly inserting @code{Elaborate} or
27180 @code{Elaborate_All} pragmas where
27181 needed.  However, this can lead to the creation of elaboration circularities
27182 and a resulting rejection of the program by gnatbind.  This issue is
27183 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
27184 In brief, there are several
27185 ways to deal with this situation:
27187 @itemize @bullet
27188 @item
27189 Modify the program to eliminate the circularities, e.g.@: by moving
27190 elaboration-time code into explicitly-invoked procedures
27191 @item
27192 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
27193 @code{Elaborate} pragmas, and then inhibit the generation of implicit
27194 @code{Elaborate_All}
27195 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
27196 (by selectively suppressing elaboration checks via pragma
27197 @code{Suppress(Elaboration_Check)} when it is safe to do so).
27198 @end itemize
27200 @node Target-specific aspects
27201 @subsection Target-specific aspects
27202 @noindent
27203 Low-level applications need to deal with machine addresses, data
27204 representations, interfacing with assembler code, and similar issues.  If
27205 such an Ada 83 application is being ported to different target hardware (for
27206 example where the byte endianness has changed) then you will need to
27207 carefully examine the program logic; the porting effort will heavily depend
27208 on the robustness of the original design.  Moreover, Ada 95 (and thus
27209 Ada 2005) are sometimes
27210 incompatible with typical Ada 83 compiler practices regarding implicit
27211 packing, the meaning of the Size attribute, and the size of access values.
27212 GNAT's approach to these issues is described in @ref{Representation Clauses}.
27214 @node Compatibility with Other Ada Systems
27215 @section Compatibility with Other Ada Systems
27217 @noindent
27218 If programs avoid the use of implementation dependent and
27219 implementation defined features, as documented in the @cite{Ada
27220 Reference Manual}, there should be a high degree of portability between
27221 GNAT and other Ada systems.  The following are specific items which
27222 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
27223 compilers, but do not affect porting code to GNAT@.
27224 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
27225 the following issues may or may not arise for Ada 2005 programs
27226 when other compilers appear.)
27228 @table @emph
27229 @item Ada 83 Pragmas and Attributes
27230 Ada 95 compilers are allowed, but not required, to implement the missing
27231 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
27232 GNAT implements all such pragmas and attributes, eliminating this as
27233 a compatibility concern, but some other Ada 95 compilers reject these
27234 pragmas and attributes.
27236 @item Specialized Needs Annexes
27237 GNAT implements the full set of special needs annexes.  At the
27238 current time, it is the only Ada 95 compiler to do so.  This means that
27239 programs making use of these features may not be portable to other Ada
27240 95 compilation systems.
27242 @item Representation Clauses
27243 Some other Ada 95 compilers implement only the minimal set of
27244 representation clauses required by the Ada 95 reference manual.  GNAT goes
27245 far beyond this minimal set, as described in the next section.
27246 @end table
27248 @node Representation Clauses
27249 @section Representation Clauses
27251 @noindent
27252 The Ada 83 reference manual was quite vague in describing both the minimal
27253 required implementation of representation clauses, and also their precise
27254 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
27255 minimal set of capabilities required is still quite limited.
27257 GNAT implements the full required set of capabilities in
27258 Ada 95 and Ada 2005, but also goes much further, and in particular
27259 an effort has been made to be compatible with existing Ada 83 usage to the
27260 greatest extent possible.
27262 A few cases exist in which Ada 83 compiler behavior is incompatible with
27263 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
27264 intentional or accidental dependence on specific implementation dependent
27265 characteristics of these Ada 83 compilers.  The following is a list of
27266 the cases most likely to arise in existing Ada 83 code.
27268 @table @emph
27269 @item Implicit Packing
27270 Some Ada 83 compilers allowed a Size specification to cause implicit
27271 packing of an array or record.  This could cause expensive implicit
27272 conversions for change of representation in the presence of derived
27273 types, and the Ada design intends to avoid this possibility.
27274 Subsequent AI's were issued to make it clear that such implicit
27275 change of representation in response to a Size clause is inadvisable,
27276 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
27277 Reference Manuals as implementation advice that is followed by GNAT@.
27278 The problem will show up as an error
27279 message rejecting the size clause.  The fix is simply to provide
27280 the explicit pragma @code{Pack}, or for more fine tuned control, provide
27281 a Component_Size clause.
27283 @item Meaning of Size Attribute
27284 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
27285 the minimal number of bits required to hold values of the type.  For example,
27286 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
27287 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
27288 some 32 in this situation.  This problem will usually show up as a compile
27289 time error, but not always.  It is a good idea to check all uses of the
27290 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
27291 Object_Size can provide a useful way of duplicating the behavior of
27292 some Ada 83 compiler systems.
27294 @item Size of Access Types
27295 A common assumption in Ada 83 code is that an access type is in fact a pointer,
27296 and that therefore it will be the same size as a System.Address value.  This
27297 assumption is true for GNAT in most cases with one exception.  For the case of
27298 a pointer to an unconstrained array type (where the bounds may vary from one
27299 value of the access type to another), the default is to use a ``fat pointer'',
27300 which is represented as two separate pointers, one to the bounds, and one to
27301 the array.  This representation has a number of advantages, including improved
27302 efficiency.  However, it may cause some difficulties in porting existing Ada 83
27303 code which makes the assumption that, for example, pointers fit in 32 bits on
27304 a machine with 32-bit addressing.
27306 To get around this problem, GNAT also permits the use of ``thin pointers'' for
27307 access types in this case (where the designated type is an unconstrained array
27308 type).  These thin pointers are indeed the same size as a System.Address value.
27309 To specify a thin pointer, use a size clause for the type, for example:
27311 @smallexample @c ada
27312 @b{type} X @b{is} @b{access} @b{all} String;
27313 @b{for} X'Size @b{use} Standard'Address_Size;
27314 @end smallexample
27316 @noindent
27317 which will cause the type X to be represented using a single pointer.
27318 When using this representation, the bounds are right behind the array.
27319 This representation is slightly less efficient, and does not allow quite
27320 such flexibility in the use of foreign pointers or in using the
27321 Unrestricted_Access attribute to create pointers to non-aliased objects.
27322 But for any standard portable use of the access type it will work in
27323 a functionally correct manner and allow porting of existing code.
27324 Note that another way of forcing a thin pointer representation
27325 is to use a component size clause for the element size in an array,
27326 or a record representation clause for an access field in a record.
27328 See the documentation of Unrestricted_Access in the GNAT RM for a
27329 full discussion of possible problems using this attribute in conjunction
27330 with thin pointers.
27331 @end table
27333 @c This brief section is only in the non-VMS version
27334 @c The complete chapter on HP Ada is in the VMS version
27335 @node Compatibility with HP Ada 83
27336 @section Compatibility with HP Ada 83
27338 @noindent
27339 The VMS version of GNAT fully implements all the pragmas and attributes
27340 provided by HP Ada 83, as well as providing the standard HP Ada 83
27341 libraries, including Starlet.  In addition, data layouts and parameter
27342 passing conventions are highly compatible.  This means that porting
27343 existing HP Ada 83 code to GNAT in VMS systems should be easier than
27344 most other porting efforts.  The following are some of the most
27345 significant differences between GNAT and HP Ada 83.
27347 @table @emph
27348 @item Default floating-point representation
27349 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
27350 it is VMS format.  GNAT does implement the necessary pragmas
27351 (Long_Float, Float_Representation) for changing this default.
27353 @item System
27354 The package System in GNAT exactly corresponds to the definition in the
27355 Ada 95 reference manual, which means that it excludes many of the
27356 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
27357 that contains the additional definitions, and a special pragma,
27358 Extend_System allows this package to be treated transparently as an
27359 extension of package System.
27361 @item To_Address
27362 The definitions provided by Aux_DEC are exactly compatible with those
27363 in the HP Ada 83 version of System, with one exception.
27364 HP Ada provides the following declarations:
27366 @smallexample @c ada
27367 TO_ADDRESS (INTEGER)
27368 TO_ADDRESS (UNSIGNED_LONGWORD)
27369 TO_ADDRESS (@i{universal_integer})
27370 @end smallexample
27372 @noindent
27373 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
27374 an extension to Ada 83 not strictly compatible with the reference manual.
27375 In GNAT, we are constrained to be exactly compatible with the standard,
27376 and this means we cannot provide this capability.  In HP Ada 83, the
27377 point of this definition is to deal with a call like:
27379 @smallexample @c ada
27380 TO_ADDRESS (16#12777#);
27381 @end smallexample
27383 @noindent
27384 Normally, according to the Ada 83 standard, one would expect this to be
27385 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
27386 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
27387 definition using @i{universal_integer} takes precedence.
27389 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
27390 is not possible to be 100% compatible.  Since there are many programs using
27391 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
27392 to change the name of the function in the UNSIGNED_LONGWORD case, so the
27393 declarations provided in the GNAT version of AUX_Dec are:
27395 @smallexample @c ada
27396 @b{function} To_Address (X : Integer) @b{return} Address;
27397 @b{pragma} Pure_Function (To_Address);
27399 @b{function} To_Address_Long (X : Unsigned_Longword)
27400  @b{return} Address;
27401 @b{pragma} Pure_Function (To_Address_Long);
27402 @end smallexample
27404 @noindent
27405 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
27406 change the name to TO_ADDRESS_LONG@.
27408 @item Task_Id values
27409 The Task_Id values assigned will be different in the two systems, and GNAT
27410 does not provide a specified value for the Task_Id of the environment task,
27411 which in GNAT is treated like any other declared task.
27412 @end table
27414 @noindent
27415 For full details on these and other less significant compatibility issues,
27416 see appendix E of the HP publication entitled @cite{HP Ada, Technical
27417 Overview and Comparison on HP Platforms}.
27419 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
27420 attributes are recognized, although only a subset of them can sensibly
27421 be implemented.  The description of pragmas in @ref{Implementation
27422 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
27423 indicates whether or not they are applicable to non-VMS systems.
27426 @c ************************************************
27427 @node Microsoft Windows Topics
27428 @appendix Microsoft Windows Topics
27429 @cindex Windows NT
27430 @cindex Windows 95
27431 @cindex Windows 98
27433 @noindent
27434 This chapter describes topics that are specific to the Microsoft Windows
27435 platforms (NT, 2000, and XP Professional).
27437 @menu
27438 @ifclear FSFEDITION
27439 * Installing from the Command Line::
27440 @end ifclear
27441 * Using GNAT on Windows::
27442 * Using a network installation of GNAT::
27443 * CONSOLE and WINDOWS subsystems::
27444 * Temporary Files::
27445 * Mixed-Language Programming on Windows::
27446 * Windows Calling Conventions::
27447 * Introduction to Dynamic Link Libraries (DLLs)::
27448 * Using DLLs with GNAT::
27449 * Building DLLs with GNAT Project files::
27450 * Building DLLs with GNAT::
27451 * Building DLLs with gnatdll::
27452 * GNAT and Windows Resources::
27453 * Debugging a DLL::
27454 * Setting Stack Size from gnatlink::
27455 * Setting Heap Size from gnatlink::
27456 @end menu
27458 @ifclear FSFEDITION
27459 @node Installing from the Command Line
27460 @section Installing from the Command Line
27461 @cindex Batch installation
27462 @cindex Silent installation
27463 @cindex Unassisted installation
27465 @noindent
27466 By default the @value{EDITION} installers display a GUI that prompts the user
27467 to enter installation path and similar information, and guide him through the
27468 installation process. It is also possible to perform silent installations
27469 using the command-line interface.
27471 In order to install one of the @value{EDITION} installers from the command
27472 line you should pass parameter @code{/S} (and, optionally,
27473 @code{/D=<directory>}) as command-line arguments.
27475 @ifset PROEDITION
27476 For example, for an unattended installation of
27477 @value{EDITION} 7.0.2 into the default directory
27478 @code{C:\GNATPRO\7.0.2} you would run:
27480 @smallexample
27481 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
27482 @end smallexample
27484 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
27486 @smallexample
27487 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
27488 @end smallexample
27489 @end ifset
27491 @ifset GPLEDITION
27492 For example, for an unattended installation of
27493 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
27495 @smallexample
27496 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
27497 @end smallexample
27498 @end ifset
27500 You can use the same syntax for all installers.
27502 Note that unattended installations don't modify system path, nor create file
27503 associations, so such activities need to be done by hand.
27504 @end ifclear
27506 @node Using GNAT on Windows
27507 @section Using GNAT on Windows
27509 @noindent
27510 One of the strengths of the GNAT technology is that its tool set
27511 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27512 @code{gdb} debugger, etc.) is used in the same way regardless of the
27513 platform.
27515 On Windows this tool set is complemented by a number of Microsoft-specific
27516 tools that have been provided to facilitate interoperability with Windows
27517 when this is required. With these tools:
27519 @itemize @bullet
27521 @item
27522 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27523 subsystems.
27525 @item
27526 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27527 relocatable and non-relocatable DLLs are supported).
27529 @item
27530 You can build Ada DLLs for use in other applications. These applications
27531 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27532 relocatable and non-relocatable Ada DLLs are supported.
27534 @item
27535 You can include Windows resources in your Ada application.
27537 @item
27538 You can use or create COM/DCOM objects.
27539 @end itemize
27541 @noindent
27542 Immediately below are listed all known general GNAT-for-Windows restrictions.
27543 Other restrictions about specific features like Windows Resources and DLLs
27544 are listed in separate sections below.
27546 @itemize @bullet
27548 @item
27549 It is not possible to use @code{GetLastError} and @code{SetLastError}
27550 when tasking, protected records, or exceptions are used. In these
27551 cases, in order to implement Ada semantics, the GNAT run-time system
27552 calls certain Win32 routines that set the last error variable to 0 upon
27553 success. It should be possible to use @code{GetLastError} and
27554 @code{SetLastError} when tasking, protected record, and exception
27555 features are not used, but it is not guaranteed to work.
27557 @item
27558 It is not possible to link against Microsoft C++ libraries except for
27559 import libraries. Interfacing must be done by the mean of DLLs.
27561 @item
27562 It is possible to link against Microsoft C libraries. Yet the preferred
27563 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
27564 doesn't require having two different development environments and makes the
27565 inter-language debugging experience smoother.
27567 @item
27568 When the compilation environment is located on FAT32 drives, users may
27569 experience recompilations of the source files that have not changed if
27570 Daylight Saving Time (DST) state has changed since the last time files
27571 were compiled. NTFS drives do not have this problem.
27573 @item
27574 No components of the GNAT toolset use any entries in the Windows
27575 registry. The only entries that can be created are file associations and
27576 PATH settings, provided the user has chosen to create them at installation
27577 time, as well as some minimal book-keeping information needed to correctly
27578 uninstall or integrate different GNAT products.
27579 @end itemize
27581 @node Using a network installation of GNAT
27582 @section Using a network installation of GNAT
27584 @noindent
27585 Make sure the system on which GNAT is installed is accessible from the
27586 current machine, i.e., the install location is shared over the network.
27587 Shared resources are accessed on Windows by means of UNC paths, which
27588 have the format @code{\\server\sharename\path}
27590 In order to use such a network installation, simply add the UNC path of the
27591 @file{bin} directory of your GNAT installation in front of your PATH. For
27592 example, if GNAT is installed in @file{\GNAT} directory of a share location
27593 called @file{c-drive} on a machine @file{LOKI}, the following command will
27594 make it available:
27596 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27598 Be aware that every compilation using the network installation results in the
27599 transfer of large amounts of data across the network and will likely cause
27600 serious performance penalty.
27602 @node CONSOLE and WINDOWS subsystems
27603 @section CONSOLE and WINDOWS subsystems
27604 @cindex CONSOLE Subsystem
27605 @cindex WINDOWS Subsystem
27606 @cindex -mwindows
27608 @noindent
27609 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27610 (which is the default subsystem) will always create a console when
27611 launching the application. This is not something desirable when the
27612 application has a Windows GUI. To get rid of this console the
27613 application must be using the @code{WINDOWS} subsystem. To do so
27614 the @option{-mwindows} linker option must be specified.
27616 @smallexample
27617 $ gnatmake winprog -largs -mwindows
27618 @end smallexample
27620 @node Temporary Files
27621 @section Temporary Files
27622 @cindex Temporary files
27624 @noindent
27625 It is possible to control where temporary files gets created by setting
27626 the @env{TMP} environment variable. The file will be created:
27628 @itemize
27629 @item Under the directory pointed to by the @env{TMP} environment variable if
27630 this directory exists.
27632 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27633 set (or not pointing to a directory) and if this directory exists.
27635 @item Under the current working directory otherwise.
27636 @end itemize
27638 @noindent
27639 This allows you to determine exactly where the temporary
27640 file will be created. This is particularly useful in networked
27641 environments where you may not have write access to some
27642 directories.
27644 @node Mixed-Language Programming on Windows
27645 @section Mixed-Language Programming on Windows
27647 @noindent
27648 Developing pure Ada applications on Windows is no different than on
27649 other GNAT-supported platforms. However, when developing or porting an
27650 application that contains a mix of Ada and C/C++, the choice of your
27651 Windows C/C++ development environment conditions your overall
27652 interoperability strategy.
27654 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
27655 your application, there are no Windows-specific restrictions that
27656 affect the overall interoperability with your Ada code. If you do want
27657 to use the Microsoft tools for your C++ code, you have two choices:
27659 @enumerate
27660 @item
27661 Encapsulate your C++ code in a DLL to be linked with your Ada
27662 application. In this case, use the Microsoft or whatever environment to
27663 build the DLL and use GNAT to build your executable
27664 (@pxref{Using DLLs with GNAT}).
27666 @item
27667 Or you can encapsulate your Ada code in a DLL to be linked with the
27668 other part of your application. In this case, use GNAT to build the DLL
27669 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27670 or whatever environment to build your executable.
27671 @end enumerate
27673 In addition to the description about C main in
27674 @pxref{Mixed Language Programming} section, if the C main uses a
27675 stand-alone library it is required on x86-windows to
27676 setup the SEH context. For this the C main must looks like this:
27678 @smallexample
27679 /* main.c */
27680 extern void adainit (void);
27681 extern void adafinal (void);
27682 extern void __gnat_initialize(void*);
27683 extern void call_to_ada (void);
27685 int main (int argc, char *argv[])
27687   int SEH [2];
27689   /* Initialize the SEH context */
27690   __gnat_initialize (&SEH);
27692   adainit();
27694   /* Then call Ada services in the stand-alone library */
27696   call_to_ada();
27698   adafinal();
27700 @end smallexample
27702 Note that this is not needed on x86_64-windows where the Windows
27703 native SEH support is used.
27705 @node Windows Calling Conventions
27706 @section Windows Calling Conventions
27707 @findex Stdcall
27708 @findex APIENTRY
27710 This section pertain only to Win32. On Win64 there is a single native
27711 calling convention. All convention specifiers are ignored on this
27712 platform.
27714 @menu
27715 * C Calling Convention::
27716 * Stdcall Calling Convention::
27717 * Win32 Calling Convention::
27718 * DLL Calling Convention::
27719 @end menu
27721 @noindent
27722 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27723 (callee), there are several ways to push @code{G}'s parameters on the
27724 stack and there are several possible scenarios to clean up the stack
27725 upon @code{G}'s return. A calling convention is an agreed upon software
27726 protocol whereby the responsibilities between the caller (@code{F}) and
27727 the callee (@code{G}) are clearly defined. Several calling conventions
27728 are available for Windows:
27730 @itemize @bullet
27731 @item
27732 @code{C} (Microsoft defined)
27734 @item
27735 @code{Stdcall} (Microsoft defined)
27737 @item
27738 @code{Win32} (GNAT specific)
27740 @item
27741 @code{DLL} (GNAT specific)
27742 @end itemize
27744 @node C Calling Convention
27745 @subsection @code{C} Calling Convention
27747 @noindent
27748 This is the default calling convention used when interfacing to C/C++
27749 routines compiled with either @command{gcc} or Microsoft Visual C++.
27751 In the @code{C} calling convention subprogram parameters are pushed on the
27752 stack by the caller from right to left. The caller itself is in charge of
27753 cleaning up the stack after the call. In addition, the name of a routine
27754 with @code{C} calling convention is mangled by adding a leading underscore.
27756 The name to use on the Ada side when importing (or exporting) a routine
27757 with @code{C} calling convention is the name of the routine. For
27758 instance the C function:
27760 @smallexample
27761 int get_val (long);
27762 @end smallexample
27764 @noindent
27765 should be imported from Ada as follows:
27767 @smallexample @c ada
27768 @group
27769 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27770 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
27771 @end group
27772 @end smallexample
27774 @noindent
27775 Note that in this particular case the @code{External_Name} parameter could
27776 have been omitted since, when missing, this parameter is taken to be the
27777 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27778 is missing, as in the above example, this parameter is set to be the
27779 @code{External_Name} with a leading underscore.
27781 When importing a variable defined in C, you should always use the @code{C}
27782 calling convention unless the object containing the variable is part of a
27783 DLL (in which case you should use the @code{Stdcall} calling
27784 convention, @pxref{Stdcall Calling Convention}).
27786 @node Stdcall Calling Convention
27787 @subsection @code{Stdcall} Calling Convention
27789 @noindent
27790 This convention, which was the calling convention used for Pascal
27791 programs, is used by Microsoft for all the routines in the Win32 API for
27792 efficiency reasons. It must be used to import any routine for which this
27793 convention was specified.
27795 In the @code{Stdcall} calling convention subprogram parameters are pushed
27796 on the stack by the caller from right to left. The callee (and not the
27797 caller) is in charge of cleaning the stack on routine exit. In addition,
27798 the name of a routine with @code{Stdcall} calling convention is mangled by
27799 adding a leading underscore (as for the @code{C} calling convention) and a
27800 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27801 bytes) of the parameters passed to the routine.
27803 The name to use on the Ada side when importing a C routine with a
27804 @code{Stdcall} calling convention is the name of the C routine. The leading
27805 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27806 the compiler. For instance the Win32 function:
27808 @smallexample
27809 @b{APIENTRY} int get_val (long);
27810 @end smallexample
27812 @noindent
27813 should be imported from Ada as follows:
27815 @smallexample @c ada
27816 @group
27817 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27818 @b{pragma} Import (Stdcall, Get_Val);
27819 --@i{  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"}
27820 @end group
27821 @end smallexample
27823 @noindent
27824 As for the @code{C} calling convention, when the @code{External_Name}
27825 parameter is missing, it is taken to be the name of the Ada entity in lower
27826 case. If instead of writing the above import pragma you write:
27828 @smallexample @c ada
27829 @group
27830 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27831 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27832 @end group
27833 @end smallexample
27835 @noindent
27836 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27837 of specifying the @code{External_Name} parameter you specify the
27838 @code{Link_Name} as in the following example:
27840 @smallexample @c ada
27841 @group
27842 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27843 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27844 @end group
27845 @end smallexample
27847 @noindent
27848 then the imported routine is @code{retrieve_val}, that is, there is no
27849 decoration at all. No leading underscore and no Stdcall suffix
27850 @code{@@}@code{@var{nn}}.
27852 @noindent
27853 This is especially important as in some special cases a DLL's entry
27854 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27855 name generated for a call has it.
27857 @noindent
27858 It is also possible to import variables defined in a DLL by using an
27859 import pragma for a variable. As an example, if a DLL contains a
27860 variable defined as:
27862 @smallexample
27863 int my_var;
27864 @end smallexample
27866 @noindent
27867 then, to access this variable from Ada you should write:
27869 @smallexample @c ada
27870 @group
27871 My_Var : Interfaces.C.int;
27872 @b{pragma} Import (Stdcall, My_Var);
27873 @end group
27874 @end smallexample
27876 @noindent
27877 Note that to ease building cross-platform bindings this convention
27878 will be handled as a @code{C} calling convention on non-Windows platforms.
27880 @node Win32 Calling Convention
27881 @subsection @code{Win32} Calling Convention
27883 @noindent
27884 This convention, which is GNAT-specific is fully equivalent to the
27885 @code{Stdcall} calling convention described above.
27887 @node DLL Calling Convention
27888 @subsection @code{DLL} Calling Convention
27890 @noindent
27891 This convention, which is GNAT-specific is fully equivalent to the
27892 @code{Stdcall} calling convention described above.
27894 @node Introduction to Dynamic Link Libraries (DLLs)
27895 @section Introduction to Dynamic Link Libraries (DLLs)
27896 @findex DLL
27898 @noindent
27899 A Dynamically Linked Library (DLL) is a library that can be shared by
27900 several applications running under Windows. A DLL can contain any number of
27901 routines and variables.
27903 One advantage of DLLs is that you can change and enhance them without
27904 forcing all the applications that depend on them to be relinked or
27905 recompiled. However, you should be aware than all calls to DLL routines are
27906 slower since, as you will understand below, such calls are indirect.
27908 To illustrate the remainder of this section, suppose that an application
27909 wants to use the services of a DLL @file{API.dll}. To use the services
27910 provided by @file{API.dll} you must statically link against the DLL or
27911 an import library which contains a jump table with an entry for each
27912 routine and variable exported by the DLL. In the Microsoft world this
27913 import library is called @file{API.lib}. When using GNAT this import
27914 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27915 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27917 After you have linked your application with the DLL or the import library
27918 and you run your application, here is what happens:
27920 @enumerate
27921 @item
27922 Your application is loaded into memory.
27924 @item
27925 The DLL @file{API.dll} is mapped into the address space of your
27926 application. This means that:
27928 @itemize @bullet
27929 @item
27930 The DLL will use the stack of the calling thread.
27932 @item
27933 The DLL will use the virtual address space of the calling process.
27935 @item
27936 The DLL will allocate memory from the virtual address space of the calling
27937 process.
27939 @item
27940 Handles (pointers) can be safely exchanged between routines in the DLL
27941 routines and routines in the application using the DLL.
27942 @end itemize
27944 @item
27945 The entries in the jump table (from the import library @file{libAPI.dll.a}
27946 or @file{API.lib} or automatically created when linking against a DLL)
27947 which is part of your application are initialized with the addresses
27948 of the routines and variables in @file{API.dll}.
27950 @item
27951 If present in @file{API.dll}, routines @code{DllMain} or
27952 @code{DllMainCRTStartup} are invoked. These routines typically contain
27953 the initialization code needed for the well-being of the routines and
27954 variables exported by the DLL.
27955 @end enumerate
27957 @noindent
27958 There is an additional point which is worth mentioning. In the Windows
27959 world there are two kind of DLLs: relocatable and non-relocatable
27960 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27961 in the target application address space. If the addresses of two
27962 non-relocatable DLLs overlap and these happen to be used by the same
27963 application, a conflict will occur and the application will run
27964 incorrectly. Hence, when possible, it is always preferable to use and
27965 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27966 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27967 User's Guide) removes the debugging symbols from the DLL but the DLL can
27968 still be relocated.
27970 As a side note, an interesting difference between Microsoft DLLs and
27971 Unix shared libraries, is the fact that on most Unix systems all public
27972 routines are exported by default in a Unix shared library, while under
27973 Windows it is possible (but not required) to list exported routines in
27974 a definition file (@pxref{The Definition File}).
27976 @node Using DLLs with GNAT
27977 @section Using DLLs with GNAT
27979 @menu
27980 * Creating an Ada Spec for the DLL Services::
27981 * Creating an Import Library::
27982 @end menu
27984 @noindent
27985 To use the services of a DLL, say @file{API.dll}, in your Ada application
27986 you must have:
27988 @enumerate
27989 @item
27990 The Ada spec for the routines and/or variables you want to access in
27991 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27992 header files provided with the DLL.
27994 @item
27995 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27996 mentioned an import library is a statically linked library containing the
27997 import table which will be filled at load time to point to the actual
27998 @file{API.dll} routines. Sometimes you don't have an import library for the
27999 DLL you want to use. The following sections will explain how to build
28000 one. Note that this is optional.
28002 @item
28003 The actual DLL, @file{API.dll}.
28004 @end enumerate
28006 @noindent
28007 Once you have all the above, to compile an Ada application that uses the
28008 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
28009 you simply issue the command
28011 @smallexample
28012 $ gnatmake my_ada_app -largs -lAPI
28013 @end smallexample
28015 @noindent
28016 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
28017 tells the GNAT linker to look for an import library. The linker will
28018 look for a library name in this specific order:
28020 @enumerate
28021 @item @file{libAPI.dll.a}
28022 @item @file{API.dll.a}
28023 @item @file{libAPI.a}
28024 @item @file{API.lib}
28025 @item @file{libAPI.dll}
28026 @item @file{API.dll}
28027 @end enumerate
28029 The first three are the GNU style import libraries. The third is the
28030 Microsoft style import libraries. The last two are the actual DLL names.
28032 Note that if the Ada package spec for @file{API.dll} contains the
28033 following pragma
28035 @smallexample @c ada
28036 @b{pragma} Linker_Options ("-lAPI");
28037 @end smallexample
28039 @noindent
28040 you do not have to add @option{-largs -lAPI} at the end of the
28041 @command{gnatmake} command.
28043 If any one of the items above is missing you will have to create it
28044 yourself. The following sections explain how to do so using as an
28045 example a fictitious DLL called @file{API.dll}.
28047 @node Creating an Ada Spec for the DLL Services
28048 @subsection Creating an Ada Spec for the DLL Services
28050 @noindent
28051 A DLL typically comes with a C/C++ header file which provides the
28052 definitions of the routines and variables exported by the DLL. The Ada
28053 equivalent of this header file is a package spec that contains definitions
28054 for the imported entities. If the DLL you intend to use does not come with
28055 an Ada spec you have to generate one such spec yourself. For example if
28056 the header file of @file{API.dll} is a file @file{api.h} containing the
28057 following two definitions:
28059 @smallexample
28060 @group
28061 @cartouche
28062 int some_var;
28063 int get (char *);
28064 @end cartouche
28065 @end group
28066 @end smallexample
28068 @noindent
28069 then the equivalent Ada spec could be:
28071 @smallexample @c ada
28072 @group
28073 @cartouche
28074 @b{with} Interfaces.C.Strings;
28075 @b{package} API @b{is}
28076    @b{use} Interfaces;
28078    Some_Var : C.int;
28079    @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
28081 @b{private}
28082    @b{pragma} Import (C, Get);
28083    @b{pragma} Import (DLL, Some_Var);
28084 @b{end} API;
28085 @end cartouche
28086 @end group
28087 @end smallexample
28089 @node Creating an Import Library
28090 @subsection Creating an Import Library
28091 @cindex Import library
28093 @menu
28094 * The Definition File::
28095 * GNAT-Style Import Library::
28096 * Microsoft-Style Import Library::
28097 @end menu
28099 @noindent
28100 If a Microsoft-style import library @file{API.lib} or a GNAT-style
28101 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
28102 with @file{API.dll} you can skip this section. You can also skip this
28103 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
28104 as in this case it is possible to link directly against the
28105 DLL. Otherwise read on.
28107 @node The Definition File
28108 @subsubsection The Definition File
28109 @cindex Definition file
28110 @findex .def
28112 @noindent
28113 As previously mentioned, and unlike Unix systems, the list of symbols
28114 that are exported from a DLL must be provided explicitly in Windows.
28115 The main goal of a definition file is precisely that: list the symbols
28116 exported by a DLL. A definition file (usually a file with a @code{.def}
28117 suffix) has the following structure:
28119 @smallexample
28120 @group
28121 @cartouche
28122 @r{[}LIBRARY @var{name}@r{]}
28123 @r{[}DESCRIPTION @var{string}@r{]}
28124 EXPORTS
28125    @var{symbol1}
28126    @var{symbol2}
28127    @dots{}
28128 @end cartouche
28129 @end group
28130 @end smallexample
28132 @table @code
28133 @item LIBRARY @var{name}
28134 This section, which is optional, gives the name of the DLL.
28136 @item DESCRIPTION @var{string}
28137 This section, which is optional, gives a description string that will be
28138 embedded in the import library.
28140 @item EXPORTS
28141 This section gives the list of exported symbols (procedures, functions or
28142 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
28143 section of @file{API.def} looks like:
28145 @smallexample
28146 @group
28147 @cartouche
28148 EXPORTS
28149    some_var
28150    get
28151 @end cartouche
28152 @end group
28153 @end smallexample
28154 @end table
28156 @noindent
28157 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
28158 (@pxref{Windows Calling Conventions}) for a Stdcall
28159 calling convention function in the exported symbols list.
28161 @noindent
28162 There can actually be other sections in a definition file, but these
28163 sections are not relevant to the discussion at hand.
28165 @node GNAT-Style Import Library
28166 @subsubsection GNAT-Style Import Library
28168 @noindent
28169 To create a static import library from @file{API.dll} with the GNAT tools
28170 you should proceed as follows:
28172 @enumerate
28173 @item
28174 Create the definition file @file{API.def} (@pxref{The Definition File}).
28175 For that use the @code{dll2def} tool as follows:
28177 @smallexample
28178 $ dll2def API.dll > API.def
28179 @end smallexample
28181 @noindent
28182 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
28183 to standard output the list of entry points in the DLL. Note that if
28184 some routines in the DLL have the @code{Stdcall} convention
28185 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
28186 suffix then you'll have to edit @file{api.def} to add it, and specify
28187 @option{-k} to @command{gnatdll} when creating the import library.
28189 @noindent
28190 Here are some hints to find the right @code{@@}@var{nn} suffix.
28192 @enumerate
28193 @item
28194 If you have the Microsoft import library (.lib), it is possible to get
28195 the right symbols by using Microsoft @code{dumpbin} tool (see the
28196 corresponding Microsoft documentation for further details).
28198 @smallexample
28199 $ dumpbin /exports api.lib
28200 @end smallexample
28202 @item
28203 If you have a message about a missing symbol at link time the compiler
28204 tells you what symbol is expected. You just have to go back to the
28205 definition file and add the right suffix.
28206 @end enumerate
28208 @item
28209 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28210 (@pxref{Using gnatdll}) as follows:
28212 @smallexample
28213 $ gnatdll -e API.def -d API.dll
28214 @end smallexample
28216 @noindent
28217 @code{gnatdll} takes as input a definition file @file{API.def} and the
28218 name of the DLL containing the services listed in the definition file
28219 @file{API.dll}. The name of the static import library generated is
28220 computed from the name of the definition file as follows: if the
28221 definition file name is @var{xyz}@code{.def}, the import library name will
28222 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
28223 @option{-e} could have been removed because the name of the definition
28224 file (before the ``@code{.def}'' suffix) is the same as the name of the
28225 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
28226 @end enumerate
28228 @node Microsoft-Style Import Library
28229 @subsubsection Microsoft-Style Import Library
28231 @noindent
28232 With GNAT you can either use a GNAT-style or Microsoft-style import
28233 library. A Microsoft import library is needed only if you plan to make an
28234 Ada DLL available to applications developed with Microsoft
28235 tools (@pxref{Mixed-Language Programming on Windows}).
28237 To create a Microsoft-style import library for @file{API.dll} you
28238 should proceed as follows:
28240 @enumerate
28241 @item
28242 Create the definition file @file{API.def} from the DLL. For this use either
28243 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
28244 tool (see the corresponding Microsoft documentation for further details).
28246 @item
28247 Build the actual import library using Microsoft's @code{lib} utility:
28249 @smallexample
28250 $ lib -machine:IX86 -def:API.def -out:API.lib
28251 @end smallexample
28253 @noindent
28254 If you use the above command the definition file @file{API.def} must
28255 contain a line giving the name of the DLL:
28257 @smallexample
28258 LIBRARY      "API"
28259 @end smallexample
28261 @noindent
28262 See the Microsoft documentation for further details about the usage of
28263 @code{lib}.
28264 @end enumerate
28266 @node Building DLLs with GNAT Project files
28267 @section Building DLLs with GNAT Project files
28268 @cindex DLLs, building
28270 @noindent
28271 There is nothing specific to Windows in the build process.
28272 @pxref{Library Projects}.
28274 @noindent
28275 Due to a system limitation, it is not possible under Windows to create threads
28276 when inside the @code{DllMain} routine which is used for auto-initialization
28277 of shared libraries, so it is not possible to have library level tasks in SALs.
28279 @node Building DLLs with GNAT
28280 @section Building DLLs with GNAT
28281 @cindex DLLs, building
28283 @noindent
28284 This section explain how to build DLLs using the GNAT built-in DLL
28285 support. With the following procedure it is straight forward to build
28286 and use DLLs with GNAT.
28288 @enumerate
28290 @item building object files
28292 The first step is to build all objects files that are to be included
28293 into the DLL. This is done by using the standard @command{gnatmake} tool.
28295 @item building the DLL
28297 To build the DLL you must use @command{gcc}'s @option{-shared} and
28298 @option{-shared-libgcc} options. It is quite simple to use this method:
28300 @smallexample
28301 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
28302 @end smallexample
28304 It is important to note that in this case all symbols found in the
28305 object files are automatically exported. It is possible to restrict
28306 the set of symbols to export by passing to @command{gcc} a definition
28307 file, @pxref{The Definition File}. For example:
28309 @smallexample
28310 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
28311 @end smallexample
28313 If you use a definition file you must export the elaboration procedures
28314 for every package that required one. Elaboration procedures are named
28315 using the package name followed by "_E".
28317 @item preparing DLL to be used
28319 For the DLL to be used by client programs the bodies must be hidden
28320 from it and the .ali set with read-only attribute. This is very important
28321 otherwise GNAT will recompile all packages and will not actually use
28322 the code in the DLL. For example:
28324 @smallexample
28325 $ mkdir apilib
28326 $ copy *.ads *.ali api.dll apilib
28327 $ attrib +R apilib\*.ali
28328 @end smallexample
28330 @end enumerate
28332 At this point it is possible to use the DLL by directly linking
28333 against it. Note that you must use the GNAT shared runtime when using
28334 GNAT shared libraries. This is achieved by using @option{-shared} binder's
28335 option.
28337 @smallexample
28338 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28339 @end smallexample
28341 @node Building DLLs with gnatdll
28342 @section Building DLLs with gnatdll
28343 @cindex DLLs, building
28345 @menu
28346 * Limitations When Using Ada DLLs from Ada::
28347 * Exporting Ada Entities::
28348 * Ada DLLs and Elaboration::
28349 * Ada DLLs and Finalization::
28350 * Creating a Spec for Ada DLLs::
28351 * Creating the Definition File::
28352 * Using gnatdll::
28353 @end menu
28355 @noindent
28356 Note that it is preferred to use GNAT Project files
28357 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28358 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28360 This section explains how to build DLLs containing Ada code using
28361 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28362 remainder of this section.
28364 The steps required to build an Ada DLL that is to be used by Ada as well as
28365 non-Ada applications are as follows:
28367 @enumerate
28368 @item
28369 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28370 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28371 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28372 skip this step if you plan to use the Ada DLL only from Ada applications.
28374 @item
28375 Your Ada code must export an initialization routine which calls the routine
28376 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28377 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28378 routine exported by the Ada DLL must be invoked by the clients of the DLL
28379 to initialize the DLL.
28381 @item
28382 When useful, the DLL should also export a finalization routine which calls
28383 routine @code{adafinal} generated by @command{gnatbind} to perform the
28384 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28385 The finalization routine exported by the Ada DLL must be invoked by the
28386 clients of the DLL when the DLL services are no further needed.
28388 @item
28389 You must provide a spec for the services exported by the Ada DLL in each
28390 of the programming languages to which you plan to make the DLL available.
28392 @item
28393 You must provide a definition file listing the exported entities
28394 (@pxref{The Definition File}).
28396 @item
28397 Finally you must use @code{gnatdll} to produce the DLL and the import
28398 library (@pxref{Using gnatdll}).
28399 @end enumerate
28401 @noindent
28402 Note that a relocatable DLL stripped using the @code{strip}
28403 binutils tool will not be relocatable anymore. To build a DLL without
28404 debug information pass @code{-largs -s} to @code{gnatdll}. This
28405 restriction does not apply to a DLL built using a Library Project.
28406 @pxref{Library Projects}.
28408 @node Limitations When Using Ada DLLs from Ada
28409 @subsection Limitations When Using Ada DLLs from Ada
28411 @noindent
28412 When using Ada DLLs from Ada applications there is a limitation users
28413 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28414 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28415 each Ada DLL includes the services of the GNAT run time that are necessary
28416 to the Ada code inside the DLL. As a result, when an Ada program uses an
28417 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28418 one in the main program.
28420 It is therefore not possible to exchange GNAT run-time objects between the
28421 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28422 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
28423 types, etc.
28425 It is completely safe to exchange plain elementary, array or record types,
28426 Windows object handles, etc.
28428 @node Exporting Ada Entities
28429 @subsection Exporting Ada Entities
28430 @cindex Export table
28432 @noindent
28433 Building a DLL is a way to encapsulate a set of services usable from any
28434 application. As a result, the Ada entities exported by a DLL should be
28435 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28436 any Ada name mangling. As an example here is an Ada package
28437 @code{API}, spec and body, exporting two procedures, a function, and a
28438 variable:
28440 @smallexample @c ada
28441 @group
28442 @cartouche
28443 @b{with} Interfaces.C; @b{use} Interfaces;
28444 @b{package} API @b{is}
28445    Count : C.int := 0;
28446    @b{function} Factorial (Val : C.int) @b{return} C.int;
28448    @b{procedure} Initialize_API;
28449    @b{procedure} Finalize_API;
28450    --@i{  Initialization & Finalization routines. More in the next section.}
28451 @b{private}
28452    @b{pragma} Export (C, Initialize_API);
28453    @b{pragma} Export (C, Finalize_API);
28454    @b{pragma} Export (C, Count);
28455    @b{pragma} Export (C, Factorial);
28456 @b{end} API;
28457 @end cartouche
28458 @end group
28459 @end smallexample
28461 @smallexample @c ada
28462 @group
28463 @cartouche
28464 @b{package} @b{body} API @b{is}
28465    @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
28466       Fact : C.int := 1;
28467    @b{begin}
28468       Count := Count + 1;
28469       @b{for} K @b{in} 1 .. Val @b{loop}
28470          Fact := Fact * K;
28471       @b{end} @b{loop};
28472       @b{return} Fact;
28473    @b{end} Factorial;
28475    @b{procedure} Initialize_API @b{is}
28476       @b{procedure} Adainit;
28477       @b{pragma} Import (C, Adainit);
28478    @b{begin}
28479       Adainit;
28480    @b{end} Initialize_API;
28482    @b{procedure} Finalize_API @b{is}
28483       @b{procedure} Adafinal;
28484       @b{pragma} Import (C, Adafinal);
28485    @b{begin}
28486       Adafinal;
28487    @b{end} Finalize_API;
28488 @b{end} API;
28489 @end cartouche
28490 @end group
28491 @end smallexample
28493 @noindent
28494 If the Ada DLL you are building will only be used by Ada applications
28495 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28496 convention. As an example, the previous package could be written as
28497 follows:
28499 @smallexample @c ada
28500 @group
28501 @cartouche
28502 @b{package} API @b{is}
28503    Count : Integer := 0;
28504    @b{function} Factorial (Val : Integer) @b{return} Integer;
28506    @b{procedure} Initialize_API;
28507    @b{procedure} Finalize_API;
28508    --@i{  Initialization and Finalization routines.}
28509 @b{end} API;
28510 @end cartouche
28511 @end group
28512 @end smallexample
28514 @smallexample @c ada
28515 @group
28516 @cartouche
28517 @b{package} @b{body} API @b{is}
28518    @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
28519       Fact : Integer := 1;
28520    @b{begin}
28521       Count := Count + 1;
28522       @b{for} K @b{in} 1 .. Val @b{loop}
28523          Fact := Fact * K;
28524       @b{end} @b{loop};
28525       @b{return} Fact;
28526    @b{end} Factorial;
28528    @dots{}
28529    --@i{  The remainder of this package body is unchanged.}
28530 @b{end} API;
28531 @end cartouche
28532 @end group
28533 @end smallexample
28535 @noindent
28536 Note that if you do not export the Ada entities with a @code{C} or
28537 @code{Stdcall} convention you will have to provide the mangled Ada names
28538 in the definition file of the Ada DLL
28539 (@pxref{Creating the Definition File}).
28541 @node Ada DLLs and Elaboration
28542 @subsection Ada DLLs and Elaboration
28543 @cindex DLLs and elaboration
28545 @noindent
28546 The DLL that you are building contains your Ada code as well as all the
28547 routines in the Ada library that are needed by it. The first thing a
28548 user of your DLL must do is elaborate the Ada code
28549 (@pxref{Elaboration Order Handling in GNAT}).
28551 To achieve this you must export an initialization routine
28552 (@code{Initialize_API} in the previous example), which must be invoked
28553 before using any of the DLL services. This elaboration routine must call
28554 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28555 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28556 @code{Initialize_Api} for an example. Note that the GNAT binder is
28557 automatically invoked during the DLL build process by the @code{gnatdll}
28558 tool (@pxref{Using gnatdll}).
28560 When a DLL is loaded, Windows systematically invokes a routine called
28561 @code{DllMain}. It would therefore be possible to call @code{adainit}
28562 directly from @code{DllMain} without having to provide an explicit
28563 initialization routine. Unfortunately, it is not possible to call
28564 @code{adainit} from the @code{DllMain} if your program has library level
28565 tasks because access to the @code{DllMain} entry point is serialized by
28566 the system (that is, only a single thread can execute ``through'' it at a
28567 time), which means that the GNAT run time will deadlock waiting for the
28568 newly created task to complete its initialization.
28570 @node Ada DLLs and Finalization
28571 @subsection Ada DLLs and Finalization
28572 @cindex DLLs and finalization
28574 @noindent
28575 When the services of an Ada DLL are no longer needed, the client code should
28576 invoke the DLL finalization routine, if available. The DLL finalization
28577 routine is in charge of releasing all resources acquired by the DLL. In the
28578 case of the Ada code contained in the DLL, this is achieved by calling
28579 routine @code{adafinal} generated by the GNAT binder
28580 (@pxref{Binding with Non-Ada Main Programs}).
28581 See the body of @code{Finalize_Api} for an
28582 example. As already pointed out the GNAT binder is automatically invoked
28583 during the DLL build process by the @code{gnatdll} tool
28584 (@pxref{Using gnatdll}).
28586 @node Creating a Spec for Ada DLLs
28587 @subsection Creating a Spec for Ada DLLs
28589 @noindent
28590 To use the services exported by the Ada DLL from another programming
28591 language (e.g.@: C), you have to translate the specs of the exported Ada
28592 entities in that language. For instance in the case of @code{API.dll},
28593 the corresponding C header file could look like:
28595 @smallexample
28596 @group
28597 @cartouche
28598 extern int *_imp__count;
28599 #define count (*_imp__count)
28600 int factorial (int);
28601 @end cartouche
28602 @end group
28603 @end smallexample
28605 @noindent
28606 It is important to understand that when building an Ada DLL to be used by
28607 other Ada applications, you need two different specs for the packages
28608 contained in the DLL: one for building the DLL and the other for using
28609 the DLL. This is because the @code{DLL} calling convention is needed to
28610 use a variable defined in a DLL, but when building the DLL, the variable
28611 must have either the @code{Ada} or @code{C} calling convention. As an
28612 example consider a DLL comprising the following package @code{API}:
28614 @smallexample @c ada
28615 @group
28616 @cartouche
28617 @b{package} API @b{is}
28618    Count : Integer := 0;
28619    @dots{}
28620    --@i{  Remainder of the package omitted.}
28621 @b{end} API;
28622 @end cartouche
28623 @end group
28624 @end smallexample
28626 @noindent
28627 After producing a DLL containing package @code{API}, the spec that
28628 must be used to import @code{API.Count} from Ada code outside of the
28629 DLL is:
28631 @smallexample @c ada
28632 @group
28633 @cartouche
28634 @b{package} API @b{is}
28635    Count : Integer;
28636    @b{pragma} Import (DLL, Count);
28637 @b{end} API;
28638 @end cartouche
28639 @end group
28640 @end smallexample
28642 @node Creating the Definition File
28643 @subsection Creating the Definition File
28645 @noindent
28646 The definition file is the last file needed to build the DLL. It lists
28647 the exported symbols. As an example, the definition file for a DLL
28648 containing only package @code{API} (where all the entities are exported
28649 with a @code{C} calling convention) is:
28651 @smallexample
28652 @group
28653 @cartouche
28654 EXPORTS
28655     count
28656     factorial
28657     finalize_api
28658     initialize_api
28659 @end cartouche
28660 @end group
28661 @end smallexample
28663 @noindent
28664 If the @code{C} calling convention is missing from package @code{API},
28665 then the definition file contains the mangled Ada names of the above
28666 entities, which in this case are:
28668 @smallexample
28669 @group
28670 @cartouche
28671 EXPORTS
28672     api__count
28673     api__factorial
28674     api__finalize_api
28675     api__initialize_api
28676 @end cartouche
28677 @end group
28678 @end smallexample
28680 @node Using gnatdll
28681 @subsection Using @code{gnatdll}
28682 @findex gnatdll
28684 @menu
28685 * gnatdll Example::
28686 * gnatdll behind the Scenes::
28687 * Using dlltool::
28688 @end menu
28690 @noindent
28691 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28692 and non-Ada sources that make up your DLL have been compiled.
28693 @code{gnatdll} is actually in charge of two distinct tasks: build the
28694 static import library for the DLL and the actual DLL. The form of the
28695 @code{gnatdll} command is
28697 @smallexample
28698 @cartouche
28699 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28700 @c Expanding @ovar macro inline (explanation in macro def comments)
28701 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28702 @end cartouche
28703 @end smallexample
28705 @noindent
28706 where @var{list-of-files} is a list of ALI and object files. The object
28707 file list must be the exact list of objects corresponding to the non-Ada
28708 sources whose services are to be included in the DLL. The ALI file list
28709 must be the exact list of ALI files for the corresponding Ada sources
28710 whose services are to be included in the DLL. If @var{list-of-files} is
28711 missing, only the static import library is generated.
28713 @noindent
28714 You may specify any of the following switches to @code{gnatdll}:
28716 @table @code
28717 @c @item -a@ovar{address}
28718 @c Expanding @ovar macro inline (explanation in macro def comments)
28719 @item -a@r{[}@var{address}@r{]}
28720 @cindex @option{-a} (@code{gnatdll})
28721 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28722 specified the default address @var{0x11000000} will be used. By default,
28723 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28724 advise the reader to build relocatable DLL.
28726 @item -b @var{address}
28727 @cindex @option{-b} (@code{gnatdll})
28728 Set the relocatable DLL base address. By default the address is
28729 @code{0x11000000}.
28731 @item -bargs @var{opts}
28732 @cindex @option{-bargs} (@code{gnatdll})
28733 Binder options. Pass @var{opts} to the binder.
28735 @item -d @var{dllfile}
28736 @cindex @option{-d} (@code{gnatdll})
28737 @var{dllfile} is the name of the DLL. This switch must be present for
28738 @code{gnatdll} to do anything. The name of the generated import library is
28739 obtained algorithmically from @var{dllfile} as shown in the following
28740 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28741 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28742 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28743 as shown in the following example:
28744 if @var{dllfile} is @code{xyz.dll}, the definition
28745 file used is @code{xyz.def}.
28747 @item -e @var{deffile}
28748 @cindex @option{-e} (@code{gnatdll})
28749 @var{deffile} is the name of the definition file.
28751 @item -g
28752 @cindex @option{-g} (@code{gnatdll})
28753 Generate debugging information. This information is stored in the object
28754 file and copied from there to the final DLL file by the linker,
28755 where it can be read by the debugger. You must use the
28756 @option{-g} switch if you plan on using the debugger or the symbolic
28757 stack traceback.
28759 @item -h
28760 @cindex @option{-h} (@code{gnatdll})
28761 Help mode. Displays @code{gnatdll} switch usage information.
28763 @item -Idir
28764 @cindex @option{-I} (@code{gnatdll})
28765 Direct @code{gnatdll} to search the @var{dir} directory for source and
28766 object files needed to build the DLL.
28767 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28769 @item -k
28770 @cindex @option{-k} (@code{gnatdll})
28771 Removes the @code{@@}@var{nn} suffix from the import library's exported
28772 names, but keeps them for the link names. You must specify this
28773 option if you want to use a @code{Stdcall} function in a DLL for which
28774 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28775 of the Windows NT DLL for example. This option has no effect when
28776 @option{-n} option is specified.
28778 @item -l @var{file}
28779 @cindex @option{-l} (@code{gnatdll})
28780 The list of ALI and object files used to build the DLL are listed in
28781 @var{file}, instead of being given in the command line. Each line in
28782 @var{file} contains the name of an ALI or object file.
28784 @item -n
28785 @cindex @option{-n} (@code{gnatdll})
28786 No Import. Do not create the import library.
28788 @item -q
28789 @cindex @option{-q} (@code{gnatdll})
28790 Quiet mode. Do not display unnecessary messages.
28792 @item -v
28793 @cindex @option{-v} (@code{gnatdll})
28794 Verbose mode. Display extra information.
28796 @item -largs @var{opts}
28797 @cindex @option{-largs} (@code{gnatdll})
28798 Linker options. Pass @var{opts} to the linker.
28799 @end table
28801 @node gnatdll Example
28802 @subsubsection @code{gnatdll} Example
28804 @noindent
28805 As an example the command to build a relocatable DLL from @file{api.adb}
28806 once @file{api.adb} has been compiled and @file{api.def} created is
28808 @smallexample
28809 $ gnatdll -d api.dll api.ali
28810 @end smallexample
28812 @noindent
28813 The above command creates two files: @file{libapi.dll.a} (the import
28814 library) and @file{api.dll} (the actual DLL). If you want to create
28815 only the DLL, just type:
28817 @smallexample
28818 $ gnatdll -d api.dll -n api.ali
28819 @end smallexample
28821 @noindent
28822 Alternatively if you want to create just the import library, type:
28824 @smallexample
28825 $ gnatdll -d api.dll
28826 @end smallexample
28828 @node gnatdll behind the Scenes
28829 @subsubsection @code{gnatdll} behind the Scenes
28831 @noindent
28832 This section details the steps involved in creating a DLL. @code{gnatdll}
28833 does these steps for you. Unless you are interested in understanding what
28834 goes on behind the scenes, you should skip this section.
28836 We use the previous example of a DLL containing the Ada package @code{API},
28837 to illustrate the steps necessary to build a DLL. The starting point is a
28838 set of objects that will make up the DLL and the corresponding ALI
28839 files. In the case of this example this means that @file{api.o} and
28840 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28841 the following:
28843 @enumerate
28844 @item
28845 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28846 the information necessary to generate relocation information for the
28847 DLL.
28849 @smallexample
28850 @group
28851 $ gnatbind -n api
28852 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28853 @end group
28854 @end smallexample
28856 @noindent
28857 In addition to the base file, the @command{gnatlink} command generates an
28858 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28859 asks @command{gnatlink} to generate the routines @code{DllMain} and
28860 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28861 is loaded into memory.
28863 @item
28864 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28865 export table (@file{api.exp}). The export table contains the relocation
28866 information in a form which can be used during the final link to ensure
28867 that the Windows loader is able to place the DLL anywhere in memory.
28869 @smallexample
28870 @group
28871 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28872           --output-exp api.exp
28873 @end group
28874 @end smallexample
28876 @item
28877 @code{gnatdll} builds the base file using the new export table. Note that
28878 @command{gnatbind} must be called once again since the binder generated file
28879 has been deleted during the previous call to @command{gnatlink}.
28881 @smallexample
28882 @group
28883 $ gnatbind -n api
28884 $ gnatlink api -o api.jnk api.exp -mdll
28885       -Wl,--base-file,api.base
28886 @end group
28887 @end smallexample
28889 @item
28890 @code{gnatdll} builds the new export table using the new base file and
28891 generates the DLL import library @file{libAPI.dll.a}.
28893 @smallexample
28894 @group
28895 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28896           --output-exp api.exp --output-lib libAPI.a
28897 @end group
28898 @end smallexample
28900 @item
28901 Finally @code{gnatdll} builds the relocatable DLL using the final export
28902 table.
28904 @smallexample
28905 @group
28906 $ gnatbind -n api
28907 $ gnatlink api api.exp -o api.dll -mdll
28908 @end group
28909 @end smallexample
28910 @end enumerate
28912 @node Using dlltool
28913 @subsubsection Using @code{dlltool}
28915 @noindent
28916 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28917 DLLs and static import libraries. This section summarizes the most
28918 common @code{dlltool} switches. The form of the @code{dlltool} command
28921 @smallexample
28922 @c $ dlltool @ovar{switches}
28923 @c Expanding @ovar macro inline (explanation in macro def comments)
28924 $ dlltool @r{[}@var{switches}@r{]}
28925 @end smallexample
28927 @noindent
28928 @code{dlltool} switches include:
28930 @table @option
28931 @item --base-file @var{basefile}
28932 @cindex @option{--base-file} (@command{dlltool})
28933 Read the base file @var{basefile} generated by the linker. This switch
28934 is used to create a relocatable DLL.
28936 @item --def @var{deffile}
28937 @cindex @option{--def} (@command{dlltool})
28938 Read the definition file.
28940 @item --dllname @var{name}
28941 @cindex @option{--dllname} (@command{dlltool})
28942 Gives the name of the DLL. This switch is used to embed the name of the
28943 DLL in the static import library generated by @code{dlltool} with switch
28944 @option{--output-lib}.
28946 @item -k
28947 @cindex @option{-k} (@command{dlltool})
28948 Kill @code{@@}@var{nn} from exported names
28949 (@pxref{Windows Calling Conventions}
28950 for a discussion about @code{Stdcall}-style symbols.
28952 @item --help
28953 @cindex @option{--help} (@command{dlltool})
28954 Prints the @code{dlltool} switches with a concise description.
28956 @item --output-exp @var{exportfile}
28957 @cindex @option{--output-exp} (@command{dlltool})
28958 Generate an export file @var{exportfile}. The export file contains the
28959 export table (list of symbols in the DLL) and is used to create the DLL.
28961 @item --output-lib @var{libfile}
28962 @cindex @option{--output-lib} (@command{dlltool})
28963 Generate a static import library @var{libfile}.
28965 @item -v
28966 @cindex @option{-v} (@command{dlltool})
28967 Verbose mode.
28969 @item --as @var{assembler-name}
28970 @cindex @option{--as} (@command{dlltool})
28971 Use @var{assembler-name} as the assembler. The default is @code{as}.
28972 @end table
28974 @node GNAT and Windows Resources
28975 @section GNAT and Windows Resources
28976 @cindex Resources, windows
28978 @menu
28979 * Building Resources::
28980 * Compiling Resources::
28981 * Using Resources::
28982 @end menu
28984 @noindent
28985 Resources are an easy way to add Windows specific objects to your
28986 application. The objects that can be added as resources include:
28988 @itemize @bullet
28989 @item menus
28991 @item accelerators
28993 @item dialog boxes
28995 @item string tables
28997 @item bitmaps
28999 @item cursors
29001 @item icons
29003 @item fonts
29005 @item version information
29006 @end itemize
29008 For example, a version information resource can be defined as follow and
29009 embedded into an executable or DLL:
29011 A version information resource can be used to embed information into an
29012 executable or a DLL. These information can be viewed using the file properties
29013 from the Windows Explorer. Here is an example of a version information
29014 resource:
29016 @smallexample
29017 @group
29018 1 VERSIONINFO
29019 FILEVERSION     1,0,0,0
29020 PRODUCTVERSION  1,0,0,0
29021 BEGIN
29022   BLOCK "StringFileInfo"
29023   BEGIN
29024     BLOCK "080904E4"
29025     BEGIN
29026       VALUE "CompanyName", "My Company Name"
29027       VALUE "FileDescription", "My application"
29028       VALUE "FileVersion", "1.0"
29029       VALUE "InternalName", "my_app"
29030       VALUE "LegalCopyright", "My Name"
29031       VALUE "OriginalFilename", "my_app.exe"
29032       VALUE "ProductName", "My App"
29033       VALUE "ProductVersion", "1.0"
29034     END
29035   END
29037   BLOCK "VarFileInfo"
29038   BEGIN
29039     VALUE "Translation", 0x809, 1252
29040   END
29042 @end group
29043 @end smallexample
29045 The value @code{0809} (langID) is for the U.K English language and
29046 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
29047 multilingual.
29049 @noindent
29050 This section explains how to build, compile and use resources. Note that this
29051 section does not cover all resource objects, for a complete description see
29052 the corresponding Microsoft documentation.
29054 @node Building Resources
29055 @subsection Building Resources
29056 @cindex Resources, building
29058 @noindent
29059 A resource file is an ASCII file. By convention resource files have an
29060 @file{.rc} extension.
29061 The easiest way to build a resource file is to use Microsoft tools
29062 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
29063 @code{dlgedit.exe} to build dialogs.
29064 It is always possible to build an @file{.rc} file yourself by writing a
29065 resource script.
29067 It is not our objective to explain how to write a resource file. A
29068 complete description of the resource script language can be found in the
29069 Microsoft documentation.
29071 @node Compiling Resources
29072 @subsection Compiling Resources
29073 @findex rc
29074 @findex windres
29075 @cindex Resources, compiling
29077 @noindent
29078 This section describes how to build a GNAT-compatible (COFF) object file
29079 containing the resources. This is done using the Resource Compiler
29080 @code{windres} as follows:
29082 @smallexample
29083 $ windres -i myres.rc -o myres.o
29084 @end smallexample
29086 @noindent
29087 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
29088 file. You can specify an alternate preprocessor (usually named
29089 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
29090 parameter. A list of all possible options may be obtained by entering
29091 the command @code{windres} @option{--help}.
29093 It is also possible to use the Microsoft resource compiler @code{rc.exe}
29094 to produce a @file{.res} file (binary resource file). See the
29095 corresponding Microsoft documentation for further details. In this case
29096 you need to use @code{windres} to translate the @file{.res} file to a
29097 GNAT-compatible object file as follows:
29099 @smallexample
29100 $ windres -i myres.res -o myres.o
29101 @end smallexample
29103 @node Using Resources
29104 @subsection Using Resources
29105 @cindex Resources, using
29107 @noindent
29108 To include the resource file in your program just add the
29109 GNAT-compatible object file for the resource(s) to the linker
29110 arguments. With @command{gnatmake} this is done by using the @option{-largs}
29111 option:
29113 @smallexample
29114 $ gnatmake myprog -largs myres.o
29115 @end smallexample
29117 @node Debugging a DLL
29118 @section Debugging a DLL
29119 @cindex DLL debugging
29121 @menu
29122 * Program and DLL Both Built with GCC/GNAT::
29123 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
29124 @end menu
29126 @noindent
29127 Debugging a DLL is similar to debugging a standard program. But
29128 we have to deal with two different executable parts: the DLL and the
29129 program that uses it. We have the following four possibilities:
29131 @enumerate 1
29132 @item
29133 The program and the DLL are built with @code{GCC/GNAT}.
29134 @item
29135 The program is built with foreign tools and the DLL is built with
29136 @code{GCC/GNAT}.
29137 @item
29138 The program is built with @code{GCC/GNAT} and the DLL is built with
29139 foreign tools.
29140 @end enumerate
29142 @noindent
29143 In this section we address only cases one and two above.
29144 There is no point in trying to debug
29145 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
29146 information in it. To do so you must use a debugger compatible with the
29147 tools suite used to build the DLL.
29149 @node Program and DLL Both Built with GCC/GNAT
29150 @subsection Program and DLL Both Built with GCC/GNAT
29152 @noindent
29153 This is the simplest case. Both the DLL and the program have @code{GDB}
29154 compatible debugging information. It is then possible to break anywhere in
29155 the process. Let's suppose here that the main procedure is named
29156 @code{ada_main} and that in the DLL there is an entry point named
29157 @code{ada_dll}.
29159 @noindent
29160 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
29161 program must have been built with the debugging information (see GNAT -g
29162 switch). Here are the step-by-step instructions for debugging it:
29164 @enumerate 1
29165 @item Launch @code{GDB} on the main program.
29167 @smallexample
29168 $ gdb -nw ada_main
29169 @end smallexample
29171 @item Start the program and stop at the beginning of the main procedure
29173 @smallexample
29174 (gdb) start
29175 @end smallexample
29177 @noindent
29178 This step is required to be able to set a breakpoint inside the DLL. As long
29179 as the program is not run, the DLL is not loaded. This has the
29180 consequence that the DLL debugging information is also not loaded, so it is not
29181 possible to set a breakpoint in the DLL.
29183 @item Set a breakpoint inside the DLL
29185 @smallexample
29186 (gdb) break ada_dll
29187 (gdb) cont
29188 @end smallexample
29190 @end enumerate
29192 @noindent
29193 At this stage a breakpoint is set inside the DLL. From there on
29194 you can use the standard approach to debug the whole program
29195 (@pxref{Running and Debugging Ada Programs}).
29197 @ignore
29198 @c This used to work, probably because the DLLs were non-relocatable
29199 @c keep this section around until the problem is sorted out.
29201 To break on the @code{DllMain} routine it is not possible to follow
29202 the procedure above. At the time the program stop on @code{ada_main}
29203 the @code{DllMain} routine as already been called. Either you can use
29204 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
29206 @enumerate 1
29207 @item Launch @code{GDB} on the main program.
29209 @smallexample
29210 $ gdb ada_main
29211 @end smallexample
29213 @item Load DLL symbols
29215 @smallexample
29216 (gdb) add-sym api.dll
29217 @end smallexample
29219 @item Set a breakpoint inside the DLL
29221 @smallexample
29222 (gdb) break ada_dll.adb:45
29223 @end smallexample
29225 Note that at this point it is not possible to break using the routine symbol
29226 directly as the program is not yet running. The solution is to break
29227 on the proper line (break in @file{ada_dll.adb} line 45).
29229 @item Start the program
29231 @smallexample
29232 (gdb) run
29233 @end smallexample
29235 @end enumerate
29236 @end ignore
29238 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
29239 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
29241 @menu
29242 * Debugging the DLL Directly::
29243 * Attaching to a Running Process::
29244 @end menu
29246 @noindent
29247 In this case things are slightly more complex because it is not possible to
29248 start the main program and then break at the beginning to load the DLL and the
29249 associated DLL debugging information. It is not possible to break at the
29250 beginning of the program because there is no @code{GDB} debugging information,
29251 and therefore there is no direct way of getting initial control. This
29252 section addresses this issue by describing some methods that can be used
29253 to break somewhere in the DLL to debug it.
29255 @noindent
29256 First suppose that the main procedure is named @code{main} (this is for
29257 example some C code built with Microsoft Visual C) and that there is a
29258 DLL named @code{test.dll} containing an Ada entry point named
29259 @code{ada_dll}.
29261 @noindent
29262 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
29263 been built with debugging information (see GNAT -g option).
29265 @node Debugging the DLL Directly
29266 @subsubsection Debugging the DLL Directly
29268 @enumerate 1
29269 @item
29270 Find out the executable starting address
29272 @smallexample
29273 $ objdump --file-header main.exe
29274 @end smallexample
29276 The starting address is reported on the last line. For example:
29278 @smallexample
29279 main.exe:     file format pei-i386
29280 architecture: i386, flags 0x0000010a:
29281 EXEC_P, HAS_DEBUG, D_PAGED
29282 start address 0x00401010
29283 @end smallexample
29285 @item
29286 Launch the debugger on the executable.
29288 @smallexample
29289 $ gdb main.exe
29290 @end smallexample
29292 @item
29293 Set a breakpoint at the starting address, and launch the program.
29295 @smallexample
29296 $ (gdb) break *0x00401010
29297 $ (gdb) run
29298 @end smallexample
29300 The program will stop at the given address.
29302 @item
29303 Set a breakpoint on a DLL subroutine.
29305 @smallexample
29306 (gdb) break ada_dll.adb:45
29307 @end smallexample
29309 Or if you want to break using a symbol on the DLL, you need first to
29310 select the Ada language (language used by the DLL).
29312 @smallexample
29313 (gdb) set language ada
29314 (gdb) break ada_dll
29315 @end smallexample
29317 @item
29318 Continue the program.
29320 @smallexample
29321 (gdb) cont
29322 @end smallexample
29324 @noindent
29325 This will run the program until it reaches the breakpoint that has been
29326 set. From that point you can use the standard way to debug a program
29327 as described in (@pxref{Running and Debugging Ada Programs}).
29329 @end enumerate
29331 @noindent
29332 It is also possible to debug the DLL by attaching to a running process.
29334 @node Attaching to a Running Process
29335 @subsubsection Attaching to a Running Process
29336 @cindex DLL debugging, attach to process
29338 @noindent
29339 With @code{GDB} it is always possible to debug a running process by
29340 attaching to it. It is possible to debug a DLL this way. The limitation
29341 of this approach is that the DLL must run long enough to perform the
29342 attach operation. It may be useful for instance to insert a time wasting
29343 loop in the code of the DLL to meet this criterion.
29345 @enumerate 1
29347 @item Launch the main program @file{main.exe}.
29349 @smallexample
29350 $ main
29351 @end smallexample
29353 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29354 that the process PID for @file{main.exe} is 208.
29356 @item Launch gdb.
29358 @smallexample
29359 $ gdb
29360 @end smallexample
29362 @item Attach to the running process to be debugged.
29364 @smallexample
29365 (gdb) attach 208
29366 @end smallexample
29368 @item Load the process debugging information.
29370 @smallexample
29371 (gdb) symbol-file main.exe
29372 @end smallexample
29374 @item Break somewhere in the DLL.
29376 @smallexample
29377 (gdb) break ada_dll
29378 @end smallexample
29380 @item Continue process execution.
29382 @smallexample
29383 (gdb) cont
29384 @end smallexample
29386 @end enumerate
29388 @noindent
29389 This last step will resume the process execution, and stop at
29390 the breakpoint we have set. From there you can use the standard
29391 approach to debug a program as described in
29392 (@pxref{Running and Debugging Ada Programs}).
29394 @node Setting Stack Size from gnatlink
29395 @section Setting Stack Size from @command{gnatlink}
29397 @noindent
29398 It is possible to specify the program stack size at link time. On modern
29399 versions of Windows, starting with XP, this is mostly useful to set the size of
29400 the main stack (environment task). The other task stacks are set with pragma
29401 Storage_Size or with the @command{gnatbind -d} command.
29403 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
29404 reserve size of individual tasks, the link-time stack size applies to all
29405 tasks, and pragma Storage_Size has no effect.
29406 In particular, Stack Overflow checks are made against this
29407 link-time specified size.
29409 This setting can be done with
29410 @command{gnatlink} using either:
29412 @itemize @bullet
29414 @item using @option{-Xlinker} linker option
29416 @smallexample
29417 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29418 @end smallexample
29420 This sets the stack reserve size to 0x10000 bytes and the stack commit
29421 size to 0x1000 bytes.
29423 @item using @option{-Wl} linker option
29425 @smallexample
29426 $ gnatlink hello -Wl,--stack=0x1000000
29427 @end smallexample
29429 This sets the stack reserve size to 0x1000000 bytes. Note that with
29430 @option{-Wl} option it is not possible to set the stack commit size
29431 because the coma is a separator for this option.
29433 @end itemize
29435 @node Setting Heap Size from gnatlink
29436 @section Setting Heap Size from @command{gnatlink}
29438 @noindent
29439 Under Windows systems, it is possible to specify the program heap size from
29440 @command{gnatlink} using either:
29442 @itemize @bullet
29444 @item using @option{-Xlinker} linker option
29446 @smallexample
29447 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29448 @end smallexample
29450 This sets the heap reserve size to 0x10000 bytes and the heap commit
29451 size to 0x1000 bytes.
29453 @item using @option{-Wl} linker option
29455 @smallexample
29456 $ gnatlink hello -Wl,--heap=0x1000000
29457 @end smallexample
29459 This sets the heap reserve size to 0x1000000 bytes. Note that with
29460 @option{-Wl} option it is not possible to set the heap commit size
29461 because the coma is a separator for this option.
29463 @end itemize
29465 @node Mac OS Topics
29466 @appendix Mac OS Topics
29467 @cindex OS X
29469 @noindent
29470 This chapter describes topics that are specific to Apple's OS X
29471 platform.
29473 @menu
29474 * Codesigning the Debugger::
29475 @end menu
29477 @node Codesigning the Debugger
29478 @section Codesigning the Debugger
29480 @noindent
29481 The Darwin Kernel requires the debugger to have special permissions
29482 before it is allowed to control other processes. These permissions
29483 are granted by codesigning the GDB executable. Without these
29484 permissions, the debugger will report error messages such as:
29486 @smallexample
29487 Starting program: /x/y/foo
29488 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
29489  (please check gdb is codesigned - see taskgated(8))
29490 @end smallexample
29492 Codesigning requires a certificate.  The following procedure explains
29493 how to create one:
29495 @itemize @bullet
29496 @item Start the Keychain Access application (in
29497 /Applications/Utilities/Keychain Access.app)
29499 @item Select the Keychain Access -> Certificate Assistant ->
29500 Create a Certificate... menu
29502 @item Then:
29504 @itemize @bullet
29505 @item Choose a name for the new certificate (this procedure will use
29506 "gdb-cert" as an example)
29508 @item Set "Identity Type" to "Self Signed Root"
29510 @item Set "Certificate Type" to "Code Signing"
29512 @item Activate the "Let me override defaults" option
29514 @end itemize
29516 @item Click several times on "Continue" until the "Specify a Location
29517 For The Certificate" screen appears, then set "Keychain" to "System"
29519 @item Click on "Continue" until the certificate is created
29521 @item Finally, in the view, double-click on the new certificate,
29522 and set "When using this certificate" to "Always Trust"
29524 @item Exit the Keychain Access application and restart the computer
29525 (this is unfortunately required)
29527 @end itemize
29529 Once a certificate has been created, the debugger can be codesigned
29530 as follow. In a Terminal, run the following command...
29532 @smallexample
29533 codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
29534 @end smallexample
29536 ... where "gdb-cert" should be replaced by the actual certificate
29537 name chosen above, and <gnat_install_prefix> should be replaced by
29538 the location where you installed GNAT.  Also, be sure that users are
29539 in the Unix group @samp{_developer}.
29541 @c **********************************
29542 @c * GNU Free Documentation License *
29543 @c **********************************
29544 @include fdl.texi
29545 @c GNU Free Documentation License
29547 @node Index
29548 @unnumbered Index
29550 @printindex cp
29552 @contents
29553 @c Put table of contents at end, otherwise it precedes the "title page" in
29554 @c the .txt version
29555 @c Edit the pdf file to move the contents to the beginning, after the title
29556 @c page
29558 @bye