* gcc.dg/store-motion-fgcse-sm.c (dg-final): Cleanup
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob39f92612c959316d9d734b0f9750d40adfa9edfe
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-2014, Free Software Foundation, Inc.          o
12 @c                                                                            o
13 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
15 @setfilename gnat_ugn.info
17 @copying
18 Copyright @copyright{} 1995-2014 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 -gnatwg
5052 @emph{Activate warnings on unrecognized pragmas.}
5053 @cindex @option{-gnatwg} (@command{gcc})
5054 @cindex Pragmas, unrecognized
5055 This switch causes a warning to be generated if an unrecognized
5056 pragma is encountered. Apart from issuing this warning, the
5057 pragma is ignored and has no effect. The default
5058 is that such warnings are issued (satisfying the Ada Reference
5059 Manual requirement that such warnings appear).
5061 @item -gnatwG
5062 @emph{Suppress warnings on unrecognized pragmas.}
5063 @cindex @option{-gnatwG} (@command{gcc})
5064 This switch suppresses warnings for unrecognized pragmas.
5066 @item -gnatw.g
5067 @emph{Warnings used for GNAT sources}
5068 @cindex @option{-gnatw.g} (@command{gcc})
5069 This switch sets the warning categories that are used by the standard
5070 GNAT style. Currently this is equivalent to
5071 @option{-gnatwAao.sI.C.V.X}
5072 but more warnings may be added in the future without advanced notice.
5074 @item -gnatwh
5075 @emph{Activate warnings on hiding.}
5076 @cindex @option{-gnatwh} (@command{gcc})
5077 @cindex Hiding of Declarations
5078 This switch activates warnings on hiding declarations.
5079 A declaration is considered hiding
5080 if it is for a non-overloadable entity, and it declares an entity with the
5081 same name as some other entity that is directly or use-visible. The default
5082 is that such warnings are not generated.
5084 @item -gnatwH
5085 @emph{Suppress warnings on hiding.}
5086 @cindex @option{-gnatwH} (@command{gcc})
5087 This switch suppresses warnings on hiding declarations.
5089 @item -gnatw.h
5090 @emph{Activate warnings on holes/gaps in records.}
5091 @cindex @option{-gnatw.h} (@command{gcc})
5092 @cindex Record Representation (gaps)
5093 This switch activates warnings on component clauses in record
5094 representation clauses that leave holes (gaps) in the record layout.
5095 If this warning option is active, then record representation clauses
5096 should specify a contiguous layout, adding unused fill fields if needed.
5098 @item -gnatw.H
5099 @emph{Suppress warnings on holes/gaps in records.}
5100 @cindex @option{-gnatw.H} (@command{gcc})
5101 This switch suppresses warnings on component clauses in record
5102 representation clauses that leave holes (haps) in the record layout.
5104 @item -gnatwi
5105 @emph{Activate warnings on implementation units.}
5106 @cindex @option{-gnatwi} (@command{gcc})
5107 This switch activates warnings for a @code{with} of an internal GNAT
5108 implementation unit, defined as any unit from the @code{Ada},
5109 @code{Interfaces}, @code{GNAT},
5110  or @code{System}
5111 hierarchies that is not
5112 documented in either the Ada Reference Manual or the GNAT
5113 Programmer's Reference Manual. Such units are intended only
5114 for internal implementation purposes and should not be @code{with}'ed
5115 by user programs. The default is that such warnings are generated
5117 @item -gnatwI
5118 @emph{Disable warnings on implementation units.}
5119 @cindex @option{-gnatwI} (@command{gcc})
5120 This switch disables warnings for a @code{with} of an internal GNAT
5121 implementation unit.
5123 @item -gnatw.i
5124 @emph{Activate warnings on overlapping actuals.}
5125 @cindex @option{-gnatw.i} (@command{gcc})
5126 This switch enables a warning on statically detectable overlapping actuals in
5127 a subprogram call, when one of the actuals is an in-out parameter, and the
5128 types of the actuals are not by-copy types. This warning is off by default.
5130 @item -gnatw.I
5131 @emph{Disable warnings on overlapping actuals.}
5132 @cindex @option{-gnatw.I} (@command{gcc})
5133 This switch disables warnings on overlapping actuals in a call..
5135 @item -gnatwj
5136 @emph{Activate warnings on obsolescent features (Annex J).}
5137 @cindex @option{-gnatwj} (@command{gcc})
5138 @cindex Features, obsolescent
5139 @cindex Obsolescent features
5140 If this warning option is activated, then warnings are generated for
5141 calls to subprograms marked with @code{pragma Obsolescent} and
5142 for use of features in Annex J of the Ada Reference Manual. In the
5143 case of Annex J, not all features are flagged. In particular use
5144 of the renamed packages (like @code{Text_IO}) and use of package
5145 @code{ASCII} are not flagged, since these are very common and
5146 would generate many annoying positive warnings. The default is that
5147 such warnings are not generated.
5149 In addition to the above cases, warnings are also generated for
5150 GNAT features that have been provided in past versions but which
5151 have been superseded (typically by features in the new Ada standard).
5152 For example, @code{pragma Ravenscar} will be flagged since its
5153 function is replaced by @code{pragma Profile(Ravenscar)}, and
5154 @code{pragma Interface_Name} will be flagged since its function
5155 is replaced by @code{pragma Import}.
5157 Note that this warning option functions differently from the
5158 restriction @code{No_Obsolescent_Features} in two respects.
5159 First, the restriction applies only to annex J features.
5160 Second, the restriction does flag uses of package @code{ASCII}.
5162 @item -gnatwJ
5163 @emph{Suppress warnings on obsolescent features (Annex J).}
5164 @cindex @option{-gnatwJ} (@command{gcc})
5165 This switch disables warnings on use of obsolescent features.
5167 @item -gnatwk
5168 @emph{Activate warnings on variables that could be constants.}
5169 @cindex @option{-gnatwk} (@command{gcc})
5170 This switch activates warnings for variables that are initialized but
5171 never modified, and then could be declared constants. The default is that
5172 such warnings are not given.
5174 @item -gnatwK
5175 @emph{Suppress warnings on variables that could be constants.}
5176 @cindex @option{-gnatwK} (@command{gcc})
5177 This switch disables warnings on variables that could be declared constants.
5179 @item -gnatw.k
5180 @emph{Activate warnings on redefinition of names in standard.}
5181 @cindex @option{-gnatw.k} (@command{gcc})
5182 This switch activates warnings for declarations that declare a name that
5183 is defined in package Standard. Such declarations can be confusing,
5184 especially since the names in package Standard continue to be directly
5185 visible, meaning that use visibiliy on such redeclared names does not
5186 work as expected. Names of discriminants and components in records are
5187 not included in this check.
5189 @item -gnatw.K
5190 @emph{Suppress warnings on redefinition of names in standard.}
5191 @cindex @option{-gnatwK} (@command{gcc})
5192 This switch activates warnings for declarations that declare a name that
5193 is defined in package Standard.
5195 @item -gnatwl
5196 @emph{Activate warnings for elaboration pragmas.}
5197 @cindex @option{-gnatwl} (@command{gcc})
5198 @cindex Elaboration, warnings
5199 This switch activates warnings for possible elaboration problems,
5200 including suspicious use
5201 of @code{Elaborate} pragmas, when using the static elaboration model, and
5202 possible situations that may raise @code{Program_Error} when using the
5203 dynamic elaboration model.
5204 See the section in this guide on elaboration checking for further details.
5205 The default is that such warnings
5206 are not generated.
5208 @item -gnatwL
5209 @emph{Suppress warnings for elaboration pragmas.}
5210 @cindex @option{-gnatwL} (@command{gcc})
5211 This switch suppresses warnings for possible elaboration problems.
5213 @item -gnatw.l
5214 @emph{List inherited aspects.}
5215 @cindex @option{-gnatw.l} (@command{gcc})
5216 This switch causes the compiler to list inherited invariants,
5217 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5218 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5220 @item -gnatw.L
5221 @emph{Suppress listing of inherited aspects.}
5222 @cindex @option{-gnatw.L} (@command{gcc})
5223 This switch suppresses listing of inherited aspects.
5225 @item -gnatwm
5226 @emph{Activate warnings on modified but unreferenced variables.}
5227 @cindex @option{-gnatwm} (@command{gcc})
5228 This switch activates warnings for variables that are assigned (using
5229 an initialization value or with one or more assignment statements) but
5230 whose value is never read. The warning is suppressed for volatile
5231 variables and also for variables that are renamings of other variables
5232 or for which an address clause is given.
5233 The default is that these warnings are not given.
5235 @item -gnatwM
5236 @emph{Disable warnings on modified but unreferenced variables.}
5237 @cindex @option{-gnatwM} (@command{gcc})
5238 This switch disables warnings for variables that are assigned or
5239 initialized, but never read.
5241 @item -gnatw.m
5242 @emph{Activate warnings on suspicious modulus values.}
5243 @cindex @option{-gnatw.m} (@command{gcc})
5244 This switch activates warnings for modulus values that seem suspicious.
5245 The cases caught are where the size is the same as the modulus (e.g.
5246 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5247 with no size clause. The guess in both cases is that 2**x was intended
5248 rather than x. In addition expressions of the form 2*x for small x
5249 generate a warning (the almost certainly accurate guess being that
5250 2**x was intended). The default is that these warnings are given.
5252 @item -gnatw.M
5253 @emph{Disable warnings on suspicious modulus values.}
5254 @cindex @option{-gnatw.M} (@command{gcc})
5255 This switch disables warnings for suspicious modulus values.
5257 @item -gnatwn
5258 @emph{Set normal warnings mode.}
5259 @cindex @option{-gnatwn} (@command{gcc})
5260 This switch sets normal warning mode, in which enabled warnings are
5261 issued and treated as warnings rather than errors. This is the default
5262 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5263 an explicit @option{-gnatws} or
5264 @option{-gnatwe}. It also cancels the effect of the
5265 implicit @option{-gnatwe} that is activated by the
5266 use of @option{-gnatg}.
5268 @item -gnatw.n
5269 @emph{Activate warnings on atomic synchronization.}
5270 @cindex @option{-gnatw.n} (@command{gcc})
5271 @cindex Atomic Synchronization, warnings
5272 This switch actives warnings when an access to an atomic variable
5273 requires the generation of atomic synchronization code. These
5274 warnings are off by default.
5275 @item -gnatw.N
5276 @emph{Suppress warnings on atomic synchronization.}
5277 @cindex @option{-gnatw.n} (@command{gcc})
5278 @cindex Atomic Synchronization, warnings
5279 This switch suppresses warnings when an access to an atomic variable
5280 requires the generation of atomic synchronization code.
5282 @item -gnatwo
5283 @emph{Activate warnings on address clause overlays.}
5284 @cindex @option{-gnatwo} (@command{gcc})
5285 @cindex Address Clauses, warnings
5286 This switch activates warnings for possibly unintended initialization
5287 effects of defining address clauses that cause one variable to overlap
5288 another. The default is that such warnings are generated.
5290 @item -gnatwO
5291 @emph{Suppress warnings on address clause overlays.}
5292 @cindex @option{-gnatwO} (@command{gcc})
5293 This switch suppresses warnings on possibly unintended initialization
5294 effects of defining address clauses that cause one variable to overlap
5295 another.
5297 @item -gnatw.o
5298 @emph{Activate warnings on modified but unreferenced out parameters.}
5299 @cindex @option{-gnatw.o} (@command{gcc})
5300 This switch activates warnings for variables that are modified by using
5301 them as actuals for a call to a procedure with an out mode formal, where
5302 the resulting assigned value is never read. It is applicable in the case
5303 where there is more than one out mode formal. If there is only one out
5304 mode formal, the warning is issued by default (controlled by -gnatwu).
5305 The warning is suppressed for volatile
5306 variables and also for variables that are renamings of other variables
5307 or for which an address clause is given.
5308 The default is that these warnings are not given.
5310 @item -gnatw.O
5311 @emph{Disable warnings on modified but unreferenced out parameters.}
5312 @cindex @option{-gnatw.O} (@command{gcc})
5313 This switch suppresses warnings for variables that are modified by using
5314 them as actuals for a call to a procedure with an out mode formal, where
5315 the resulting assigned value is never read.
5317 @item -gnatwp
5318 @emph{Activate warnings on ineffective pragma Inlines.}
5319 @cindex @option{-gnatwp} (@command{gcc})
5320 @cindex Inlining, warnings
5321 This switch activates warnings for failure of front end inlining
5322 (activated by @option{-gnatN}) to inline a particular call. There are
5323 many reasons for not being able to inline a call, including most
5324 commonly that the call is too complex to inline. The default is
5325 that such warnings are not given.
5326 Warnings on ineffective inlining by the gcc back-end can be activated
5327 separately, using the gcc switch -Winline.
5329 @item -gnatwP
5330 @emph{Suppress warnings on ineffective pragma Inlines.}
5331 @cindex @option{-gnatwP} (@command{gcc})
5332 This switch suppresses warnings on ineffective pragma Inlines. If the
5333 inlining mechanism cannot inline a call, it will simply ignore the
5334 request silently.
5336 @item -gnatw.p
5337 @emph{Activate warnings on parameter ordering.}
5338 @cindex @option{-gnatw.p} (@command{gcc})
5339 @cindex Parameter order, warnings
5340 This switch activates warnings for cases of suspicious parameter
5341 ordering when the list of arguments are all simple identifiers that
5342 match the names of the formals, but are in a different order. The
5343 warning is suppressed if any use of named parameter notation is used,
5344 so this is the appropriate way to suppress a false positive (and
5345 serves to emphasize that the "misordering" is deliberate). The
5346 default is that such warnings are not given.
5348 @item -gnatw.P
5349 @emph{Suppress warnings on parameter ordering.}
5350 @cindex @option{-gnatw.P} (@command{gcc})
5351 This switch suppresses warnings on cases of suspicious parameter
5352 ordering.
5354 @item -gnatwq
5355 @emph{Activate warnings on questionable missing parentheses.}
5356 @cindex @option{-gnatwq} (@command{gcc})
5357 @cindex Parentheses, warnings
5358 This switch activates warnings for cases where parentheses are not used and
5359 the result is potential ambiguity from a readers point of view. For example
5360 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5361 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5362 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5363 follow the rule of always parenthesizing to make the association clear, and
5364 this warning switch warns if such parentheses are not present. The default
5365 is that these warnings are given.
5367 @item -gnatwQ
5368 @emph{Suppress warnings on questionable missing parentheses.}
5369 @cindex @option{-gnatwQ} (@command{gcc})
5370 This switch suppresses warnings for cases where the association is not
5371 clear and the use of parentheses is preferred.
5373 @item -gnatwr
5374 @emph{Activate warnings on redundant constructs.}
5375 @cindex @option{-gnatwr} (@command{gcc})
5376 This switch activates warnings for redundant constructs. The following
5377 is the current list of constructs regarded as redundant:
5379 @itemize @bullet
5380 @item
5381 Assignment of an item to itself.
5382 @item
5383 Type conversion that converts an expression to its own type.
5384 @item
5385 Use of the attribute @code{Base} where @code{typ'Base} is the same
5386 as @code{typ}.
5387 @item
5388 Use of pragma @code{Pack} when all components are placed by a record
5389 representation clause.
5390 @item
5391 Exception handler containing only a reraise statement (raise with no
5392 operand) which has no effect.
5393 @item
5394 Use of the operator abs on an operand that is known at compile time
5395 to be non-negative
5396 @item
5397 Comparison of boolean expressions to an explicit True value.
5398 @end itemize
5400 The default is that warnings for redundant constructs are not given.
5402 @item -gnatwR
5403 @emph{Suppress warnings on redundant constructs.}
5404 @cindex @option{-gnatwR} (@command{gcc})
5405 This switch suppresses warnings for redundant constructs.
5407 @item -gnatw.r
5408 @emph{Activate warnings for object renaming function.}
5409 @cindex @option{-gnatw.r} (@command{gcc})
5410 This switch activates warnings for an object renaming that renames a
5411 function call, which is equivalent to a constant declaration (as
5412 opposed to renaming the function itself).  The default is that these
5413 warnings are given.
5415 @item -gnatw.R
5416 @emph{Suppress warnings for object renaming function.}
5417 @cindex @option{-gnatwT} (@command{gcc})
5418 This switch suppresses warnings for object renaming function.
5420 @item -gnatws
5421 @emph{Suppress all warnings.}
5422 @cindex @option{-gnatws} (@command{gcc})
5423 This switch completely suppresses the
5424 output of all warning messages from the GNAT front end, including
5425 both warnings that can be controlled by switches described in this
5426 section, and those that are normally given unconditionally. The
5427 effect of this suppress action can only be cancelled by a subsequent
5428 use of the switch @option{-gnatwn}.
5430 Note that switch @option{-gnatws} does not suppress
5431 warnings from the @command{gcc} back end.
5432 To suppress these back end warnings as well, use the switch @option{-w}
5433 in addition to @option{-gnatws}. Also this switch has no effect on the
5434 handling of style check messages.
5436 @item -gnatw.s
5437 @emph{Activate warnings on overridden size clauses.}
5438 @cindex @option{-gnatw.s} (@command{gcc})
5439 @cindex Record Representation (component sizes)
5440 This switch activates warnings on component clauses in record
5441 representation clauses where the length given overrides that
5442 specified by an explicit size clause for the component type. A
5443 warning is similarly given in the array case if a specified
5444 component size overrides an explicit size clause for the array
5445 component type.
5447 @item -gnatw.S
5448 @emph{Suppress warnings on overridden size clauses.}
5449 @cindex @option{-gnatw.S} (@command{gcc})
5450 This switch suppresses warnings on component clauses in record
5451 representation clauses that override size clauses, and similar
5452 warnings when an array component size overrides a size clause.
5454 @item -gnatwt
5455 @emph{Activate warnings for tracking of deleted conditional code.}
5456 @cindex @option{-gnatwt} (@command{gcc})
5457 @cindex Deactivated code, warnings
5458 @cindex Deleted code, warnings
5459 This switch activates warnings for tracking of code in conditionals (IF and
5460 CASE statements) that is detected to be dead code which cannot be executed, and
5461 which is removed by the front end. This warning is off by default. This may be
5462 useful for detecting deactivated code in certified applications.
5464 @item -gnatwT
5465 @emph{Suppress warnings for tracking of deleted conditional code.}
5466 @cindex @option{-gnatwT} (@command{gcc})
5467 This switch suppresses warnings for tracking of deleted conditional code.
5469 @item -gnatw.t
5470 @emph{Activate warnings on suspicious contracts.}
5471 @cindex @option{-gnatw.t} (@command{gcc})
5472 This switch activates warnings on suspicious postconditions (whether a
5473 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5474 and suspicious contract cases (pragma @code{Contract_Cases}). A
5475 function postcondition or contract case is suspicious when no postcondition
5476 or contract case for this function mentions the result of the function.
5477 A procedure postcondition or contract case is suspicious when it only
5478 refers to the pre-state of the procedure, because in that case it should
5479 rather be expressed as a precondition. The default is that such warnings
5480 are not generated.
5482 @item -gnatw.T
5483 @emph{Suppress warnings on suspicious contracts.}
5484 @cindex @option{-gnatw.T} (@command{gcc})
5485 This switch suppresses warnings on suspicious postconditions.
5487 @item -gnatwu
5488 @emph{Activate warnings on unused entities.}
5489 @cindex @option{-gnatwu} (@command{gcc})
5490 This switch activates warnings to be generated for entities that
5491 are declared but not referenced, and for units that are @code{with}'ed
5492 and not
5493 referenced. In the case of packages, a warning is also generated if
5494 no entities in the package are referenced. This means that if a with'ed
5495 package is referenced but the only references are in @code{use}
5496 clauses or @code{renames}
5497 declarations, a warning is still generated. A warning is also generated
5498 for a generic package that is @code{with}'ed but never instantiated.
5499 In the case where a package or subprogram body is compiled, and there
5500 is a @code{with} on the corresponding spec
5501 that is only referenced in the body,
5502 a warning is also generated, noting that the
5503 @code{with} can be moved to the body. The default is that
5504 such warnings are not generated.
5505 This switch also activates warnings on unreferenced formals
5506 (it includes the effect of @option{-gnatwf}).
5508 @item -gnatwU
5509 @emph{Suppress warnings on unused entities.}
5510 @cindex @option{-gnatwU} (@command{gcc})
5511 This switch suppresses warnings for unused entities and packages.
5512 It also turns off warnings on unreferenced formals (and thus includes
5513 the effect of @option{-gnatwF}).
5515 @item -gnatw.u
5516 @emph{Activate warnings on unordered enumeration types.}
5517 @cindex @option{-gnatw.u} (@command{gcc})
5518 This switch causes enumeration types to be considered as conceptually
5519 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5520 The effect is to generate warnings in clients that use explicit comparisons
5521 or subranges, since these constructs both treat objects of the type as
5522 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5523 which the type is declared, or its body or subunits.) Please refer to
5524 the description of pragma @code{Ordered} in the
5525 @cite{@value{EDITION} Reference Manual} for further details.
5526 The default is that such warnings are not generated.
5528 @item -gnatw.U
5529 @emph{Deactivate warnings on unordered enumeration types.}
5530 @cindex @option{-gnatw.U} (@command{gcc})
5531 This switch causes all enumeration types to be considered as ordered, so
5532 that no warnings are given for comparisons or subranges for any type.
5534 @item -gnatwv
5535 @emph{Activate warnings on unassigned variables.}
5536 @cindex @option{-gnatwv} (@command{gcc})
5537 @cindex Unassigned variable warnings
5538 This switch activates warnings for access to variables which
5539 may not be properly initialized. The default is that
5540 such warnings are generated.
5542 @item -gnatwV
5543 @emph{Suppress warnings on unassigned variables.}
5544 @cindex @option{-gnatwV} (@command{gcc})
5545 This switch suppresses warnings for access to variables which
5546 may not be properly initialized.
5547 For variables of a composite type, the warning can also be suppressed in
5548 Ada 2005 by using a default initialization with a box. For example, if
5549 Table is an array of records whose components are only partially uninitialized,
5550 then the following code:
5552 @smallexample @c ada
5553    Tab : Table := (@b{others} => <>);
5554 @end smallexample
5556 will suppress warnings on subsequent statements that access components
5557 of variable Tab.
5559 @item -gnatw.v
5560 @emph{Activate info messages for non-default bit order.}
5561 @cindex @option{-gnatw.v} (@command{gcc})
5562 @cindex bit order warnings
5563 This switch activates messages (labeled "info", they are not warnings,
5564 just informational messages) about the effects of non-default bit-order
5565 on records to which a component clause is applied. The effect of specifying
5566 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5567 these messages, which are given by default, are useful in understanding the
5568 exact consequences of using this feature.
5570 @item -gnatw.V
5571 @emph{Suppress info messages for non-default bit order.}
5572 @cindex @option{-gnatw.V} (@command{gcc})
5573 This switch suppresses information messages for the effects of specifying
5574 non-default bit order on record components with component clauses.
5576 @item -gnatww
5577 @emph{Activate warnings on wrong low bound assumption.}
5578 @cindex @option{-gnatww} (@command{gcc})
5579 @cindex String indexing warnings
5580 This switch activates warnings for indexing an unconstrained string parameter
5581 with a literal or S'Length. This is a case where the code is assuming that the
5582 low bound is one, which is in general not true (for example when a slice is
5583 passed). The default is that such warnings are generated.
5585 @item -gnatwW
5586 @emph{Suppress warnings on wrong low bound assumption.}
5587 @cindex @option{-gnatwW} (@command{gcc})
5588 This switch suppresses warnings for indexing an unconstrained string parameter
5589 with a literal or S'Length. Note that this warning can also be suppressed
5590 in a particular case by adding an
5591 assertion that the lower bound is 1,
5592 as shown in the following example.
5594 @smallexample @c ada
5595    @b{procedure} K (S : String) @b{is}
5596       @b{pragma} Assert (S'First = 1);
5597       @dots{}
5598 @end smallexample
5600 @item -gnatw.w
5601 @emph{Activate warnings on Warnings Off pragmas}
5602 @cindex @option{-gnatw.w} (@command{gcc})
5603 @cindex Warnings Off control
5604 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5605 where either the pragma is entirely useless (because it suppresses no
5606 warnings), or it could be replaced by @code{pragma Unreferenced} or
5607 @code{pragma Unmodified}.
5608 Also activates warnings for the case of
5609 Warnings (Off, String), where either there is no matching
5610 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
5611 The default is that these warnings are not given.
5613 @item -gnatw.W
5614 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5615 @cindex @option{-gnatw.W} (@command{gcc})
5616 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
5618 @item -gnatwx
5619 @emph{Activate warnings on Export/Import pragmas.}
5620 @cindex @option{-gnatwx} (@command{gcc})
5621 @cindex Export/Import pragma warnings
5622 This switch activates warnings on Export/Import pragmas when
5623 the compiler detects a possible conflict between the Ada and
5624 foreign language calling sequences. For example, the use of
5625 default parameters in a convention C procedure is dubious
5626 because the C compiler cannot supply the proper default, so
5627 a warning is issued. The default is that such warnings are
5628 generated.
5630 @item -gnatwX
5631 @emph{Suppress warnings on Export/Import pragmas.}
5632 @cindex @option{-gnatwX} (@command{gcc})
5633 This switch suppresses warnings on Export/Import pragmas.
5634 The sense of this is that you are telling the compiler that
5635 you know what you are doing in writing the pragma, and it
5636 should not complain at you.
5638 @item -gnatw.x
5639 @emph{Activate warnings for No_Exception_Propagation mode.}
5640 @cindex @option{-gnatwm} (@command{gcc})
5641 This switch activates warnings for exception usage when pragma Restrictions
5642 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5643 explicit exception raises which are not covered by a local handler, and for
5644 exception handlers which do not cover a local raise. The default is that these
5645 warnings are not given.
5647 @item -gnatw.X
5648 @emph{Disable warnings for No_Exception_Propagation mode.}
5649 This switch disables warnings for exception usage when pragma Restrictions
5650 (No_Exception_Propagation) is in effect.
5652 @item -gnatwy
5653 @emph{Activate warnings for Ada compatibility issues.}
5654 @cindex @option{-gnatwy} (@command{gcc})
5655 @cindex Ada compatibility issues warnings
5656 For the most part, newer versions of Ada are upwards compatible
5657 with older versions. For example, Ada 2005 programs will almost
5658 always work when compiled as Ada 2012.
5659 However there are some exceptions (for example the fact that
5660 @code{some} is now a reserved word in Ada 2012). This
5661 switch activates several warnings to help in identifying
5662 and correcting such incompatibilities. The default is that
5663 these warnings are generated. Note that at one point Ada 2005
5664 was called Ada 0Y, hence the choice of character.
5666 @item -gnatwY
5667 @emph{Disable warnings for Ada compatibility issues.}
5668 @cindex @option{-gnatwY} (@command{gcc})
5669 @cindex Ada compatibility issues warnings
5670 This switch suppresses the warnings intended to help in identifying
5671 incompatibilities between Ada language versions.
5673 @item -gnatw.y
5674 @emph{Activate information messages for why package spec needs body}
5675 @cindex @option{-gnatw.y} (@command{gcc})
5676 @cindex Package spec needing body
5677 There are a number of cases in which a package spec needs a body.
5678 For example, the use of pragma Elaborate_Body, or the declaration
5679 of a procedure specification requiring a completion. This switch
5680 causes information messages to be output showing why a package
5681 specification requires a body. This can be useful in the case of
5682 a large package specification which is unexpectedly requiring a
5683 body. The default is that such information messages are not output.
5685 @item -gnatw.Y
5686 @emph{Disable information messages for why package spec needs body}
5687 @cindex @option{-gnatw.Y} (@command{gcc})
5688 @cindex No information messages for why package spec needs body
5689 This switch suppresses the output of information messages showing why
5690 a package specification needs a body.
5692 @item -gnatwz
5693 @emph{Activate warnings on unchecked conversions.}
5694 @cindex @option{-gnatwz} (@command{gcc})
5695 @cindex Unchecked_Conversion warnings
5696 This switch activates warnings for unchecked conversions
5697 where the types are known at compile time to have different
5698 sizes. The default
5699 is that such warnings are generated. Warnings are also
5700 generated for subprogram pointers with different conventions,
5701 and, on VMS only, for data pointers with different conventions.
5703 @item -gnatwZ
5704 @emph{Suppress warnings on unchecked conversions.}
5705 @cindex @option{-gnatwZ} (@command{gcc})
5706 This switch suppresses warnings for unchecked conversions
5707 where the types are known at compile time to have different
5708 sizes or conventions.
5710 @item -gnatw.z
5711 @emph{Activate warnings for size not a multiple of alignment.}
5712 @cindex @option{-gnatw.z} (@command{gcc})
5713 @cindex Size/Alignment warnings
5714 This switch activates warnings for cases of record types with
5715 specified @code{Size} and @code{Alignment} attributes where the
5716 size is not a multiple of the alignment, resulting in an object
5717 size that is greater than the specified size. The default
5718 is that such warnings are generated.
5720 @item -gnatw.Z
5721 @emph{Suppress warnings for size not a multiple of alignment.}
5722 @cindex @option{-gnatw.Z} (@command{gcc})
5723 @cindex Size/Alignment warnings
5724 This switch suppresses warnings for cases of record types with
5725 specified @code{Size} and @code{Alignment} attributes where the
5726 size is not a multiple of the alignment, resulting in an object
5727 size that is greater than the specified size.
5728 The warning can also be
5729 suppressed by giving an explicit @code{Object_Size} value.
5731 @item -Wunused
5732 @cindex @option{-Wunused}
5733 The warnings controlled by the @option{-gnatw} switch are generated by
5734 the front end of the compiler. The @option{GCC} back end can provide
5735 additional warnings and they are controlled by the @option{-W} switch.
5736 For example, @option{-Wunused} activates back end
5737 warnings for entities that are declared but not referenced.
5739 @item -Wuninitialized
5740 @cindex @option{-Wuninitialized}
5741 Similarly, @option{-Wuninitialized} activates
5742 the back end warning for uninitialized variables. This switch must be
5743 used in conjunction with an optimization level greater than zero.
5745 @item -Wstack-usage=@var{len}
5746 @cindex @option{-Wstack-usage}
5747 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5748 See @ref{Static Stack Usage Analysis} for details.
5750 @item -Wall
5751 @cindex @option{-Wall}
5752 This switch enables most warnings from the @option{GCC} back end.
5753 The code generator detects a number of warning situations that are missed
5754 by the @option{GNAT} front end, and this switch can be used to activate them.
5755 The use of this switch also sets the default front end warning mode to
5756 @option{-gnatwa}, that is, most front end warnings activated as well.
5758 @item -w
5759 @cindex @option{-w}
5760 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5761 The use of this switch also sets the default front end warning mode to
5762 @option{-gnatws}, that is, front end warnings suppressed as well.
5764 @item -Werror
5765 @cindex @option{-Werror}
5766 This switch causes warnings from the @option{GCC} back end to be treated as
5767 errors.  The warning string still appears, but the warning messages are
5768 counted as errors, and prevent the generation of an object file.
5770 @end table
5772 @noindent
5773 A string of warning parameters can be used in the same parameter. For example:
5775 @smallexample
5776 -gnatwaGe
5777 @end smallexample
5779 @noindent
5780 will turn on all optional warnings except for unrecognized pragma warnings,
5781 and also specify that warnings should be treated as errors.
5783 When no switch @option{-gnatw} is used, this is equivalent to:
5785 @table @option
5786 @c !sort!
5787 @item -gnatw.a
5788 @item -gnatwB
5789 @item -gnatw.b
5790 @item -gnatwC
5791 @item -gnatw.C
5792 @item -gnatwD
5793 @item -gnatwF
5794 @item -gnatwg
5795 @item -gnatwH
5796 @item -gnatwi
5797 @item -gnatw.I
5798 @item -gnatwJ
5799 @item -gnatwK
5800 @item -gnatwL
5801 @item -gnatw.L
5802 @item -gnatwM
5803 @item -gnatw.m
5804 @item -gnatwn
5805 @item -gnatwo
5806 @item -gnatw.O
5807 @item -gnatwP
5808 @item -gnatw.P
5809 @item -gnatwq
5810 @item -gnatwR
5811 @item -gnatw.R
5812 @item -gnatw.S
5813 @item -gnatwT
5814 @item -gnatw.T
5815 @item -gnatwU
5816 @item -gnatwv
5817 @item -gnatww
5818 @item -gnatw.W
5819 @item -gnatwx
5820 @item -gnatw.X
5821 @item -gnatwy
5822 @item -gnatwz
5824 @end table
5826 @node Debugging and Assertion Control
5827 @subsection Debugging and Assertion Control
5829 @table @option
5830 @item -gnata
5831 @cindex @option{-gnata} (@command{gcc})
5832 @findex Assert
5833 @findex Debug
5834 @cindex Assertions
5836 @noindent
5837 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5838 are ignored. This switch, where @samp{a} stands for assert, causes
5839 @code{Assert} and @code{Debug} pragmas to be activated.
5841 The pragmas have the form:
5843 @smallexample
5844 @cartouche
5845    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5846                       @var{static-string-expression}@r{]})
5847    @b{pragma} Debug (@var{procedure call})
5848 @end cartouche
5849 @end smallexample
5851 @noindent
5852 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5853 If the result is @code{True}, the pragma has no effect (other than
5854 possible side effects from evaluating the expression). If the result is
5855 @code{False}, the exception @code{Assert_Failure} declared in the package
5856 @code{System.Assertions} is
5857 raised (passing @var{static-string-expression}, if present, as the
5858 message associated with the exception). If no string expression is
5859 given the default is a string giving the file name and line number
5860 of the pragma.
5862 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5863 @code{pragma Debug} may appear within a declaration sequence, allowing
5864 debugging procedures to be called between declarations.
5866 @end table
5868 @node Validity Checking
5869 @subsection Validity Checking
5870 @findex Validity Checking
5872 @noindent
5873 The Ada Reference Manual defines the concept of invalid values (see
5874 RM 13.9.1). The primary source of invalid values is uninitialized
5875 variables. A scalar variable that is left uninitialized may contain
5876 an invalid value; the concept of invalid does not apply to access or
5877 composite types.
5879 It is an error to read an invalid value, but the RM does not require
5880 run-time checks to detect such errors, except for some minimal
5881 checking to prevent erroneous execution (i.e. unpredictable
5882 behavior). This corresponds to the @option{-gnatVd} switch below,
5883 which is the default. For example, by default, if the expression of a
5884 case statement is invalid, it will raise Constraint_Error rather than
5885 causing a wild jump, and if an array index on the left-hand side of an
5886 assignment is invalid, it will raise Constraint_Error rather than
5887 overwriting an arbitrary memory location.
5889 The @option{-gnatVa} may be used to enable additional validity checks,
5890 which are not required by the RM. These checks are often very
5891 expensive (which is why the RM does not require them). These checks
5892 are useful in tracking down uninitialized variables, but they are
5893 not usually recommended for production builds, and in particular
5894 we do not recommend using these extra validity checking options in
5895 combination with optimization, since this can confuse the optimizer.
5896 If performance is a consideration, leading to the need to optimize,
5897 then the validity checking options should not be used.
5899 The other @option{-gnatV@var{x}} switches below allow finer-grained
5900 control; you can enable whichever validity checks you desire. However,
5901 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5902 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5903 sufficient for non-debugging use.
5905 The @option{-gnatB} switch tells the compiler to assume that all
5906 values are valid (that is, within their declared subtype range)
5907 except in the context of a use of the Valid attribute. This means
5908 the compiler can generate more efficient code, since the range
5909 of values is better known at compile time. However, an uninitialized
5910 variable can cause wild jumps and memory corruption in this mode.
5912 The @option{-gnatV@var{x}} switch allows control over the validity
5913 checking mode as described below.
5914 The @code{x} argument is a string of letters that
5915 indicate validity checks that are performed or not performed in addition
5916 to the default checks required by Ada as described above.
5918 @table @option
5919 @c !sort!
5920 @item -gnatVa
5921 @emph{All validity checks.}
5922 @cindex @option{-gnatVa} (@command{gcc})
5923 All validity checks are turned on.
5924 That is, @option{-gnatVa} is
5925 equivalent to @option{gnatVcdfimorst}.
5927 @item -gnatVc
5928 @emph{Validity checks for copies.}
5929 @cindex @option{-gnatVc} (@command{gcc})
5930 The right hand side of assignments, and the initializing values of
5931 object declarations are validity checked.
5933 @item -gnatVd
5934 @emph{Default (RM) validity checks.}
5935 @cindex @option{-gnatVd} (@command{gcc})
5936 Some validity checks are done by default following normal Ada semantics
5937 (RM 13.9.1 (9-11)).
5938 A check is done in case statements that the expression is within the range
5939 of the subtype. If it is not, Constraint_Error is raised.
5940 For assignments to array components, a check is done that the expression used
5941 as index is within the range. If it is not, Constraint_Error is raised.
5942 Both these validity checks may be turned off using switch @option{-gnatVD}.
5943 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5944 switch @option{-gnatVd} will leave the checks turned on.
5945 Switch @option{-gnatVD} should be used only if you are sure that all such
5946 expressions have valid values. If you use this switch and invalid values
5947 are present, then the program is erroneous, and wild jumps or memory
5948 overwriting may occur.
5950 @item -gnatVe
5951 @emph{Validity checks for elementary components.}
5952 @cindex @option{-gnatVe} (@command{gcc})
5953 In the absence of this switch, assignments to record or array components are
5954 not validity checked, even if validity checks for assignments generally
5955 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5956 require valid data, but assignment of individual components does. So for
5957 example, there is a difference between copying the elements of an array with a
5958 slice assignment, compared to assigning element by element in a loop. This
5959 switch allows you to turn off validity checking for components, even when they
5960 are assigned component by component.
5962 @item -gnatVf
5963 @emph{Validity checks for floating-point values.}
5964 @cindex @option{-gnatVf} (@command{gcc})
5965 In the absence of this switch, validity checking occurs only for discrete
5966 values. If @option{-gnatVf} is specified, then validity checking also applies
5967 for floating-point values, and NaNs and infinities are considered invalid,
5968 as well as out of range values for constrained types. Note that this means
5969 that standard IEEE infinity mode is not allowed. The exact contexts
5970 in which floating-point values are checked depends on the setting of other
5971 options. For example,
5972 @option{-gnatVif} or
5973 @option{-gnatVfi}
5974 (the order does not matter) specifies that floating-point parameters of mode
5975 @code{in} should be validity checked.
5977 @item -gnatVi
5978 @emph{Validity checks for @code{in} mode parameters}
5979 @cindex @option{-gnatVi} (@command{gcc})
5980 Arguments for parameters of mode @code{in} are validity checked in function
5981 and procedure calls at the point of call.
5983 @item -gnatVm
5984 @emph{Validity checks for @code{in out} mode parameters.}
5985 @cindex @option{-gnatVm} (@command{gcc})
5986 Arguments for parameters of mode @code{in out} are validity checked in
5987 procedure calls at the point of call. The @code{'m'} here stands for
5988 modify, since this concerns parameters that can be modified by the call.
5989 Note that there is no specific option to test @code{out} parameters,
5990 but any reference within the subprogram will be tested in the usual
5991 manner, and if an invalid value is copied back, any reference to it
5992 will be subject to validity checking.
5994 @item -gnatVn
5995 @emph{No validity checks.}
5996 @cindex @option{-gnatVn} (@command{gcc})
5997 This switch turns off all validity checking, including the default checking
5998 for case statements and left hand side subscripts. Note that the use of
5999 the switch @option{-gnatp} suppresses all run-time checks, including
6000 validity checks, and thus implies @option{-gnatVn}. When this switch
6001 is used, it cancels any other @option{-gnatV} previously issued.
6003 @item -gnatVo
6004 @emph{Validity checks for operator and attribute operands.}
6005 @cindex @option{-gnatVo} (@command{gcc})
6006 Arguments for predefined operators and attributes are validity checked.
6007 This includes all operators in package @code{Standard},
6008 the shift operators defined as intrinsic in package @code{Interfaces}
6009 and operands for attributes such as @code{Pos}. Checks are also made
6010 on individual component values for composite comparisons, and on the
6011 expressions in type conversions and qualified expressions. Checks are
6012 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6014 @item -gnatVp
6015 @emph{Validity checks for parameters.}
6016 @cindex @option{-gnatVp} (@command{gcc})
6017 This controls the treatment of parameters within a subprogram (as opposed
6018 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6019 of parameters on a call. If either of these call options is used, then
6020 normally an assumption is made within a subprogram that the input arguments
6021 have been validity checking at the point of call, and do not need checking
6022 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6023 is not made, and parameters are not assumed to be valid, so their validity
6024 will be checked (or rechecked) within the subprogram.
6026 @item -gnatVr
6027 @emph{Validity checks for function returns.}
6028 @cindex @option{-gnatVr} (@command{gcc})
6029 The expression in @code{return} statements in functions is validity
6030 checked.
6032 @item -gnatVs
6033 @emph{Validity checks for subscripts.}
6034 @cindex @option{-gnatVs} (@command{gcc})
6035 All subscripts expressions are checked for validity, whether they appear
6036 on the right side or left side (in default mode only left side subscripts
6037 are validity checked).
6039 @item -gnatVt
6040 @emph{Validity checks for tests.}
6041 @cindex @option{-gnatVt} (@command{gcc})
6042 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6043 statements are checked, as well as guard expressions in entry calls.
6045 @end table
6047 @noindent
6048 The @option{-gnatV} switch may be followed by
6049 a string of letters
6050 to turn on a series of validity checking options.
6051 For example,
6052 @option{-gnatVcr}
6053 specifies that in addition to the default validity checking, copies and
6054 function return expressions are to be validity checked.
6055 In order to make it easier
6056 to specify the desired combination of effects,
6057 the upper case letters @code{CDFIMORST} may
6058 be used to turn off the corresponding lower case option.
6059 Thus
6060 @option{-gnatVaM}
6061 turns on all validity checking options except for
6062 checking of @code{@b{in out}} procedure arguments.
6064 The specification of additional validity checking generates extra code (and
6065 in the case of @option{-gnatVa} the code expansion can be substantial).
6066 However, these additional checks can be very useful in detecting
6067 uninitialized variables, incorrect use of unchecked conversion, and other
6068 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6069 is useful in conjunction with the extra validity checking, since this
6070 ensures that wherever possible uninitialized variables have invalid values.
6072 See also the pragma @code{Validity_Checks} which allows modification of
6073 the validity checking mode at the program source level, and also allows for
6074 temporary disabling of validity checks.
6076 @node Style Checking
6077 @subsection Style Checking
6078 @findex Style checking
6080 @noindent
6081 The @option{-gnatyx} switch
6082 @cindex @option{-gnaty} (@command{gcc})
6083 causes the compiler to
6084 enforce specified style rules. A limited set of style rules has been used
6085 in writing the GNAT sources themselves. This switch allows user programs
6086 to activate all or some of these checks. If the source program fails a
6087 specified style check, an appropriate message is given, preceded by
6088 the character sequence ``(style)''. This message does not prevent
6089 successful compilation (unless the @option{-gnatwe} switch is used).
6091 Note that this is by no means intended to be a general facility for
6092 checking arbitrary coding standards. It is simply an embedding of the
6093 style rules we have chosen for the GNAT sources. If you are starting
6094 a project which does not have established style standards, you may
6095 find it useful to adopt the entire set of GNAT coding standards, or
6096 some subset of them.
6097 @ifclear FSFEDITION
6098 If you already have an established set of coding
6099 standards, then the selected style checking options may
6100 indeed correspond to choices you have made, but for general checking
6101 of an existing set of coding rules, you should look to the gnatcheck
6102 tool, which is designed for that purpose.
6103 @end ifclear
6105 The string @var{x} is a sequence of letters or digits
6106 indicating the particular style
6107 checks to be performed. The following checks are defined:
6109 @table @option
6110 @c !sort!
6111 @item 0-9
6112 @emph{Specify indentation level.}
6113 If a digit from 1-9 appears
6114 in the string after @option{-gnaty}
6115 then proper indentation is checked, with the digit indicating the
6116 indentation level required. A value of zero turns off this style check.
6117 The general style of required indentation is as specified by
6118 the examples in the Ada Reference Manual. Full line comments must be
6119 aligned with the @code{--} starting on a column that is a multiple of
6120 the alignment level, or they may be aligned the same way as the following
6121 non-blank line (this is useful when full line comments appear in the middle
6122 of a statement, or they may be aligned with the source line on the previous
6123 non-blank line.
6125 @item a
6126 @emph{Check attribute casing.}
6127 Attribute names, including the case of keywords such as @code{digits}
6128 used as attributes names, must be written in mixed case, that is, the
6129 initial letter and any letter following an underscore must be uppercase.
6130 All other letters must be lowercase.
6132 @item A
6133 @emph{Use of array index numbers in array attributes.}
6134 When using the array attributes First, Last, Range,
6135 or Length, the index number must be omitted for one-dimensional arrays
6136 and is required for multi-dimensional arrays.
6138 @item b
6139 @emph{Blanks not allowed at statement end.}
6140 Trailing blanks are not allowed at the end of statements. The purpose of this
6141 rule, together with h (no horizontal tabs), is to enforce a canonical format
6142 for the use of blanks to separate source tokens.
6144 @item B
6145 @emph{Check Boolean operators.}
6146 The use of AND/OR operators is not permitted except in the cases of modular
6147 operands, array operands, and simple stand-alone boolean variables or
6148 boolean constants. In all other cases @code{and then}/@code{or else} are
6149 required.
6151 @item c
6152 @emph{Check comments, double space.}
6153 Comments must meet the following set of rules:
6155 @itemize @bullet
6157 @item
6158 The ``@code{--}'' that starts the column must either start in column one,
6159 or else at least one blank must precede this sequence.
6161 @item
6162 Comments that follow other tokens on a line must have at least one blank
6163 following the ``@code{--}'' at the start of the comment.
6165 @item
6166 Full line comments must have at least two blanks following the
6167 ``@code{--}'' that starts the comment, with the following exceptions.
6169 @item
6170 A line consisting only of the ``@code{--}'' characters, possibly preceded
6171 by blanks is permitted.
6173 @item
6174 A comment starting with ``@code{--x}'' where @code{x} is a special character
6175 is permitted.
6176 This allows proper processing of the output generated by specialized tools
6177 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6178 annotation
6179 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6180 special character is defined as being in one of the ASCII ranges
6181 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6182 Note that this usage is not permitted
6183 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6185 @item
6186 A line consisting entirely of minus signs, possibly preceded by blanks, is
6187 permitted. This allows the construction of box comments where lines of minus
6188 signs are used to form the top and bottom of the box.
6190 @item
6191 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6192 least one blank follows the initial ``@code{--}''. Together with the preceding
6193 rule, this allows the construction of box comments, as shown in the following
6194 example:
6195 @smallexample
6196 ---------------------------
6197 -- This is a box comment --
6198 -- with two text lines.  --
6199 ---------------------------
6200 @end smallexample
6201 @end itemize
6203 @item C
6204 @emph{Check comments, single space.}
6205 This is identical to @code{c} except that only one space
6206 is required following the @code{--} of a comment instead of two.
6208 @item d
6209 @emph{Check no DOS line terminators present.}
6210 All lines must be terminated by a single ASCII.LF
6211 character (in particular the DOS line terminator sequence CR/LF is not
6212 allowed).
6214 @item e
6215 @emph{Check end/exit labels.}
6216 Optional labels on @code{end} statements ending subprograms and on
6217 @code{exit} statements exiting named loops, are required to be present.
6219 @item f
6220 @emph{No form feeds or vertical tabs.}
6221 Neither form feeds nor vertical tab characters are permitted
6222 in the source text.
6224 @item g
6225 @emph{GNAT style mode.}
6226 The set of style check switches is set to match that used by the GNAT sources.
6227 This may be useful when developing code that is eventually intended to be
6228 incorporated into GNAT. Currently this is equivalent to @option{-gnatwydISux})
6229 but additional style switches may be added to this set in the future without
6230 advance notice.
6232 @item h
6233 @emph{No horizontal tabs.}
6234 Horizontal tab characters are not permitted in the source text.
6235 Together with the b (no blanks at end of line) check, this
6236 enforces a canonical form for the use of blanks to separate
6237 source tokens.
6239 @item i
6240 @emph{Check if-then layout.}
6241 The keyword @code{then} must appear either on the same
6242 line as corresponding @code{if}, or on a line on its own, lined
6243 up under the @code{if}.
6245 @item I
6246 @emph{check mode IN keywords.}
6247 Mode @code{in} (the default mode) is not
6248 allowed to be given explicitly. @code{in out} is fine,
6249 but not @code{in} on its own.
6251 @item k
6252 @emph{Check keyword casing.}
6253 All keywords must be in lower case (with the exception of keywords
6254 such as @code{digits} used as attribute names to which this check
6255 does not apply).
6257 @item l
6258 @emph{Check layout.}
6259 Layout of statement and declaration constructs must follow the
6260 recommendations in the Ada Reference Manual, as indicated by the
6261 form of the syntax rules. For example an @code{else} keyword must
6262 be lined up with the corresponding @code{if} keyword.
6264 There are two respects in which the style rule enforced by this check
6265 option are more liberal than those in the Ada Reference Manual. First
6266 in the case of record declarations, it is permissible to put the
6267 @code{record} keyword on the same line as the @code{type} keyword, and
6268 then the @code{end} in @code{end record} must line up under @code{type}.
6269 This is also permitted when the type declaration is split on two lines.
6270 For example, any of the following three layouts is acceptable:
6272 @smallexample @c ada
6273 @cartouche
6274 @b{type} q @b{is} @b{record}
6275    a : integer;
6276    b : integer;
6277 @b{end} @b{record};
6279 @b{type} q @b{is}
6280    @b{record}
6281       a : integer;
6282       b : integer;
6283    @b{end} @b{record};
6285 @b{type} q @b{is}
6286    @b{record}
6287       a : integer;
6288       b : integer;
6289 @b{end} @b{record};
6291 @end cartouche
6292 @end smallexample
6294 @noindent
6295 Second, in the case of a block statement, a permitted alternative
6296 is to put the block label on the same line as the @code{declare} or
6297 @code{begin} keyword, and then line the @code{end} keyword up under
6298 the block label. For example both the following are permitted:
6300 @smallexample @c ada
6301 @cartouche
6302 Block : @b{declare}
6303    A : Integer := 3;
6304 @b{begin}
6305    Proc (A, A);
6306 @b{end} Block;
6308 Block :
6309    @b{declare}
6310       A : Integer := 3;
6311    @b{begin}
6312       Proc (A, A);
6313    @b{end} Block;
6314 @end cartouche
6315 @end smallexample
6317 @noindent
6318 The same alternative format is allowed for loops. For example, both of
6319 the following are permitted:
6321 @smallexample @c ada
6322 @cartouche
6323 Clear : @b{while} J < 10 @b{loop}
6324    A (J) := 0;
6325 @b{end} @b{loop} Clear;
6327 Clear :
6328    @b{while} J < 10 @b{loop}
6329       A (J) := 0;
6330    @b{end} @b{loop} Clear;
6331 @end cartouche
6332 @end smallexample
6334 @item Lnnn
6335 @emph{Set maximum nesting level.}
6336 The maximum level of nesting of constructs (including subprograms, loops,
6337 blocks, packages, and conditionals) may not exceed the given value
6338 @option{nnn}. A value of zero disconnects this style check.
6340 @item m
6341 @emph{Check maximum line length.}
6342 The length of source lines must not exceed 79 characters, including
6343 any trailing blanks. The value of 79 allows convenient display on an
6344 80 character wide device or window, allowing for possible special
6345 treatment of 80 character lines. Note that this count is of
6346 characters in the source text. This means that a tab character counts
6347 as one character in this count and a wide character sequence counts as
6348 a single character (however many bytes are needed in the encoding).
6350 @item Mnnn
6351 @emph{Set maximum line length.}
6352 The length of lines must not exceed the
6353 given value @option{nnn}. The maximum value that can be specified is 32767.
6354 If neither style option for setting the line length is used, then the
6355 default is 255. This also controls the maximum length of lexical elements,
6356 where the only restriction is that they must fit on a single line.
6358 @item n
6359 @emph{Check casing of entities in Standard.}
6360 Any identifier from Standard must be cased
6361 to match the presentation in the Ada Reference Manual (for example,
6362 @code{Integer} and @code{ASCII.NUL}).
6364 @item N
6365 @emph{Turn off all style checks.}
6366 All style check options are turned off.
6368 @item o
6369 @emph{Check order of subprogram bodies.}
6370 All subprogram bodies in a given scope
6371 (e.g.@: a package body) must be in alphabetical order. The ordering
6372 rule uses normal Ada rules for comparing strings, ignoring casing
6373 of letters, except that if there is a trailing numeric suffix, then
6374 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6375 before Junk10).
6377 @item O
6378 @emph{Check that overriding subprograms are explicitly marked as such.}
6379 The declaration of a primitive operation of a type extension that overrides
6380 an inherited operation must carry an overriding indicator.
6382 @item p
6383 @emph{Check pragma casing.}
6384 Pragma names must be written in mixed case, that is, the
6385 initial letter and any letter following an underscore must be uppercase.
6386 All other letters must be lowercase. An exception is that SPARK_Mode is
6387 allowed as an alternative for Spark_Mode.
6389 @item r
6390 @emph{Check references.}
6391 All identifier references must be cased in the same way as the
6392 corresponding declaration. No specific casing style is imposed on
6393 identifiers. The only requirement is for consistency of references
6394 with declarations.
6396 @item s
6397 @emph{Check separate specs.}
6398 Separate declarations (``specs'') are required for subprograms (a
6399 body is not allowed to serve as its own declaration). The only
6400 exception is that parameterless library level procedures are
6401 not required to have a separate declaration. This exception covers
6402 the most frequent form of main program procedures.
6404 @item S
6405 @emph{Check no statements after @code{then}/@code{else}.}
6406 No statements are allowed
6407 on the same line as a @code{then} or @code{else} keyword following the
6408 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6409 affected, and a special exception allows a pragma to appear after @code{else}.
6411 @item t
6412 @emph{Check token spacing.}
6413 The following token spacing rules are enforced:
6415 @itemize @bullet
6417 @item
6418 The keywords @code{abs} and @code{not} must be followed by a space.
6420 @item
6421 The token @code{=>} must be surrounded by spaces.
6423 @item
6424 The token @code{<>} must be preceded by a space or a left parenthesis.
6426 @item
6427 Binary operators other than @code{**} must be surrounded by spaces.
6428 There is no restriction on the layout of the @code{**} binary operator.
6430 @item
6431 Colon must be surrounded by spaces.
6433 @item
6434 Colon-equal (assignment, initialization) must be surrounded by spaces.
6436 @item
6437 Comma must be the first non-blank character on the line, or be
6438 immediately preceded by a non-blank character, and must be followed
6439 by a space.
6441 @item
6442 If the token preceding a left parenthesis ends with a letter or digit, then
6443 a space must separate the two tokens.
6445 @item
6446 if the token following a right parenthesis starts with a letter or digit, then
6447 a space must separate the two tokens.
6449 @item
6450 A right parenthesis must either be the first non-blank character on
6451 a line, or it must be preceded by a non-blank character.
6453 @item
6454 A semicolon must not be preceded by a space, and must not be followed by
6455 a non-blank character.
6457 @item
6458 A unary plus or minus may not be followed by a space.
6460 @item
6461 A vertical bar must be surrounded by spaces.
6462 @end itemize
6464 Exactly one blank (and no other white space) must appear between
6465 a @code{not} token and a following @code{in} token.
6467 @item u
6468 @emph{Check unnecessary blank lines.}
6469 Unnecessary blank lines are not allowed. A blank line is considered
6470 unnecessary if it appears at the end of the file, or if more than
6471 one blank line occurs in sequence.
6473 @item x
6474 @emph{Check extra parentheses.}
6475 Unnecessary extra level of parentheses (C-style) are not allowed
6476 around conditions in @code{if} statements, @code{while} statements and
6477 @code{exit} statements.
6479 @item y
6480 @emph{Set all standard style check options}
6481 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6482 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6483 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6484 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6486 @item -
6487 @emph{Remove style check options}
6488 This causes any subsequent options in the string to act as canceling the
6489 corresponding style check option. To cancel maximum nesting level control,
6490 use @option{L} parameter witout any integer value after that, because any
6491 digit following @option{-} in the parameter string of the @option{-gnaty}
6492 option will be threated as canceling indentation check. The same is true
6493 for @option{M} parameter. @option{y} and @option{N} parameters are not
6494 allowed after @option{-}.
6496 @item +
6497 This causes any subsequent options in the string to enable the corresponding
6498 style check option. That is, it cancels the effect of a previous -,
6499 if any.
6501 @end table
6503 @noindent
6504 In the above rules, appearing in column one is always permitted, that is,
6505 counts as meeting either a requirement for a required preceding space,
6506 or as meeting a requirement for no preceding space.
6508 Appearing at the end of a line is also always permitted, that is, counts
6509 as meeting either a requirement for a following space, or as meeting
6510 a requirement for no following space.
6512 @noindent
6513 If any of these style rules is violated, a message is generated giving
6514 details on the violation. The initial characters of such messages are
6515 always ``@code{(style)}''. Note that these messages are treated as warning
6516 messages, so they normally do not prevent the generation of an object
6517 file. The @option{-gnatwe} switch can be used to treat warning messages,
6518 including style messages, as fatal errors.
6520 The switch
6521 @option{-gnaty} on its own (that is not
6522 followed by any letters or digits) is equivalent
6523 to the use of @option{-gnatyy} as described above, that is all
6524 built-in standard style check options are enabled.
6527 The switch
6528 @option{-gnatyN}
6529 clears any previously set style checks.
6531 @node Run-Time Checks
6532 @subsection Run-Time Checks
6533 @cindex Division by zero
6534 @cindex Access before elaboration
6535 @cindex Checks, division by zero
6536 @cindex Checks, access before elaboration
6537 @cindex Checks, stack overflow checking
6539 @noindent
6540 By default, the following checks are suppressed: integer overflow
6541 checks, stack overflow checks, and checks for access before
6542 elaboration on subprogram calls. All other checks, including range
6543 checks and array bounds checks, are turned on by default. The
6544 following @command{gcc} switches refine this default behavior.
6546 @table @option
6547 @c !sort!
6548 @item -gnatp
6549 @cindex @option{-gnatp} (@command{gcc})
6550 @cindex Suppressing checks
6551 @cindex Checks, suppressing
6552 @findex Suppress
6553 This switch causes the unit to be compiled
6554 as though @code{pragma Suppress (All_checks)}
6555 had been present in the source. Validity checks are also eliminated (in
6556 other words @option{-gnatp} also implies @option{-gnatVn}.
6557 Use this switch to improve the performance
6558 of the code at the expense of safety in the presence of invalid data or
6559 program bugs.
6561 Note that when checks are suppressed, the compiler is allowed, but not
6562 required, to omit the checking code. If the run-time cost of the
6563 checking code is zero or near-zero, the compiler will generate it even
6564 if checks are suppressed. In particular, if the compiler can prove
6565 that a certain check will necessarily fail, it will generate code to
6566 do an unconditional ``raise'', even if checks are suppressed. The
6567 compiler warns in this case. Another case in which checks may not be
6568 eliminated is when they are embedded in certain run time routines such
6569 as math library routines.
6571 Of course, run-time checks are omitted whenever the compiler can prove
6572 that they will not fail, whether or not checks are suppressed.
6574 Note that if you suppress a check that would have failed, program
6575 execution is erroneous, which means the behavior is totally
6576 unpredictable. The program might crash, or print wrong answers, or
6577 do anything else. It might even do exactly what you wanted it to do
6578 (and then it might start failing mysteriously next week or next
6579 year). The compiler will generate code based on the assumption that
6580 the condition being checked is true, which can result in erroneous
6581 execution if that assumption is wrong.
6583 The checks subject to suppression include all the checks defined by
6584 the Ada standard, the additional implementation defined checks
6585 @code{Alignment_Check},
6586 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, and
6587 @code{Validity_Check}, as well as any checks introduced using
6588 @code{pragma Check_Name}. Note that @code{Atomic_Synchronization}
6589 is not automatically suppressed by use of this option.
6591 If the code depends on certain checks being active, you can use
6592 pragma @code{Unsuppress} either as a configuration pragma or as
6593 a local pragma to make sure that a specified check is performed
6594 even if @option{gnatp} is specified.
6596 The @option{-gnatp} switch has no effect if a subsequent
6597 @option{-gnat-p} switch appears.
6599 @item -gnat-p
6600 @cindex @option{-gnat-p} (@command{gcc})
6601 @cindex Suppressing checks
6602 @cindex Checks, suppressing
6603 @findex Suppress
6604 This switch cancels the effect of a previous @option{gnatp} switch.
6606 @item -gnato??
6607 @cindex @option{-gnato??} (@command{gcc})
6608 @cindex Overflow checks
6609 @cindex Overflow mode
6610 @cindex Check, overflow
6611 This switch controls the mode used for computing intermediate
6612 arithmetic integer operations, and also enables overflow checking.
6613 For a full description of overflow mode and checking control, see
6614 the ``Overflow Check Handling in GNAT'' appendix in this
6615 User's Guide.
6617 Overflow checks are always enabled by this switch. The argument
6618 controls the mode, using the codes
6620 @itemize
6621 @item 1 = STRICT
6622 In STRICT mode, intermediate operations are always done using the
6623 base type, and overflow checking ensures that the result is within
6624 the base type range.
6626 @item 2 = MINIMIZED
6627 In MINIMIZED mode, overflows in intermediate operations are avoided
6628 where possible by using a larger integer type for the computation
6629 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6630 the result fits in this larger integer type.
6632 @item 3 = ELIMINATED
6633 In ELIMINATED mode, overflows in intermediate operations are avoided
6634 by using multi-precision arithmetic. In this case, overflow checking
6635 has no effect on intermediate operations (since overflow is impossible).
6636 @end itemize
6638 If two digits are present after @option{-gnato} then the first digit
6639 sets the mode for expressions outside assertions, and the second digit
6640 sets the mode for expressions within assertions. Here assertions is used
6641 in the technical sense (which includes for example precondition and
6642 postcondition expressions).
6644 If one digit is present, the corresponding mode is applicable to both
6645 expressions within and outside assertion expressions.
6647 If no digits are present, the default is to enable overflow checks
6648 and set STRICT mode for both kinds of expressions. This is compatible
6649 with the use of @option{-gnato} in previous versions of GNAT.
6651 @findex Machine_Overflows
6652 Note that the @option{-gnato??} switch does not affect the code generated
6653 for any floating-point operations; it applies only to integer semantics.
6654 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6655 attribute set to @code{False} and the normal mode of operation is to
6656 generate IEEE NaN and infinite values on overflow or invalid operations
6657 (such as dividing 0.0 by 0.0).
6659 The reason that we distinguish overflow checking from other kinds of
6660 range constraint checking is that a failure of an overflow check, unlike
6661 for example the failure of a range check, can result in an incorrect
6662 value, but cannot cause random memory destruction (like an out of range
6663 subscript), or a wild jump (from an out of range case value). Overflow
6664 checking is also quite expensive in time and space, since in general it
6665 requires the use of double length arithmetic.
6667 Note again that the default is @option{-gnato00},
6668 so overflow checking is not performed in default mode. This means that out of
6669 the box, with the default settings, @value{EDITION} does not do all the checks
6670 expected from the language description in the Ada Reference Manual.
6671 If you want all constraint checks to be performed, as described in this Manual,
6672 then you must explicitly use the @option{-gnato??}
6673 switch either on the @command{gnatmake} or @command{gcc} command.
6675 @item -gnatE
6676 @cindex @option{-gnatE} (@command{gcc})
6677 @cindex Elaboration checks
6678 @cindex Check, elaboration
6679 Enables dynamic checks for access-before-elaboration
6680 on subprogram calls and generic instantiations.
6681 Note that @option{-gnatE} is not necessary for safety, because in the
6682 default mode, GNAT ensures statically that the checks would not fail.
6683 For full details of the effect and use of this switch,
6684 @xref{Compiling with gcc}.
6686 @item -fstack-check
6687 @cindex @option{-fstack-check} (@command{gcc})
6688 @cindex Stack Overflow Checking
6689 @cindex Checks, stack overflow checking
6690 Activates stack overflow checking. For full details of the effect and use of
6691 this switch see @ref{Stack Overflow Checking}.
6692 @end table
6694 @findex Unsuppress
6695 @noindent
6696 The setting of these switches only controls the default setting of the
6697 checks. You may modify them using either @code{Suppress} (to remove
6698 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6699 the program source.
6701 @node Using gcc for Syntax Checking
6702 @subsection Using @command{gcc} for Syntax Checking
6703 @table @option
6704 @item -gnats
6705 @cindex @option{-gnats} (@command{gcc})
6707 @noindent
6708 The @code{s} stands for ``syntax''.
6710 Run GNAT in syntax checking only mode. For
6711 example, the command
6713 @smallexample
6714 $ gcc -c -gnats x.adb
6715 @end smallexample
6717 @noindent
6718 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6719 series of files in a single command
6720 , and can use wild cards to specify such a group of files.
6721 Note that you must specify the @option{-c} (compile
6722 only) flag in addition to the @option{-gnats} flag.
6724 You may use other switches in conjunction with @option{-gnats}. In
6725 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6726 format of any generated error messages.
6728 When the source file is empty or contains only empty lines and/or comments,
6729 the output is a warning:
6731 @smallexample
6732 $ gcc -c -gnats -x ada toto.txt
6733 toto.txt:1:01: warning: empty file, contains no compilation units
6735 @end smallexample
6737 Otherwise, the output is simply the error messages, if any. No object file or
6738 ALI file is generated by a syntax-only compilation. Also, no units other
6739 than the one specified are accessed. For example, if a unit @code{X}
6740 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6741 check only mode does not access the source file containing unit
6742 @code{Y}.
6744 @cindex Multiple units, syntax checking
6745 Normally, GNAT allows only a single unit in a source file. However, this
6746 restriction does not apply in syntax-check-only mode, and it is possible
6747 to check a file containing multiple compilation units concatenated
6748 together. This is primarily used by the @code{gnatchop} utility
6749 (@pxref{Renaming Files with gnatchop}).
6750 @end table
6752 @node Using gcc for Semantic Checking
6753 @subsection Using @command{gcc} for Semantic Checking
6754 @table @option
6755 @item -gnatc
6756 @cindex @option{-gnatc} (@command{gcc})
6758 @noindent
6759 The @code{c} stands for ``check''.
6760 Causes the compiler to operate in semantic check mode,
6761 with full checking for all illegalities specified in the
6762 Ada Reference Manual, but without generation of any object code
6763 (no object file is generated).
6765 Because dependent files must be accessed, you must follow the GNAT
6766 semantic restrictions on file structuring to operate in this mode:
6768 @itemize @bullet
6769 @item
6770 The needed source files must be accessible
6771 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6773 @item
6774 Each file must contain only one compilation unit.
6776 @item
6777 The file name and unit name must match (@pxref{File Naming Rules}).
6778 @end itemize
6780 The output consists of error messages as appropriate. No object file is
6781 generated. An @file{ALI} file is generated for use in the context of
6782 cross-reference tools, but this file is marked as not being suitable
6783 for binding (since no object file is generated).
6784 The checking corresponds exactly to the notion of
6785 legality in the Ada Reference Manual.
6787 Any unit can be compiled in semantics-checking-only mode, including
6788 units that would not normally be compiled (subunits,
6789 and specifications where a separate body is present).
6790 @end table
6792 @node Compiling Different Versions of Ada
6793 @subsection Compiling Different Versions of Ada
6795 @noindent
6796 The switches described in this section allow you to explicitly specify
6797 the version of the Ada language that your programs are written in.
6798 The default mode is Ada 2012,
6799 but you can also specify Ada 95, Ada 2005 mode, or
6800 indicate Ada 83 compatibility mode.
6802 @table @option
6803 @cindex Compatibility with Ada 83
6805 @item -gnat83 (Ada 83 Compatibility Mode)
6806 @cindex @option{-gnat83} (@command{gcc})
6807 @cindex ACVC, Ada 83 tests
6808 @cindex Ada 83 mode
6810 @noindent
6811 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6812 specifies that the program is to be compiled in Ada 83 mode. With
6813 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6814 semantics where this can be done easily.
6815 It is not possible to guarantee this switch does a perfect
6816 job; some subtle tests, such as are
6817 found in earlier ACVC tests (and that have been removed from the ACATS suite
6818 for Ada 95), might not compile correctly.
6819 Nevertheless, this switch may be useful in some circumstances, for example
6820 where, due to contractual reasons, existing code needs to be maintained
6821 using only Ada 83 features.
6823 With few exceptions (most notably the need to use @code{<>} on
6824 @cindex Generic formal parameters
6825 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6826 reserved words, and the use of packages
6827 with optional bodies), it is not necessary to specify the
6828 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6829 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6830 a correct Ada 83 program is usually also a correct program
6831 in these later versions of the language standard.
6832 For further information, please refer to @ref{Compatibility and Porting Guide}.
6834 @item -gnat95 (Ada 95 mode)
6835 @cindex @option{-gnat95} (@command{gcc})
6836 @cindex Ada 95 mode
6838 @noindent
6839 This switch directs the compiler to implement the Ada 95 version of the
6840 language.
6841 Since Ada 95 is almost completely upwards
6842 compatible with Ada 83, Ada 83 programs may generally be compiled using
6843 this switch (see the description of the @option{-gnat83} switch for further
6844 information about Ada 83 mode).
6845 If an Ada 2005 program is compiled in Ada 95 mode,
6846 uses of the new Ada 2005 features will cause error
6847 messages or warnings.
6849 This switch also can be used to cancel the effect of a previous
6850 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6851 switch earlier in the command line.
6853 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6854 @cindex @option{-gnat05} (@command{gcc})
6855 @cindex @option{-gnat2005} (@command{gcc})
6856 @cindex Ada 2005 mode
6858 @noindent
6859 This switch directs the compiler to implement the Ada 2005 version of the
6860 language, as documented in the official Ada standards document.
6861 Since Ada 2005 is almost completely upwards
6862 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6863 may generally be compiled using this switch (see the description of the
6864 @option{-gnat83} and @option{-gnat95} switches for further
6865 information).
6867 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6868 @cindex @option{-gnat12} (@command{gcc})
6869 @cindex @option{-gnat2012} (@command{gcc})
6870 @cindex Ada 2012 mode
6872 @noindent
6873 This switch directs the compiler to implement the Ada 2012 version of the
6874 language (also the default).
6875 Since Ada 2012 is almost completely upwards
6876 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6877 Ada 83 and Ada 95 programs
6878 may generally be compiled using this switch (see the description of the
6879 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6880 for further information).
6882 @item -gnatX (Enable GNAT Extensions)
6883 @cindex @option{-gnatX} (@command{gcc})
6884 @cindex Ada language extensions
6885 @cindex GNAT extensions
6887 @noindent
6888 This switch directs the compiler to implement the latest version of the
6889 language (currently Ada 2012) and also to enable certain GNAT implementation
6890 extensions that are not part of any Ada standard. For a full list of these
6891 extensions, see the GNAT reference manual.
6893 @end table
6895 @node Character Set Control
6896 @subsection Character Set Control
6897 @table @option
6898 @item -gnati@var{c}
6899 @cindex @option{-gnati} (@command{gcc})
6901 @noindent
6902 Normally GNAT recognizes the Latin-1 character set in source program
6903 identifiers, as described in the Ada Reference Manual.
6904 This switch causes
6905 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6906 single character  indicating the character set, as follows:
6908 @table @code
6909 @item 1
6910 ISO 8859-1 (Latin-1) identifiers
6912 @item 2
6913 ISO 8859-2 (Latin-2) letters allowed in identifiers
6915 @item 3
6916 ISO 8859-3 (Latin-3) letters allowed in identifiers
6918 @item 4
6919 ISO 8859-4 (Latin-4) letters allowed in identifiers
6921 @item 5
6922 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6924 @item 9
6925 ISO 8859-15 (Latin-9) letters allowed in identifiers
6927 @item p
6928 IBM PC letters (code page 437) allowed in identifiers
6930 @item 8
6931 IBM PC letters (code page 850) allowed in identifiers
6933 @item f
6934 Full upper-half codes allowed in identifiers
6936 @item n
6937 No upper-half codes allowed in identifiers
6939 @item w
6940 Wide-character codes (that is, codes greater than 255)
6941 allowed in identifiers
6942 @end table
6944 @xref{Foreign Language Representation}, for full details on the
6945 implementation of these character sets.
6947 @item -gnatW@var{e}
6948 @cindex @option{-gnatW} (@command{gcc})
6949 Specify the method of encoding for wide characters.
6950 @var{e} is one of the following:
6952 @table @code
6954 @item h
6955 Hex encoding (brackets coding also recognized)
6957 @item u
6958 Upper half encoding (brackets encoding also recognized)
6960 @item s
6961 Shift/JIS encoding (brackets encoding also recognized)
6963 @item e
6964 EUC encoding (brackets encoding also recognized)
6966 @item 8
6967 UTF-8 encoding (brackets encoding also recognized)
6969 @item b
6970 Brackets encoding only (default value)
6971 @end table
6972 For full details on these encoding
6973 methods see @ref{Wide_Character Encodings}.
6974 Note that brackets coding is always accepted, even if one of the other
6975 options is specified, so for example @option{-gnatW8} specifies that both
6976 brackets and UTF-8 encodings will be recognized. The units that are
6977 with'ed directly or indirectly will be scanned using the specified
6978 representation scheme, and so if one of the non-brackets scheme is
6979 used, it must be used consistently throughout the program. However,
6980 since brackets encoding is always recognized, it may be conveniently
6981 used in standard libraries, allowing these libraries to be used with
6982 any of the available coding schemes.
6984 Note that brackets encoding only applies to program text. Within comments,
6985 brackets are considered to be normal graphic characters, and bracket sequences
6986 are never recognized as wide characters.
6988 If no @option{-gnatW?} parameter is present, then the default
6989 representation is normally Brackets encoding only. However, if the
6990 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6991 byte order mark or BOM for UTF-8), then these three characters are
6992 skipped and the default representation for the file is set to UTF-8.
6994 Note that the wide character representation that is specified (explicitly
6995 or by default) for the main program also acts as the default encoding used
6996 for Wide_Text_IO files if not specifically overridden by a WCEM form
6997 parameter.
6999 @end table
7001 When no @option{-gnatW?} is specified, then characters (other than wide
7002 characters represented using brackets notation) are treated as 8-bit
7003 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7004 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7005 characters in the range 16#00#..16#1F# are not accepted in program text
7006 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7007 in program text, but allowed and ignored in comments. Note in particular
7008 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7009 as an end of line in this default mode. If your source program contains
7010 instances of the NEL character used as a line terminator,
7011 you must use UTF-8 encoding for the whole
7012 source program. In default mode, all lines must be ended by a standard
7013 end of line sequence (CR, CR/LF, or LF).
7015 Note that the convention of simply accepting all upper half characters in
7016 comments means that programs that use standard ASCII for program text, but
7017 UTF-8 encoding for comments are accepted in default mode, providing that the
7018 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7019 This is a common mode for many programs with foreign language comments.
7021 @node File Naming Control
7022 @subsection File Naming Control
7024 @table @option
7025 @item -gnatk@var{n}
7026 @cindex @option{-gnatk} (@command{gcc})
7027 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7028 1-999, indicates the maximum allowable length of a file name (not
7029 including the @file{.ads} or @file{.adb} extension). The default is not
7030 to enable file name krunching.
7032 For the source file naming rules, @xref{File Naming Rules}.
7033 @end table
7035 @node Subprogram Inlining Control
7036 @subsection Subprogram Inlining Control
7038 @table @option
7039 @c !sort!
7040 @item -gnatn[12]
7041 @cindex @option{-gnatn} (@command{gcc})
7042 The @code{n} here is intended to suggest the first syllable of the
7043 word ``inline''.
7044 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7045 inlining to actually occur, optimization must be enabled and, in order
7046 to enable inlining of subprograms specified by pragma @code{Inline},
7047 you must also specify this switch.
7048 In the absence of this switch, GNAT does not attempt
7049 inlining and does not need to access the bodies of
7050 subprograms for which @code{pragma Inline} is specified if they are not
7051 in the current unit.
7053 You can optionally specify the inlining level: 1 for moderate inlining across
7054 modules, which is a good compromise between compilation times and performances
7055 at run time, or 2 for full inlining across modules, which may bring about
7056 longer compilation times. If no inlining level is specified, the compiler will
7057 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7058 @option{-Os} and 2 for @option{-O3}.
7060 If you specify this switch the compiler will access these bodies,
7061 creating an extra source dependency for the resulting object file, and
7062 where possible, the call will be inlined.
7063 For further details on when inlining is possible
7064 see @ref{Inlining of Subprograms}.
7066 @item -gnatN
7067 @cindex @option{-gnatN} (@command{gcc})
7068 This switch activates front-end inlining which also
7069 generates additional dependencies.
7071 When using a gcc-based back end (in practice this means using any version
7072 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7073 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7074 Historically front end inlining was more extensive than the gcc back end
7075 inlining, but that is no longer the case.
7076 @end table
7078 @node Auxiliary Output Control
7079 @subsection Auxiliary Output Control
7081 @table @option
7082 @item -gnatt
7083 @cindex @option{-gnatt} (@command{gcc})
7084 @cindex Writing internal trees
7085 @cindex Internal trees, writing to file
7086 Causes GNAT to write the internal tree for a unit to a file (with the
7087 extension @file{.adt}.
7088 This not normally required, but is used by separate analysis tools.
7089 Typically
7090 these tools do the necessary compilations automatically, so you should
7091 not have to specify this switch in normal operation.
7092 Note that the combination of switches @option{-gnatct}
7093 generates a tree in the form required by ASIS applications.
7095 @item -gnatu
7096 @cindex @option{-gnatu} (@command{gcc})
7097 Print a list of units required by this compilation on @file{stdout}.
7098 The listing includes all units on which the unit being compiled depends
7099 either directly or indirectly.
7101 @item -pass-exit-codes
7102 @cindex @option{-pass-exit-codes} (@command{gcc})
7103 If this switch is not used, the exit code returned by @command{gcc} when
7104 compiling multiple files indicates whether all source files have
7105 been successfully used to generate object files or not.
7107 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7108 exit status and allows an integrated development environment to better
7109 react to a compilation failure. Those exit status are:
7111 @table @asis
7112 @item 5
7113 There was an error in at least one source file.
7114 @item 3
7115 At least one source file did not generate an object file.
7116 @item 2
7117 The compiler died unexpectedly (internal error for example).
7118 @item 0
7119 An object file has been generated for every source file.
7120 @end table
7121 @end table
7123 @node Debugging Control
7124 @subsection Debugging Control
7126 @table @option
7127 @c !sort!
7128 @cindex Debugging options
7129 @item -gnatd@var{x}
7130 @cindex @option{-gnatd} (@command{gcc})
7131 Activate internal debugging switches. @var{x} is a letter or digit, or
7132 string of letters or digits, which specifies the type of debugging
7133 outputs desired. Normally these are used only for internal development
7134 or system debugging purposes. You can find full documentation for these
7135 switches in the body of the @code{Debug} unit in the compiler source
7136 file @file{debug.adb}.
7138 @item -gnatG[=nn]
7139 @cindex @option{-gnatG} (@command{gcc})
7140 This switch causes the compiler to generate auxiliary output containing
7141 a pseudo-source listing of the generated expanded code. Like most Ada
7142 compilers, GNAT works by first transforming the high level Ada code into
7143 lower level constructs. For example, tasking operations are transformed
7144 into calls to the tasking run-time routines. A unique capability of GNAT
7145 is to list this expanded code in a form very close to normal Ada source.
7146 This is very useful in understanding the implications of various Ada
7147 usage on the efficiency of the generated code. There are many cases in
7148 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7149 generate a lot of run-time code. By using @option{-gnatG} you can identify
7150 these cases, and consider whether it may be desirable to modify the coding
7151 approach to improve efficiency.
7153 The optional parameter @code{nn} if present after -gnatG specifies an
7154 alternative maximum line length that overrides the normal default of 72.
7155 This value is in the range 40-999999, values less than 40 being silently
7156 reset to 40. The equal sign is optional.
7158 The format of the output is very similar to standard Ada source, and is
7159 easily understood by an Ada programmer. The following special syntactic
7160 additions correspond to low level features used in the generated code that
7161 do not have any exact analogies in pure Ada source form. The following
7162 is a partial list of these special constructions. See the spec
7163 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7165 If the switch @option{-gnatL} is used in conjunction with
7166 @cindex @option{-gnatL} (@command{gcc})
7167 @option{-gnatG}, then the original source lines are interspersed
7168 in the expanded source (as comment lines with the original line number).
7170 @table @code
7171 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7172 Shows the storage pool being used for an allocator.
7174 @item at end @var{procedure-name};
7175 Shows the finalization (cleanup) procedure for a scope.
7177 @item (if @var{expr} then @var{expr} else @var{expr})
7178 Conditional expression equivalent to the @code{x?y:z} construction in C.
7180 @item @var{target}^(@var{source})
7181 A conversion with floating-point truncation instead of rounding.
7183 @item @var{target}?(@var{source})
7184 A conversion that bypasses normal Ada semantic checking. In particular
7185 enumeration types and fixed-point types are treated simply as integers.
7187 @item @var{target}?^(@var{source})
7188 Combines the above two cases.
7190 @item @var{x} #/ @var{y}
7191 @itemx @var{x} #mod @var{y}
7192 @itemx @var{x} #* @var{y}
7193 @itemx @var{x} #rem @var{y}
7194 A division or multiplication of fixed-point values which are treated as
7195 integers without any kind of scaling.
7197 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7198 Shows the storage pool associated with a @code{free} statement.
7200 @item [subtype or type declaration]
7201 Used to list an equivalent declaration for an internally generated
7202 type that is referenced elsewhere in the listing.
7204 @c @item freeze @var{type-name} @ovar{actions}
7205 @c Expanding @ovar macro inline (explanation in macro def comments)
7206 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7207 Shows the point at which @var{type-name} is frozen, with possible
7208 associated actions to be performed at the freeze point.
7210 @item reference @var{itype}
7211 Reference (and hence definition) to internal type @var{itype}.
7213 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7214 Intrinsic function call.
7216 @item @var{label-name} : label
7217 Declaration of label @var{labelname}.
7219 @item #$ @var{subprogram-name}
7220 An implicit call to a run-time support routine
7221 (to meet the requirement of H.3.1(9) in a
7222 convenient manner).
7224 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7225 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7226 @var{expr}, but handled more efficiently).
7228 @item [constraint_error]
7229 Raise the @code{Constraint_Error} exception.
7231 @item @var{expression}'reference
7232 A pointer to the result of evaluating @var{expression}.
7234 @item @var{target-type}!(@var{source-expression})
7235 An unchecked conversion of @var{source-expression} to @var{target-type}.
7237 @item [@var{numerator}/@var{denominator}]
7238 Used to represent internal real literals (that) have no exact
7239 representation in base 2-16 (for example, the result of compile time
7240 evaluation of the expression 1.0/27.0).
7241 @end table
7243 @item -gnatD[=nn]
7244 @cindex @option{-gnatD} (@command{gcc})
7245 When used in conjunction with @option{-gnatG}, this switch causes
7246 the expanded source, as described above for
7247 @option{-gnatG} to be written to files with names
7248 @file{xxx.dg}, where @file{xxx} is the normal file name,
7249 instead of to the standard output file. For
7250 example, if the source file name is @file{hello.adb}, then a file
7251 @file{hello.adb.dg} will be written.  The debugging
7252 information generated by the @command{gcc} @option{-g} switch
7253 will refer to the generated @file{xxx.dg} file. This allows
7254 you to do source level debugging using the generated code which is
7255 sometimes useful for complex code, for example to find out exactly
7256 which part of a complex construction raised an exception. This switch
7257 also suppress generation of cross-reference information (see
7258 @option{-gnatx}) since otherwise the cross-reference information
7259 would refer to the @file{.dg} file, which would cause
7260 confusion since this is not the original source file.
7262 Note that @option{-gnatD} actually implies @option{-gnatG}
7263 automatically, so it is not necessary to give both options.
7264 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7266 If the switch @option{-gnatL} is used in conjunction with
7267 @cindex @option{-gnatL} (@command{gcc})
7268 @option{-gnatDG}, then the original source lines are interspersed
7269 in the expanded source (as comment lines with the original line number).
7271 The optional parameter @code{nn} if present after -gnatD specifies an
7272 alternative maximum line length that overrides the normal default of 72.
7273 This value is in the range 40-999999, values less than 40 being silently
7274 reset to 40. The equal sign is optional.
7276 @item -gnatr
7277 @cindex @option{-gnatr} (@command{gcc})
7278 @cindex pragma Restrictions
7279 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7280 so that violation of restrictions causes warnings rather than illegalities.
7281 This is useful during the development process when new restrictions are added
7282 or investigated. The switch also causes pragma Profile to be treated as
7283 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7284 restriction warnings rather than restrictions.
7286 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7287 @cindex @option{-gnatR} (@command{gcc})
7288 This switch controls output from the compiler of a listing showing
7289 representation information for declared types and objects. For
7290 @option{-gnatR0}, no information is output (equivalent to omitting
7291 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7292 so @option{-gnatR} with no parameter has the same effect), size and alignment
7293 information is listed for declared array and record types. For
7294 @option{-gnatR2}, size and alignment information is listed for all
7295 declared types and objects. The @code{Linker_Section} is also listed for any
7296 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7297 latter case occurs for objects of a type for which a @code{Linker_Section}
7298 is set).
7300 Finally @option{-gnatR3} includes symbolic
7301 expressions for values that are computed at run time for
7302 variant records. These symbolic expressions have a mostly obvious
7303 format with #n being used to represent the value of the n'th
7304 discriminant. See source files @file{repinfo.ads/adb} in the
7305 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7306 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7307 the output is to a file with the name @file{file.rep} where
7308 file is the name of the corresponding source file.
7310 @item -gnatRm[s]
7311 This form of the switch controls output of subprogram conventions
7312 and parameter passing mechanisms for all subprograms. A following
7313 @code{s} means output to a file as described above.
7315 Note that it is possible for record components to have zero size. In
7316 this case, the component clause uses an obvious extension of permitted
7317 Ada syntax, for example @code{at 0 range 0 .. -1}.
7319 Representation information requires that code be generated (since it is the
7320 code generator that lays out complex data structures). If an attempt is made
7321 to output representation information when no code is generated, for example
7322 when a subunit is compiled on its own, then no information can be generated
7323 and the compiler outputs a message to this effect.
7325 @item -gnatS
7326 @cindex @option{-gnatS} (@command{gcc})
7327 The use of the switch @option{-gnatS} for an
7328 Ada compilation will cause the compiler to output a
7329 representation of package Standard in a form very
7330 close to standard Ada. It is not quite possible to
7331 do this entirely in standard Ada (since new
7332 numeric base types cannot be created in standard
7333 Ada), but the output is easily
7334 readable to any Ada programmer, and is useful to
7335 determine the characteristics of target dependent
7336 types in package Standard.
7338 @item -gnatx
7339 @cindex @option{-gnatx} (@command{gcc})
7340 Normally the compiler generates full cross-referencing information in
7341 the @file{ALI} file. This information is used by a number of tools,
7342 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7343 suppresses this information. This saves some space and may slightly
7344 speed up compilation, but means that these tools cannot be used.
7345 @end table
7347 @node Exception Handling Control
7348 @subsection Exception Handling Control
7350 @noindent
7351 GNAT uses two methods for handling exceptions at run-time. The
7352 @code{setjmp/longjmp} method saves the context when entering
7353 a frame with an exception handler. Then when an exception is
7354 raised, the context can be restored immediately, without the
7355 need for tracing stack frames. This method provides very fast
7356 exception propagation, but introduces significant overhead for
7357 the use of exception handlers, even if no exception is raised.
7359 The other approach is called ``zero cost'' exception handling.
7360 With this method, the compiler builds static tables to describe
7361 the exception ranges. No dynamic code is required when entering
7362 a frame containing an exception handler. When an exception is
7363 raised, the tables are used to control a back trace of the
7364 subprogram invocation stack to locate the required exception
7365 handler. This method has considerably poorer performance for
7366 the propagation of exceptions, but there is no overhead for
7367 exception handlers if no exception is raised. Note that in this
7368 mode and in the context of mixed Ada and C/C++ programming,
7369 to propagate an exception through a C/C++ code, the C/C++ code
7370 must be compiled with the @option{-funwind-tables} GCC's
7371 option.
7373 The following switches may be used to control which of the
7374 two exception handling methods is used.
7376 @table @option
7377 @c !sort!
7379 @item --RTS=sjlj
7380 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7381 This switch causes the setjmp/longjmp run-time (when available) to be used
7382 for exception handling. If the default
7383 mechanism for the target is zero cost exceptions, then
7384 this switch can be used to modify this default, and must be
7385 used for all units in the partition.
7386 This option is rarely used. One case in which it may be
7387 advantageous is if you have an application where exception
7388 raising is common and the overall performance of the
7389 application is improved by favoring exception propagation.
7391 @item --RTS=zcx
7392 @cindex @option{--RTS=zcx} (@command{gnatmake})
7393 @cindex Zero Cost Exceptions
7394 This switch causes the zero cost approach to be used
7395 for exception handling. If this is the default mechanism for the
7396 target (see below), then this switch is unneeded. If the default
7397 mechanism for the target is setjmp/longjmp exceptions, then
7398 this switch can be used to modify this default, and must be
7399 used for all units in the partition.
7400 This option can only be used if the zero cost approach
7401 is available for the target in use, otherwise it will generate an error.
7402 @end table
7404 @noindent
7405 The same option @option{--RTS} must be used both for @command{gcc}
7406 and @command{gnatbind}. Passing this option to @command{gnatmake}
7407 (@pxref{Switches for gnatmake}) will ensure the required consistency
7408 through the compilation and binding steps.
7410 @node Units to Sources Mapping Files
7411 @subsection Units to Sources Mapping Files
7413 @table @option
7415 @item -gnatem=@var{path}
7416 @cindex @option{-gnatem} (@command{gcc})
7417 A mapping file is a way to communicate to the compiler two mappings:
7418 from unit names to file names (without any directory information) and from
7419 file names to path names (with full directory information). These mappings
7420 are used by the compiler to short-circuit the path search.
7422 The use of mapping files is not required for correct operation of the
7423 compiler, but mapping files can improve efficiency, particularly when
7424 sources are read over a slow network connection. In normal operation,
7425 you need not be concerned with the format or use of mapping files,
7426 and the @option{-gnatem} switch is not a switch that you would use
7427 explicitly. It is intended primarily for use by automatic tools such as
7428 @command{gnatmake} running under the project file facility. The
7429 description here of the format of mapping files is provided
7430 for completeness and for possible use by other tools.
7432 A mapping file is a sequence of sets of three lines. In each set, the
7433 first line is the unit name, in lower case, with @code{%s} appended
7434 for specs and @code{%b} appended for bodies; the second line is the
7435 file name; and the third line is the path name.
7437 Example:
7438 @smallexample
7439    main%b
7440    main.2.ada
7441    /gnat/project1/sources/main.2.ada
7442 @end smallexample
7444 When the switch @option{-gnatem} is specified, the compiler will
7445 create in memory the two mappings from the specified file. If there is
7446 any problem (nonexistent file, truncated file or duplicate entries),
7447 no mapping will be created.
7449 Several @option{-gnatem} switches may be specified; however, only the
7450 last one on the command line will be taken into account.
7452 When using a project file, @command{gnatmake} creates a temporary
7453 mapping file and communicates it to the compiler using this switch.
7455 @end table
7457 @node Integrated Preprocessing
7458 @subsection Integrated Preprocessing
7460 @noindent
7461 GNAT sources may be preprocessed immediately before compilation.
7462 In this case, the actual
7463 text of the source is not the text of the source file, but is derived from it
7464 through a process called preprocessing. Integrated preprocessing is specified
7465 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7466 indicates, through a text file, the preprocessing data to be used.
7467 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7468 Note that integrated preprocessing applies only to Ada source files, it is
7469 not available for configuration pragma files.
7471 @noindent
7472 Note that when integrated preprocessing is used, the output from the
7473 preprocessor is not written to any external file. Instead it is passed
7474 internally to the compiler. If you need to preserve the result of
7475 preprocessing in a file, then you should use @command{gnatprep}
7476 to perform the desired preprocessing in stand-alone mode.
7478 @noindent
7479 It is recommended that @command{gnatmake} switch -s should be
7480 used when Integrated Preprocessing is used. The reason is that preprocessing
7481 with another Preprocessing Data file without changing the sources will
7482 not trigger recompilation without this switch.
7484 @noindent
7485 Note that @command{gnatmake} switch -m will almost
7486 always trigger recompilation for sources that are preprocessed,
7487 because @command{gnatmake} cannot compute the checksum of the source after
7488 preprocessing.
7490 @noindent
7491 The actual preprocessing function is described in details in section
7492 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7493 preprocessing is triggered and parameterized.
7495 @table @code
7497 @item -gnatep=@var{file}
7498 @cindex @option{-gnatep} (@command{gcc})
7499 This switch indicates to the compiler the file name (without directory
7500 information) of the preprocessor data file to use. The preprocessor data file
7501 should be found in the source directories. Note that when the compiler is
7502 called by a builder such as (@command{gnatmake} with a project
7503 file, if the object directory is not also a source directory, the builder needs
7504 to be called with @option{-x}.
7506 @noindent
7507 A preprocessing data file is a text file with significant lines indicating
7508 how should be preprocessed either a specific source or all sources not
7509 mentioned in other lines. A significant line is a nonempty, non-comment line.
7510 Comments are similar to Ada comments.
7512 @noindent
7513 Each significant line starts with either a literal string or the character '*'.
7514 A literal string is the file name (without directory information) of the source
7515 to preprocess. A character '*' indicates the preprocessing for all the sources
7516 that are not specified explicitly on other lines (order of the lines is not
7517 significant). It is an error to have two lines with the same file name or two
7518 lines starting with the character '*'.
7520 @noindent
7521 After the file name or the character '*', another optional literal string
7522 indicating the file name of the definition file to be used for preprocessing
7523 (@pxref{Form of Definitions File}). The definition files are found by the
7524 compiler in one of the source directories. In some cases, when compiling
7525 a source in a directory other than the current directory, if the definition
7526 file is in the current directory, it may be necessary to add the current
7527 directory as a source directory through switch -I., otherwise
7528 the compiler would not find the definition file.
7530 @noindent
7531 Then, optionally, switches similar to those of @code{gnatprep} may
7532 be found. Those switches are:
7534 @table @code
7536 @item -b
7537 Causes both preprocessor lines and the lines deleted by
7538 preprocessing to be replaced by blank lines, preserving the line number.
7539 This switch is always implied; however, if specified after @option{-c}
7540 it cancels the effect of @option{-c}.
7542 @item -c
7543 Causes both preprocessor lines and the lines deleted
7544 by preprocessing to be retained as comments marked
7545 with the special string ``@code{--! }''.
7547 @item -Dsymbol=value
7548 Define or redefine a symbol, associated with value. A symbol is an Ada
7549 identifier, or an Ada reserved word, with the exception of @code{if},
7550 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7551 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7552 word. A symbol declared with this switch replaces a symbol with the
7553 same name defined in a definition file.
7555 @item -s
7556 Causes a sorted list of symbol names and values to be
7557 listed on the standard output file.
7559 @item -u
7560 Causes undefined symbols to be treated as having the value @code{FALSE}
7561 in the context
7562 of a preprocessor test. In the absence of this option, an undefined symbol in
7563 a @code{#if} or @code{#elsif} test will be treated as an error.
7565 @end table
7567 @noindent
7568 Examples of valid lines in a preprocessor data file:
7570 @smallexample
7571   "toto.adb"  "prep.def" -u
7572   --  preprocess "toto.adb", using definition file "prep.def",
7573   --  undefined symbol are False.
7575   * -c -DVERSION=V101
7576   --  preprocess all other sources without a definition file;
7577   --  suppressed lined are commented; symbol VERSION has the value V101.
7579   "titi.adb" "prep2.def" -s
7580   --  preprocess "titi.adb", using definition file "prep2.def";
7581   --  list all symbols with their values.
7582 @end smallexample
7584 @item -gnateDsymbol@r{[}=value@r{]}
7585 @cindex @option{-gnateD} (@command{gcc})
7586 Define or redefine a preprocessing symbol, associated with value. If no value
7587 is given on the command line, then the value of the symbol is @code{True}.
7588 A symbol is an identifier, following normal Ada (case-insensitive)
7589 rules for its syntax, and value is either an arbitrary string between double
7590 quotes or any sequence (including an empty sequence) of characters from the
7591 set (letters, digits, period, underline).
7592 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7593 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7595 @noindent
7596 Examples:
7598 @smallexample
7599    -gnateDToto=Titi
7600    -gnateDFoo
7601    -gnateDFoo=\"Foo-Bar\"
7602 @end smallexample
7604 @noindent
7605 A symbol declared with this switch on the command line replaces a
7606 symbol with the same name either in a definition file or specified with a
7607 switch -D in the preprocessor data file.
7609 @noindent
7610 This switch is similar to switch @option{-D} of @code{gnatprep}.
7612 @item -gnateG
7613 When integrated preprocessing is performed and the preprocessor modifies
7614 the source text, write the result of this preprocessing into a file
7615 <source>.prep.
7617 @end table
7619 @node Code Generation Control
7620 @subsection Code Generation Control
7622 @noindent
7624 The GCC technology provides a wide range of target dependent
7625 @option{-m} switches for controlling
7626 details of code generation with respect to different versions of
7627 architectures. This includes variations in instruction sets (e.g.@:
7628 different members of the power pc family), and different requirements
7629 for optimal arrangement of instructions (e.g.@: different members of
7630 the x86 family). The list of available @option{-m} switches may be
7631 found in the GCC documentation.
7633 Use of these @option{-m} switches may in some cases result in improved
7634 code performance.
7636 The @value{EDITION} technology is tested and qualified without any
7637 @option{-m} switches,
7638 so generally the most reliable approach is to avoid the use of these
7639 switches. However, we generally expect most of these switches to work
7640 successfully with @value{EDITION}, and many customers have reported successful
7641 use of these options.
7643 Our general advice is to avoid the use of @option{-m} switches unless
7644 special needs lead to requirements in this area. In particular,
7645 there is no point in using @option{-m} switches to improve performance
7646 unless you actually see a performance improvement.
7649 @node Search Paths and the Run-Time Library (RTL)
7650 @section Search Paths and the Run-Time Library (RTL)
7652 @noindent
7653 With the GNAT source-based library system, the compiler must be able to
7654 find source files for units that are needed by the unit being compiled.
7655 Search paths are used to guide this process.
7657 The compiler compiles one source file whose name must be given
7658 explicitly on the command line. In other words, no searching is done
7659 for this file. To find all other source files that are needed (the most
7660 common being the specs of units), the compiler examines the following
7661 directories, in the following order:
7663 @enumerate
7664 @item
7665 The directory containing the source file of the main unit being compiled
7666 (the file name on the command line).
7668 @item
7669 Each directory named by an @option{-I} switch given on the
7670 @command{gcc} command line, in the order given.
7672 @item
7673 @findex ADA_PRJ_INCLUDE_FILE
7674 Each of the directories listed in the text file whose name is given
7675 by the @env{ADA_PRJ_INCLUDE_FILE} environment variable.
7677 @noindent
7678 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
7679 driver when project files are used. It should not normally be set
7680 by other means.
7682 @item
7683 @findex ADA_INCLUDE_PATH
7684 Each of the directories listed in the value of the
7685 @env{ADA_INCLUDE_PATH} environment variable.
7686 Construct this value
7687 exactly as the @env{PATH} environment variable: a list of directory
7688 names separated by colons (semicolons when working with the NT version).
7690 @item
7691 The content of the @file{ada_source_path} file which is part of the GNAT
7692 installation tree and is used to store standard libraries such as the
7693 GNAT Run Time Library (RTL) source files.
7694 @ref{Installing a library}
7695 @end enumerate
7697 @noindent
7698 Specifying the switch @option{-I-}
7699 inhibits the use of the directory
7700 containing the source file named in the command line. You can still
7701 have this directory on your search path, but in this case it must be
7702 explicitly requested with a @option{-I} switch.
7704 Specifying the switch @option{-nostdinc}
7705 inhibits the search of the default location for the GNAT Run Time
7706 Library (RTL) source files.
7708 The compiler outputs its object files and ALI files in the current
7709 working directory.
7710 Caution: The object file can be redirected with the @option{-o} switch;
7711 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7712 so the @file{ALI} file will not go to the right place. Therefore, you should
7713 avoid using the @option{-o} switch.
7715 @findex System.IO
7716 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7717 children make up the GNAT RTL, together with the simple @code{System.IO}
7718 package used in the @code{"Hello World"} example. The sources for these units
7719 are needed by the compiler and are kept together in one directory. Not
7720 all of the bodies are needed, but all of the sources are kept together
7721 anyway. In a normal installation, you need not specify these directory
7722 names when compiling or binding. Either the environment variables or
7723 the built-in defaults cause these files to be found.
7725 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7726 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7727 consisting of child units of @code{GNAT}. This is a collection of generally
7728 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7729 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7731 Besides simplifying access to the RTL, a major use of search paths is
7732 in compiling sources from multiple directories. This can make
7733 development environments much more flexible.
7735 @node Order of Compilation Issues
7736 @section Order of Compilation Issues
7738 @noindent
7739 If, in our earlier example, there was a spec for the @code{hello}
7740 procedure, it would be contained in the file @file{hello.ads}; yet this
7741 file would not have to be explicitly compiled. This is the result of the
7742 model we chose to implement library management. Some of the consequences
7743 of this model are as follows:
7745 @itemize @bullet
7746 @item
7747 There is no point in compiling specs (except for package
7748 specs with no bodies) because these are compiled as needed by clients. If
7749 you attempt a useless compilation, you will receive an error message.
7750 It is also useless to compile subunits because they are compiled as needed
7751 by the parent.
7753 @item
7754 There are no order of compilation requirements: performing a
7755 compilation never obsoletes anything. The only way you can obsolete
7756 something and require recompilations is to modify one of the
7757 source files on which it depends.
7759 @item
7760 There is no library as such, apart from the ALI files
7761 (@pxref{The Ada Library Information Files}, for information on the format
7762 of these files). For now we find it convenient to create separate ALI files,
7763 but eventually the information therein may be incorporated into the object
7764 file directly.
7766 @item
7767 When you compile a unit, the source files for the specs of all units
7768 that it @code{with}'s, all its subunits, and the bodies of any generics it
7769 instantiates must be available (reachable by the search-paths mechanism
7770 described above), or you will receive a fatal error message.
7771 @end itemize
7773 @node Examples
7774 @section Examples
7776 @noindent
7777 The following are some typical Ada compilation command line examples:
7779 @table @code
7780 @item $ gcc -c xyz.adb
7781 Compile body in file @file{xyz.adb} with all default options.
7783 @item $ gcc -c -O2 -gnata xyz-def.adb
7785 Compile the child unit package in file @file{xyz-def.adb} with extensive
7786 optimizations, and pragma @code{Assert}/@code{Debug} statements
7787 enabled.
7789 @item $ gcc -c -gnatc abc-def.adb
7790 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7791 mode.
7792 @end table
7794 @node Binding with gnatbind
7795 @chapter Binding with @code{gnatbind}
7796 @findex gnatbind
7798 @menu
7799 * Running gnatbind::
7800 * Switches for gnatbind::
7801 * Command-Line Access::
7802 * Search Paths for gnatbind::
7803 * Examples of gnatbind Usage::
7804 @end menu
7806 @noindent
7807 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7808 to bind compiled GNAT objects.
7810 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7811 driver (see @ref{The GNAT Driver and Project Files}).
7813 The @code{gnatbind} program performs four separate functions:
7815 @enumerate
7816 @item
7817 Checks that a program is consistent, in accordance with the rules in
7818 Chapter 10 of the Ada Reference Manual. In particular, error
7819 messages are generated if a program uses inconsistent versions of a
7820 given unit.
7822 @item
7823 Checks that an acceptable order of elaboration exists for the program
7824 and issues an error message if it cannot find an order of elaboration
7825 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7827 @item
7828 Generates a main program incorporating the given elaboration order.
7829 This program is a small Ada package (body and spec) that
7830 must be subsequently compiled
7831 using the GNAT compiler. The necessary compilation step is usually
7832 performed automatically by @command{gnatlink}. The two most important
7833 functions of this program
7834 are to call the elaboration routines of units in an appropriate order
7835 and to call the main program.
7837 @item
7838 Determines the set of object files required by the given main program.
7839 This information is output in the forms of comments in the generated program,
7840 to be read by the @command{gnatlink} utility used to link the Ada application.
7841 @end enumerate
7843 @node Running gnatbind
7844 @section Running @code{gnatbind}
7846 @noindent
7847 The form of the @code{gnatbind} command is
7849 @smallexample
7850 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7851 @c Expanding @ovar macro inline (explanation in macro def comments)
7852 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7853 @end smallexample
7855 @noindent
7856 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7857 unit body. @code{gnatbind} constructs an Ada
7858 package in two files whose names are
7859 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7860 For example, if given the
7861 parameter @file{hello.ali}, for a main program contained in file
7862 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7863 and @file{b~hello.adb}.
7865 When doing consistency checking, the binder takes into consideration
7866 any source files it can locate. For example, if the binder determines
7867 that the given main program requires the package @code{Pack}, whose
7868 @file{.ALI}
7869 file is @file{pack.ali} and whose corresponding source spec file is
7870 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7871 (using the same search path conventions as previously described for the
7872 @command{gcc} command). If it can locate this source file, it checks that
7873 the time stamps
7874 or source checksums of the source and its references to in @file{ALI} files
7875 match. In other words, any @file{ALI} files that mentions this spec must have
7876 resulted from compiling this version of the source file (or in the case
7877 where the source checksums match, a version close enough that the
7878 difference does not matter).
7880 @cindex Source files, use by binder
7881 The effect of this consistency checking, which includes source files, is
7882 that the binder ensures that the program is consistent with the latest
7883 version of the source files that can be located at bind time. Editing a
7884 source file without compiling files that depend on the source file cause
7885 error messages to be generated by the binder.
7887 For example, suppose you have a main program @file{hello.adb} and a
7888 package @code{P}, from file @file{p.ads} and you perform the following
7889 steps:
7891 @enumerate
7892 @item
7893 Enter @code{gcc -c hello.adb} to compile the main program.
7895 @item
7896 Enter @code{gcc -c p.ads} to compile package @code{P}.
7898 @item
7899 Edit file @file{p.ads}.
7901 @item
7902 Enter @code{gnatbind hello}.
7903 @end enumerate
7905 @noindent
7906 At this point, the file @file{p.ali} contains an out-of-date time stamp
7907 because the file @file{p.ads} has been edited. The attempt at binding
7908 fails, and the binder generates the following error messages:
7910 @smallexample
7911 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7912 error: "p.ads" has been modified and must be recompiled
7913 @end smallexample
7915 @noindent
7916 Now both files must be recompiled as indicated, and then the bind can
7917 succeed, generating a main program. You need not normally be concerned
7918 with the contents of this file, but for reference purposes a sample
7919 binder output file is given in @ref{Example of Binder Output File}.
7921 In most normal usage, the default mode of @command{gnatbind} which is to
7922 generate the main package in Ada, as described in the previous section.
7923 In particular, this means that any Ada programmer can read and understand
7924 the generated main program. It can also be debugged just like any other
7925 Ada code provided the @option{-g} switch is used for
7926 @command{gnatbind} and @command{gnatlink}.
7928 @node Switches for gnatbind
7929 @section Switches for @command{gnatbind}
7931 @noindent
7932 The following switches are available with @code{gnatbind}; details will
7933 be presented in subsequent sections.
7935 @menu
7936 * Consistency-Checking Modes::
7937 * Binder Error Message Control::
7938 * Elaboration Control::
7939 * Output Control::
7940 * Dynamic Allocation Control::
7941 * Binding with Non-Ada Main Programs::
7942 * Binding Programs with No Main Subprogram::
7943 @end menu
7945 @table @option
7946 @c !sort!
7948 @item --version
7949 @cindex @option{--version} @command{gnatbind}
7950 Display Copyright and version, then exit disregarding all other options.
7952 @item --help
7953 @cindex @option{--help} @command{gnatbind}
7954 If @option{--version} was not used, display usage, then exit disregarding
7955 all other options.
7957 @item -a
7958 @cindex @option{-a} @command{gnatbind}
7959 Indicates that, if supported by the platform, the adainit procedure should
7960 be treated as an initialisation routine by the linker (a constructor). This
7961 is intended to be used by the Project Manager to automatically initialize
7962 shared Stand-Alone Libraries.
7964 @item -aO
7965 @cindex @option{-aO} (@command{gnatbind})
7966 Specify directory to be searched for ALI files.
7968 @item -aI
7969 @cindex @option{-aI} (@command{gnatbind})
7970 Specify directory to be searched for source file.
7972 @item -A@r{[=}@var{filename}@r{]}
7973 @cindex @option{-A} (@command{gnatbind})
7974 Output ALI list (to standard output or to the named file).
7976 @item -b
7977 @cindex @option{-b} (@command{gnatbind})
7978 Generate brief messages to @file{stderr} even if verbose mode set.
7980 @item -c
7981 @cindex @option{-c} (@command{gnatbind})
7982 Check only, no generation of binder output file.
7984 @item -d@var{nn}@r{[}k@r{|}m@r{]}
7985 @cindex @option{-d@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7986 This switch can be used to change the default task stack size value
7987 to a specified size @var{nn}, which is expressed in bytes by default, or
7988 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7989 with @var{m}.
7990 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7991 in effect, to completing all task specs with
7992 @smallexample @c ada
7993    @b{pragma} Storage_Size (nn);
7994 @end smallexample
7995 When they do not already have such a pragma.
7997 @item -D@var{nn}@r{[}k@r{|}m@r{]}
7998 @cindex @option{-D} (@command{gnatbind})
7999 This switch can be used to change the default secondary stack size value
8000 to a specified size @var{nn}, which is expressed in bytes by default, or
8001 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8002 with @var{m}.
8004 The secondary stack is used to deal with functions that return a variable
8005 sized result, for example a function returning an unconstrained
8006 String. There are two ways in which this secondary stack is allocated.
8008 For most targets, the secondary stack is growing on demand and is allocated
8009 as a chain of blocks in the heap. The -D option is not very
8010 relevant. It only give some control over the size of the allocated
8011 blocks (whose size is the minimum of the default secondary stack size value,
8012 and the actual size needed for the current allocation request).
8014 For certain targets, notably VxWorks 653,
8015 the secondary stack is allocated by carving off a fixed ratio chunk of the
8016 primary task stack. The -D option is used to define the
8017 size of the environment task's secondary stack.
8019 @item -e
8020 @cindex @option{-e} (@command{gnatbind})
8021 Output complete list of elaboration-order dependencies.
8023 @item -E
8024 @cindex @option{-E} (@command{gnatbind})
8025 Store tracebacks in exception occurrences when the target supports it.
8026 @ignore
8027 @c The following may get moved to an appendix
8028 This option is currently supported on the following targets:
8029 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8030 @end ignore
8031 See also the packages @code{GNAT.Traceback} and
8032 @code{GNAT.Traceback.Symbolic} for more information.
8033 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8034 @command{gcc} option.
8036 @item -F
8037 @cindex @option{-F} (@command{gnatbind})
8038 Force the checks of elaboration flags. @command{gnatbind} does not normally
8039 generate checks of elaboration flags for the main executable, except when
8040 a Stand-Alone Library is used. However, there are cases when this cannot be
8041 detected by gnatbind. An example is importing an interface of a Stand-Alone
8042 Library through a pragma Import and only specifying through a linker switch
8043 this Stand-Alone Library. This switch is used to guarantee that elaboration
8044 flag checks are generated.
8046 @item -h
8047 @cindex @option{-h} (@command{gnatbind})
8048 Output usage (help) information
8050 @item -H32
8051 @cindex @option{-H32} (@command{gnatbind})
8052 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8053 For further details see @ref{Dynamic Allocation Control}.
8055 @item -H64
8056 @cindex @option{-H64} (@command{gnatbind})
8057 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8058 @cindex @code{__gnat_malloc}
8059 For further details see @ref{Dynamic Allocation Control}.
8061 @item -I
8062 @cindex @option{-I} (@command{gnatbind})
8063 Specify directory to be searched for source and ALI files.
8065 @item -I-
8066 @cindex @option{-I-} (@command{gnatbind})
8067 Do not look for sources in the current directory where @code{gnatbind} was
8068 invoked, and do not look for ALI files in the directory containing the
8069 ALI file named in the @code{gnatbind} command line.
8071 @item -l
8072 @cindex @option{-l} (@command{gnatbind})
8073 Output chosen elaboration order.
8075 @item -L@var{xxx}
8076 @cindex @option{-L} (@command{gnatbind})
8077 Bind the units for library building. In this case the adainit and
8078 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8079 are renamed to @var{xxx}init and
8080 @var{xxx}final.
8081 Implies -n.
8082 (@xref{GNAT and Libraries}, for more details.)
8084 @item -Mxyz
8085 @cindex @option{-M} (@command{gnatbind})
8086 Rename generated main program from main to xyz. This option is
8087 supported on cross environments only.
8089 @item -m@var{n}
8090 @cindex @option{-m} (@command{gnatbind})
8091 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8092 in the range 1..999999. The default value if no switch is
8093 given is 9999. If the number of warnings reaches this limit, then a
8094 message is output and further warnings are suppressed, the bind
8095 continues in this case. If the number of errors reaches this
8096 limit, then a message is output and the bind is abandoned.
8097 A value of zero means that no limit is enforced. The equal
8098 sign is optional.
8100 @item -n
8101 @cindex @option{-n} (@command{gnatbind})
8102 No main program.
8104 @item -nostdinc
8105 @cindex @option{-nostdinc} (@command{gnatbind})
8106 Do not look for sources in the system default directory.
8108 @item -nostdlib
8109 @cindex @option{-nostdlib} (@command{gnatbind})
8110 Do not look for library files in the system default directory.
8112 @item --RTS=@var{rts-path}
8113 @cindex @option{--RTS} (@code{gnatbind})
8114 Specifies the default location of the runtime library. Same meaning as the
8115 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8117 @item -o @var{file}
8118 @cindex @option{-o } (@command{gnatbind})
8119 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8120 Note that if this option is used, then linking must be done manually,
8121 gnatlink cannot be used.
8123 @item -O@r{[=}@var{filename}@r{]}
8124 @cindex @option{-O} (@command{gnatbind})
8125 Output object list (to standard output or to the named file).
8127 @item -p
8128 @cindex @option{-p} (@command{gnatbind})
8129 Pessimistic (worst-case) elaboration order
8131 @item -P
8132 @cindex @option{-P} (@command{gnatbind})
8133 Generate binder file suitable for CodePeer.
8135 @item -R
8136 @cindex @option{-R} (@command{gnatbind})
8137 Output closure source list, which includes all non-run-time units that are
8138 included in the bind.
8140 @item -Ra
8141 @cindex @option{-Ra} (@command{gnatbind})
8142 Like @option{-R} but the list includes run-time units.
8144 @item -s
8145 @cindex @option{-s} (@command{gnatbind})
8146 Require all source files to be present.
8148 @item -S@var{xxx}
8149 @cindex @option{-S} (@command{gnatbind})
8150 Specifies the value to be used when detecting uninitialized scalar
8151 objects with pragma Initialize_Scalars.
8152 The @var{xxx} string specified with the switch is one of:
8153 @itemize @bullet
8155 @item ``@option{in}'' for an invalid value
8156 If zero is invalid for the discrete type in question,
8157 then the scalar value is set to all zero bits.
8158 For signed discrete types, the largest possible negative value of
8159 the underlying scalar is set (i.e. a one bit followed by all zero bits).
8160 For unsigned discrete types, the underlying scalar value is set to all
8161 one bits. For floating-point types, a NaN value is set
8162 (see body of package System.Scalar_Values for exact values).
8164 @item ``@option{lo}'' for low value
8165 If zero is invalid for the discrete type in question,
8166 then the scalar value is set to all zero bits.
8167 For signed discrete types, the largest possible negative value of
8168 the underlying scalar is set (i.e. a one bit followed by all zero bits).
8169 For unsigned discrete types, the underlying scalar value is set to all
8170 zero bits. For floating-point, a small value is set
8171 (see body of package System.Scalar_Values for exact values).
8173 @item ``@option{hi}'' for high value
8174 If zero is invalid for the discrete type in question,
8175 then the scalar value is set to all one bits.
8176 For signed discrete types, the largest possible positive value of
8177 the underlying scalar is set (i.e. a zero bit followed by all one bits).
8178 For unsigned discrete types, the underlying scalar value is set to all
8179 one bits. For floating-point, a large value is set
8180 (see body of package System.Scalar_Values for exact values).
8182 @item ``@option{@var{xx}}'' for hex value (two hex digits)
8183 The underlying scalar is set to a value consisting of repeated bytes, whose
8184 value corresponds to the given value. For example if @option{BF} is given,
8185 then a 32-bit scalar value will be set to the bit patterm 16#BFBFBFBF#.
8186 @end itemize
8188 In addition, you can specify @option{-Sev} to indicate that the value is
8189 to be set at run time. In this case, the program will look for an environment
8190 @cindex GNAT_INIT_SCALARS
8191 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8192 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8193 If no environment variable is found, or if it does not have a valid value,
8194 then the default is @option{in} (invalid values).
8196 @item -static
8197 @cindex @option{-static} (@code{gnatbind})
8198 Link against a static GNAT run time.
8200 @item -shared
8201 @cindex @option{-shared} (@code{gnatbind})
8202 Link against a shared GNAT run time when available.
8204 @item -t
8205 @cindex @option{-t} (@code{gnatbind})
8206 Tolerate time stamp and other consistency errors
8208 @item -T@var{n}
8209 @cindex @option{-T} (@code{gnatbind})
8210 Set the time slice value to @var{n} milliseconds. If the system supports
8211 the specification of a specific time slice value, then the indicated value
8212 is used. If the system does not support specific time slice values, but
8213 does support some general notion of round-robin scheduling, then any
8214 nonzero value will activate round-robin scheduling.
8216 A value of zero is treated specially. It turns off time
8217 slicing, and in addition, indicates to the tasking run time that the
8218 semantics should match as closely as possible the Annex D
8219 requirements of the Ada RM, and in particular sets the default
8220 scheduling policy to @code{FIFO_Within_Priorities}.
8222 @item -u@var{n}
8223 @cindex @option{-u} (@code{gnatbind})
8224 Enable dynamic stack usage, with @var{n} results stored and displayed
8225 at program termination. A result is generated when a task
8226 terminates. Results that can't be stored are displayed on the fly, at
8227 task termination. This option is currently not supported on Itanium
8228 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8230 @item -v
8231 @cindex @option{-v} (@code{gnatbind})
8232 Verbose mode. Write error messages, header, summary output to
8233 @file{stdout}.
8235 @item -w@var{x}
8236 @cindex @option{-w} (@code{gnatbind})
8237 Warning mode (@var{x}=s/e for suppress/treat as error)
8240 @item -Wx@var{e}
8241 @cindex @option{-Wx} (@code{gnatbind})
8242 Override default wide character encoding for standard Text_IO files.
8244 @item -x
8245 @cindex @option{-x} (@code{gnatbind})
8246 Exclude source files (check object consistency only).
8249 @item -X@var{nnn}
8250 @cindex @option{-X@var{nnn}} (@code{gnatbind})
8251 Set default exit status value, normally 0 for POSIX compliance.
8254 @item -y
8255 @cindex @option{-y} (@code{gnatbind})
8256 Enable leap seconds support in @code{Ada.Calendar} and its children.
8258 @item -z
8259 @cindex @option{-z} (@code{gnatbind})
8260 No main subprogram.
8261 @end table
8263 @noindent
8264 You may obtain this listing of switches by running @code{gnatbind} with
8265 no arguments.
8267 @node Consistency-Checking Modes
8268 @subsection Consistency-Checking Modes
8270 @noindent
8271 As described earlier, by default @code{gnatbind} checks
8272 that object files are consistent with one another and are consistent
8273 with any source files it can locate. The following switches control binder
8274 access to sources.
8276 @table @option
8277 @c !sort!
8278 @item -s
8279 @cindex @option{-s} (@code{gnatbind})
8280 Require source files to be present. In this mode, the binder must be
8281 able to locate all source files that are referenced, in order to check
8282 their consistency. In normal mode, if a source file cannot be located it
8283 is simply ignored. If you specify this switch, a missing source
8284 file is an error.
8286 @item -Wx@var{e}
8287 @cindex @option{-Wx} (@code{gnatbind})
8288 Override default wide character encoding for standard Text_IO files.
8289 Normally the default wide character encoding method used for standard
8290 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8291 the main source input (see description of switch
8292 @option{-gnatWx} for the compiler). The
8293 use of this switch for the binder (which has the same set of
8294 possible arguments) overrides this default as specified.
8296 @item -x
8297 @cindex @option{-x} (@code{gnatbind})
8298 Exclude source files. In this mode, the binder only checks that ALI
8299 files are consistent with one another. Source files are not accessed.
8300 The binder runs faster in this mode, and there is still a guarantee that
8301 the resulting program is self-consistent.
8302 If a source file has been edited since it was last compiled, and you
8303 specify this switch, the binder will not detect that the object
8304 file is out of date with respect to the source file. Note that this is the
8305 mode that is automatically used by @command{gnatmake} because in this
8306 case the checking against sources has already been performed by
8307 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8309 @end table
8311 @node Binder Error Message Control
8312 @subsection Binder Error Message Control
8314 @noindent
8315 The following switches provide control over the generation of error
8316 messages from the binder:
8318 @table @option
8319 @c !sort!
8320 @item -v
8321 @cindex @option{-v} (@code{gnatbind})
8322 Verbose mode. In the normal mode, brief error messages are generated to
8323 @file{stderr}. If this switch is present, a header is written
8324 to @file{stdout} and any error messages are directed to @file{stdout}.
8325 All that is written to @file{stderr} is a brief summary message.
8327 @item -b
8328 @cindex @option{-b} (@code{gnatbind})
8329 Generate brief error messages to @file{stderr} even if verbose mode is
8330 specified. This is relevant only when used with the
8331 @option{-v} switch.
8333 @item -m@var{n}
8334 @cindex @option{-m} (@code{gnatbind})
8335 Limits the number of error messages to @var{n}, a decimal integer in the
8336 range 1-999. The binder terminates immediately if this limit is reached.
8338 @item -M@var{xxx}
8339 @cindex @option{-M} (@code{gnatbind})
8340 Renames the generated main program from @code{main} to @code{xxx}.
8341 This is useful in the case of some cross-building environments, where
8342 the actual main program is separate from the one generated
8343 by @code{gnatbind}.
8345 @item -ws
8346 @cindex @option{-ws} (@code{gnatbind})
8347 @cindex Warnings
8348 Suppress all warning messages.
8350 @item -we
8351 @cindex @option{-we} (@code{gnatbind})
8352 Treat any warning messages as fatal errors.
8355 @item -t
8356 @cindex @option{-t} (@code{gnatbind})
8357 @cindex Time stamp checks, in binder
8358 @cindex Binder consistency checks
8359 @cindex Consistency checks, in binder
8360 The binder performs a number of consistency checks including:
8362 @itemize @bullet
8363 @item
8364 Check that time stamps of a given source unit are consistent
8365 @item
8366 Check that checksums of a given source unit are consistent
8367 @item
8368 Check that consistent versions of @code{GNAT} were used for compilation
8369 @item
8370 Check consistency of configuration pragmas as required
8371 @end itemize
8373 @noindent
8374 Normally failure of such checks, in accordance with the consistency
8375 requirements of the Ada Reference Manual, causes error messages to be
8376 generated which abort the binder and prevent the output of a binder
8377 file and subsequent link to obtain an executable.
8379 The @option{-t} switch converts these error messages
8380 into warnings, so that
8381 binding and linking can continue to completion even in the presence of such
8382 errors. The result may be a failed link (due to missing symbols), or a
8383 non-functional executable which has undefined semantics.
8384 @emph{This means that
8385 @option{-t} should be used only in unusual situations,
8386 with extreme care.}
8387 @end table
8389 @node Elaboration Control
8390 @subsection Elaboration Control
8392 @noindent
8393 The following switches provide additional control over the elaboration
8394 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8396 @table @option
8397 @item -p
8398 @cindex @option{-p} (@code{gnatbind})
8399 Normally the binder attempts to choose an elaboration order that is
8400 likely to minimize the likelihood of an elaboration order error resulting
8401 in raising a @code{Program_Error} exception. This switch reverses the
8402 action of the binder, and requests that it deliberately choose an order
8403 that is likely to maximize the likelihood of an elaboration error.
8404 This is useful in ensuring portability and avoiding dependence on
8405 accidental fortuitous elaboration ordering.
8407 Normally it only makes sense to use the @option{-p}
8408 switch if dynamic
8409 elaboration checking is used (@option{-gnatE} switch used for compilation).
8410 This is because in the default static elaboration mode, all necessary
8411 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8412 These implicit pragmas are still respected by the binder in
8413 @option{-p} mode, so a
8414 safe elaboration order is assured.
8416 Note that @option{-p} is not intended for
8417 production use; it is more for debugging/experimental use.
8418 @end table
8420 @node Output Control
8421 @subsection Output Control
8423 @noindent
8424 The following switches allow additional control over the output
8425 generated by the binder.
8427 @table @option
8428 @c !sort!
8430 @item -c
8431 @cindex @option{-c} (@code{gnatbind})
8432 Check only. Do not generate the binder output file. In this mode the
8433 binder performs all error checks but does not generate an output file.
8435 @item -e
8436 @cindex @option{-e} (@code{gnatbind})
8437 Output complete list of elaboration-order dependencies, showing the
8438 reason for each dependency. This output can be rather extensive but may
8439 be useful in diagnosing problems with elaboration order. The output is
8440 written to @file{stdout}.
8442 @item -h
8443 @cindex @option{-h} (@code{gnatbind})
8444 Output usage information. The output is written to @file{stdout}.
8446 @item -K
8447 @cindex @option{-K} (@code{gnatbind})
8448 Output linker options to @file{stdout}. Includes library search paths,
8449 contents of pragmas Ident and Linker_Options, and libraries added
8450 by @code{gnatbind}.
8452 @item -l
8453 @cindex @option{-l} (@code{gnatbind})
8454 Output chosen elaboration order. The output is written to @file{stdout}.
8456 @item -O
8457 @cindex @option{-O} (@code{gnatbind})
8458 Output full names of all the object files that must be linked to provide
8459 the Ada component of the program. The output is written to @file{stdout}.
8460 This list includes the files explicitly supplied and referenced by the user
8461 as well as implicitly referenced run-time unit files. The latter are
8462 omitted if the corresponding units reside in shared libraries. The
8463 directory names for the run-time units depend on the system configuration.
8465 @item -o @var{file}
8466 @cindex @option{-o} (@code{gnatbind})
8467 Set name of output file to @var{file} instead of the normal
8468 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8469 binder generated body filename.
8470 Note that if this option is used, then linking must be done manually.
8471 It is not possible to use gnatlink in this case, since it cannot locate
8472 the binder file.
8474 @item -r
8475 @cindex @option{-r} (@code{gnatbind})
8476 Generate list of @code{pragma Restrictions} that could be applied to
8477 the current unit. This is useful for code audit purposes, and also may
8478 be used to improve code generation in some cases.
8480 @end table
8482 @node Dynamic Allocation Control
8483 @subsection Dynamic Allocation Control
8485 @noindent
8486 The heap control switches -- @option{-H32} and @option{-H64} --
8487 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8488 They only affect compiler-generated allocations via @code{__gnat_malloc};
8489 explicit calls to @code{malloc} and related functions from the C
8490 run-time library are unaffected.
8492 @table @option
8493 @item -H32
8494 Allocate memory on 32-bit heap
8496 @item -H64
8497 Allocate memory on 64-bit heap.  This is the default
8498 unless explicitly overridden by a @code{'Size} clause on the access type.
8499 @end table
8501 @noindent
8502 These switches are only effective on VMS platforms.
8505 @node Binding with Non-Ada Main Programs
8506 @subsection Binding with Non-Ada Main Programs
8508 @noindent
8509 In our description so far we have assumed that the main
8510 program is in Ada, and that the task of the binder is to generate a
8511 corresponding function @code{main} that invokes this Ada main
8512 program. GNAT also supports the building of executable programs where
8513 the main program is not in Ada, but some of the called routines are
8514 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8515 The following switch is used in this situation:
8517 @table @option
8518 @item -n
8519 @cindex @option{-n} (@code{gnatbind})
8520 No main program. The main program is not in Ada.
8521 @end table
8523 @noindent
8524 In this case, most of the functions of the binder are still required,
8525 but instead of generating a main program, the binder generates a file
8526 containing the following callable routines:
8528 @table @code
8529 @item adainit
8530 @findex adainit
8531 You must call this routine to initialize the Ada part of the program by
8532 calling the necessary elaboration routines. A call to @code{adainit} is
8533 required before the first call to an Ada subprogram.
8535 Note that it is assumed that the basic execution environment must be setup
8536 to be appropriate for Ada execution at the point where the first Ada
8537 subprogram is called. In particular, if the Ada code will do any
8538 floating-point operations, then the FPU must be setup in an appropriate
8539 manner. For the case of the x86, for example, full precision mode is
8540 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8541 that the FPU is in the right state.
8543 @item adafinal
8544 @findex adafinal
8545 You must call this routine to perform any library-level finalization
8546 required by the Ada subprograms. A call to @code{adafinal} is required
8547 after the last call to an Ada subprogram, and before the program
8548 terminates.
8549 @end table
8551 @noindent
8552 If the @option{-n} switch
8553 @cindex @option{-n} (@command{gnatbind})
8554 @cindex Binder, multiple input files
8555 is given, more than one ALI file may appear on
8556 the command line for @code{gnatbind}. The normal @dfn{closure}
8557 calculation is performed for each of the specified units. Calculating
8558 the closure means finding out the set of units involved by tracing
8559 @code{with} references. The reason it is necessary to be able to
8560 specify more than one ALI file is that a given program may invoke two or
8561 more quite separate groups of Ada units.
8563 The binder takes the name of its output file from the last specified ALI
8564 file, unless overridden by the use of the @option{-o file}.
8565 @cindex @option{-o} (@command{gnatbind})
8566 The output is an Ada unit in source form that can be compiled with GNAT.
8567 This compilation occurs automatically as part of the @command{gnatlink}
8568 processing.
8570 Currently the GNAT run time requires a FPU using 80 bits mode
8571 precision. Under targets where this is not the default it is required to
8572 call GNAT.Float_Control.Reset before using floating point numbers (this
8573 include float computation, float input and output) in the Ada code. A
8574 side effect is that this could be the wrong mode for the foreign code
8575 where floating point computation could be broken after this call.
8577 @node Binding Programs with No Main Subprogram
8578 @subsection Binding Programs with No Main Subprogram
8580 @noindent
8581 It is possible to have an Ada program which does not have a main
8582 subprogram. This program will call the elaboration routines of all the
8583 packages, then the finalization routines.
8585 The following switch is used to bind programs organized in this manner:
8587 @table @option
8588 @item -z
8589 @cindex @option{-z} (@code{gnatbind})
8590 Normally the binder checks that the unit name given on the command line
8591 corresponds to a suitable main subprogram. When this switch is used,
8592 a list of ALI files can be given, and the execution of the program
8593 consists of elaboration of these units in an appropriate order. Note
8594 that the default wide character encoding method for standard Text_IO
8595 files is always set to Brackets if this switch is set (you can use
8596 the binder switch
8597 @option{-Wx} to override this default).
8598 @end table
8600 @node Command-Line Access
8601 @section Command-Line Access
8603 @noindent
8604 The package @code{Ada.Command_Line} provides access to the command-line
8605 arguments and program name. In order for this interface to operate
8606 correctly, the two variables
8608 @smallexample
8609 @group
8610 int gnat_argc;
8611 char **gnat_argv;
8612 @end group
8613 @end smallexample
8615 @noindent
8616 @findex gnat_argv
8617 @findex gnat_argc
8618 are declared in one of the GNAT library routines. These variables must
8619 be set from the actual @code{argc} and @code{argv} values passed to the
8620 main program. With no @option{n} present, @code{gnatbind}
8621 generates the C main program to automatically set these variables.
8622 If the @option{n} switch is used, there is no automatic way to
8623 set these variables. If they are not set, the procedures in
8624 @code{Ada.Command_Line} will not be available, and any attempt to use
8625 them will raise @code{Constraint_Error}. If command line access is
8626 required, your main program must set @code{gnat_argc} and
8627 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8630 @node Search Paths for gnatbind
8631 @section Search Paths for @code{gnatbind}
8633 @noindent
8634 The binder takes the name of an ALI file as its argument and needs to
8635 locate source files as well as other ALI files to verify object consistency.
8637 For source files, it follows exactly the same search rules as @command{gcc}
8638 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8639 directories searched are:
8641 @enumerate
8642 @item
8643 The directory containing the ALI file named in the command line, unless
8644 the switch @option{-I-} is specified.
8646 @item
8647 All directories specified by @option{-I}
8648 switches on the @code{gnatbind}
8649 command line, in the order given.
8651 @item
8652 @findex ADA_PRJ_OBJECTS_FILE
8653 Each of the directories listed in the text file whose name is given
8654 by the @env{ADA_PRJ_OBJECTS_FILE} environment variable.
8656 @noindent
8657 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
8658 driver when project files are used. It should not normally be set
8659 by other means.
8661 @item
8662 @findex ADA_OBJECTS_PATH
8663 Each of the directories listed in the value of the
8664 @env{ADA_OBJECTS_PATH} environment variable.
8665 Construct this value
8666 exactly as the @env{PATH} environment variable: a list of directory
8667 names separated by colons (semicolons when working with the NT version
8668 of GNAT).
8670 @item
8671 The content of the @file{ada_object_path} file which is part of the GNAT
8672 installation tree and is used to store standard libraries such as the
8673 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8674 specified.
8675 @ref{Installing a library}
8676 @end enumerate
8678 @noindent
8679 In the binder the switch @option{-I}
8680 @cindex @option{-I} (@command{gnatbind})
8681 is used to specify both source and
8682 library file paths. Use @option{-aI}
8683 @cindex @option{-aI} (@command{gnatbind})
8684 instead if you want to specify
8685 source paths only, and @option{-aO}
8686 @cindex @option{-aO} (@command{gnatbind})
8687 if you want to specify library paths
8688 only. This means that for the binder
8689 @option{-I}@var{dir} is equivalent to
8690 @option{-aI}@var{dir}
8691 @option{-aO}@var{dir}.
8692 The binder generates the bind file (a C language source file) in the
8693 current working directory.
8695 @findex Ada
8696 @findex System
8697 @findex Interfaces
8698 @findex GNAT
8699 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8700 children make up the GNAT Run-Time Library, together with the package
8701 GNAT and its children, which contain a set of useful additional
8702 library functions provided by GNAT. The sources for these units are
8703 needed by the compiler and are kept together in one directory. The ALI
8704 files and object files generated by compiling the RTL are needed by the
8705 binder and the linker and are kept together in one directory, typically
8706 different from the directory containing the sources. In a normal
8707 installation, you need not specify these directory names when compiling
8708 or binding. Either the environment variables or the built-in defaults
8709 cause these files to be found.
8711 Besides simplifying access to the RTL, a major use of search paths is
8712 in compiling sources from multiple directories. This can make
8713 development environments much more flexible.
8715 @node Examples of gnatbind Usage
8716 @section Examples of @code{gnatbind} Usage
8718 @noindent
8719 This section contains a number of examples of using the GNAT binding
8720 utility @code{gnatbind}.
8722 @table @code
8723 @item gnatbind hello
8724 The main program @code{Hello} (source program in @file{hello.adb}) is
8725 bound using the standard switch settings. The generated main program is
8726 @file{b~hello.adb}. This is the normal, default use of the binder.
8728 @item gnatbind hello -o mainprog.adb
8729 The main program @code{Hello} (source program in @file{hello.adb}) is
8730 bound using the standard switch settings. The generated main program is
8731 @file{mainprog.adb} with the associated spec in
8732 @file{mainprog.ads}. Note that you must specify the body here not the
8733 spec. Note that if this option is used, then linking must be done manually,
8734 since gnatlink will not be able to find the generated file.
8735 @end table
8737 @c ------------------------------------
8738 @node Linking with gnatlink
8739 @chapter Linking with @command{gnatlink}
8740 @c ------------------------------------
8741 @findex gnatlink
8743 @noindent
8744 This chapter discusses @command{gnatlink}, a tool that links
8745 an Ada program and builds an executable file. This utility
8746 invokes the system linker (via the @command{gcc} command)
8747 with a correct list of object files and library references.
8748 @command{gnatlink} automatically determines the list of files and
8749 references for the Ada part of a program. It uses the binder file
8750 generated by the @command{gnatbind} to determine this list.
8752 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8753 driver (see @ref{The GNAT Driver and Project Files}).
8755 @menu
8756 * Running gnatlink::
8757 * Switches for gnatlink::
8758 @end menu
8760 @node Running gnatlink
8761 @section Running @command{gnatlink}
8763 @noindent
8764 The form of the @command{gnatlink} command is
8766 @smallexample
8767 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8768 @c            @ovar{non-Ada objects} @ovar{linker options}
8769 @c Expanding @ovar macro inline (explanation in macro def comments)
8770 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8771            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8773 @end smallexample
8775 @noindent
8776 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8777 non-Ada objects
8778 or linker options) may be in any order, provided that no non-Ada object may
8779 be mistaken for a main @file{ALI} file.
8780 Any file name @file{F} without the @file{.ali}
8781 extension will be taken as the main @file{ALI} file if a file exists
8782 whose name is the concatenation of @file{F} and @file{.ali}.
8784 @noindent
8785 @file{@var{mainprog}.ali} references the ALI file of the main program.
8786 The @file{.ali} extension of this file can be omitted. From this
8787 reference, @command{gnatlink} locates the corresponding binder file
8788 @file{b~@var{mainprog}.adb} and, using the information in this file along
8789 with the list of non-Ada objects and linker options, constructs a
8790 linker command file to create the executable.
8792 The arguments other than the @command{gnatlink} switches and the main
8793 @file{ALI} file are passed to the linker uninterpreted.
8794 They typically include the names of
8795 object files for units written in other languages than Ada and any library
8796 references required to resolve references in any of these foreign language
8797 units, or in @code{Import} pragmas in any Ada units.
8799 @var{linker options} is an optional list of linker specific
8800 switches.
8801 The default linker called by gnatlink is @command{gcc} which in
8802 turn calls the appropriate system linker.
8804 One useful option for the linker is @option{-s}: it reduces the size of the
8805 executable by removing all symbol table and relocation information from the
8806 executable.
8808 Standard options for the linker such as @option{-lmy_lib} or
8809 @option{-Ldir} can be added as is.
8810 For options that are not recognized by
8811 @command{gcc} as linker options, use the @command{gcc} switches
8812 @option{-Xlinker} or @option{-Wl,}.
8814 Refer to the GCC documentation for
8815 details.
8817 Here is an example showing how to generate a linker map:
8819 @smallexample
8820 $ gnatlink my_prog -Wl,-Map,MAPFILE
8821 @end smallexample
8823 Using @var{linker options} it is possible to set the program stack and
8824 heap size.
8825 See @ref{Setting Stack Size from gnatlink} and
8826 @ref{Setting Heap Size from gnatlink}.
8828 @command{gnatlink} determines the list of objects required by the Ada
8829 program and prepends them to the list of objects passed to the linker.
8830 @command{gnatlink} also gathers any arguments set by the use of
8831 @code{pragma Linker_Options} and adds them to the list of arguments
8832 presented to the linker.
8835 @node Switches for gnatlink
8836 @section Switches for @command{gnatlink}
8838 @noindent
8839 The following switches are available with the @command{gnatlink} utility:
8841 @table @option
8842 @c !sort!
8844 @item --version
8845 @cindex @option{--version} @command{gnatlink}
8846 Display Copyright and version, then exit disregarding all other options.
8848 @item --help
8849 @cindex @option{--help} @command{gnatlink}
8850 If @option{--version} was not used, display usage, then exit disregarding
8851 all other options.
8853 @item -f
8854 @cindex Command line length
8855 @cindex @option{-f} (@command{gnatlink})
8856 On some targets, the command line length is limited, and @command{gnatlink}
8857 will generate a separate file for the linker if the list of object files
8858 is too long.
8859 The @option{-f} switch forces this file
8860 to be generated even if
8861 the limit is not exceeded. This is useful in some cases to deal with
8862 special situations where the command line length is exceeded.
8864 @item -g
8865 @cindex Debugging information, including
8866 @cindex @option{-g} (@command{gnatlink})
8867 The option to include debugging information causes the Ada bind file (in
8868 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8869 @option{-g}.
8870 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8871 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8872 Without @option{-g}, the binder removes these files by
8873 default. The same procedure apply if a C bind file was generated using
8874 @option{-C} @code{gnatbind} option, in this case the filenames
8875 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8877 @item -n
8878 @cindex @option{-n} (@command{gnatlink})
8879 Do not compile the file generated by the binder. This may be used when
8880 a link is rerun with different options, but there is no need to recompile
8881 the binder file.
8883 @item -v
8884 @cindex @option{-v} (@command{gnatlink})
8885 Causes additional information to be output, including a full list of the
8886 included object files. This switch option is most useful when you want
8887 to see what set of object files are being used in the link step.
8889 @item -v -v
8890 @cindex @option{-v -v} (@command{gnatlink})
8891 Very verbose mode. Requests that the compiler operate in verbose mode when
8892 it compiles the binder file, and that the system linker run in verbose mode.
8894 @item -o @var{exec-name}
8895 @cindex @option{-o} (@command{gnatlink})
8896 @var{exec-name} specifies an alternate name for the generated
8897 executable program. If this switch is omitted, the executable has the same
8898 name as the main unit. For example, @code{gnatlink try.ali} creates
8899 an executable called @file{try}.
8901 @item -b @var{target}
8902 @cindex @option{-b} (@command{gnatlink})
8903 Compile your program to run on @var{target}, which is the name of a
8904 system configuration. You must have a GNAT cross-compiler built if
8905 @var{target} is not the same as your host system.
8907 @item -B@var{dir}
8908 @cindex @option{-B} (@command{gnatlink})
8909 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8910 from @var{dir} instead of the default location. Only use this switch
8911 when multiple versions of the GNAT compiler are available.
8912 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8913 for further details. You would normally use the @option{-b} or
8914 @option{-V} switch instead.
8916 @item -M
8917 When linking an executable, create a map file. The name of the map file
8918 has the same name as the executable with extension ".map".
8920 @item -M=mapfile
8921 When linking an executable, create a map file. The name of the map file is
8922 "mapfile".
8924 @item --GCC=@var{compiler_name}
8925 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8926 Program used for compiling the binder file. The default is
8927 @command{gcc}. You need to use quotes around @var{compiler_name} if
8928 @code{compiler_name} contains spaces or other separator characters.
8929 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8930 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8931 inserted after your command name. Thus in the above example the compiler
8932 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8933 A limitation of this syntax is that the name and path name of the executable
8934 itself must not include any embedded spaces. If the compiler executable is
8935 different from the default one (gcc or <prefix>-gcc), then the back-end
8936 switches in the ALI file are not used to compile the binder generated source.
8937 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8938 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8939 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8940 is taken into account. However, all the additional switches are also taken
8941 into account. Thus,
8942 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8943 @option{--GCC="bar -x -y -z -t"}.
8945 @item --LINK=@var{name}
8946 @cindex @option{--LINK=} (@command{gnatlink})
8947 @var{name} is the name of the linker to be invoked. This is especially
8948 useful in mixed language programs since languages such as C++ require
8949 their own linker to be used. When this switch is omitted, the default
8950 name for the linker is @command{gcc}. When this switch is used, the
8951 specified linker is called instead of @command{gcc} with exactly the same
8952 parameters that would have been passed to @command{gcc} so if the desired
8953 linker requires different parameters it is necessary to use a wrapper
8954 script that massages the parameters before invoking the real linker. It
8955 may be useful to control the exact invocation by using the verbose
8956 switch.
8960 @end table
8962 @node The GNAT Make Program gnatmake
8963 @chapter The GNAT Make Program @command{gnatmake}
8964 @findex gnatmake
8966 @menu
8967 * Running gnatmake::
8968 * Switches for gnatmake::
8969 * Mode Switches for gnatmake::
8970 * Notes on the Command Line::
8971 * How gnatmake Works::
8972 * Examples of gnatmake Usage::
8973 @end menu
8974 @noindent
8975 A typical development cycle when working on an Ada program consists of
8976 the following steps:
8978 @enumerate
8979 @item
8980 Edit some sources to fix bugs.
8982 @item
8983 Add enhancements.
8985 @item
8986 Compile all sources affected.
8988 @item
8989 Rebind and relink.
8991 @item
8992 Test.
8993 @end enumerate
8995 @noindent
8996 The third step can be tricky, because not only do the modified files
8997 @cindex Dependency rules
8998 have to be compiled, but any files depending on these files must also be
8999 recompiled. The dependency rules in Ada can be quite complex, especially
9000 in the presence of overloading, @code{use} clauses, generics and inlined
9001 subprograms.
9003 @command{gnatmake} automatically takes care of the third and fourth steps
9004 of this process. It determines which sources need to be compiled,
9005 compiles them, and binds and links the resulting object files.
9007 Unlike some other Ada make programs, the dependencies are always
9008 accurately recomputed from the new sources. The source based approach of
9009 the GNAT compilation model makes this possible. This means that if
9010 changes to the source program cause corresponding changes in
9011 dependencies, they will always be tracked exactly correctly by
9012 @command{gnatmake}.
9014 @node Running gnatmake
9015 @section Running @command{gnatmake}
9017 @noindent
9018 The usual form of the @command{gnatmake} command is
9020 @smallexample
9021 @c $ gnatmake @ovar{switches} @var{file_name}
9022 @c       @ovar{file_names} @ovar{mode_switches}
9023 @c Expanding @ovar macro inline (explanation in macro def comments)
9024 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9025       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9026 @end smallexample
9028 @noindent
9029 The only required argument is one @var{file_name}, which specifies
9030 a compilation unit that is a main program. Several @var{file_names} can be
9031 specified: this will result in several executables being built.
9032 If @code{switches} are present, they can be placed before the first
9033 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9034 If @var{mode_switches} are present, they must always be placed after
9035 the last @var{file_name} and all @code{switches}.
9037 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9038 extension may be omitted from the @var{file_name} arguments. However, if
9039 you are using non-standard extensions, then it is required that the
9040 extension be given. A relative or absolute directory path can be
9041 specified in a @var{file_name}, in which case, the input source file will
9042 be searched for in the specified directory only. Otherwise, the input
9043 source file will first be searched in the directory where
9044 @command{gnatmake} was invoked and if it is not found, it will be search on
9045 the source path of the compiler as described in
9046 @ref{Search Paths and the Run-Time Library (RTL)}.
9048 All @command{gnatmake} output (except when you specify
9049 @option{-M}) is to
9050 @file{stderr}. The output produced by the
9051 @option{-M} switch is send to
9052 @file{stdout}.
9054 @node Switches for gnatmake
9055 @section Switches for @command{gnatmake}
9057 @noindent
9058 You may specify any of the following switches to @command{gnatmake}:
9060 @table @option
9061 @c !sort!
9063 @item --version
9064 @cindex @option{--version} @command{gnatmake}
9065 Display Copyright and version, then exit disregarding all other options.
9067 @item --help
9068 @cindex @option{--help} @command{gnatmake}
9069 If @option{--version} was not used, display usage, then exit disregarding
9070 all other options.
9072 @item --GCC=@var{compiler_name}
9073 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9074 Program used for compiling. The default is `@command{gcc}'. You need to use
9075 quotes around @var{compiler_name} if @code{compiler_name} contains
9076 spaces or other separator characters. As an example @option{--GCC="foo -x
9077 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9078 compiler. A limitation of this syntax is that the name and path name of
9079 the executable itself must not include any embedded spaces. Note that
9080 switch @option{-c} is always inserted after your command name. Thus in the
9081 above example the compiler command that will be used by @command{gnatmake}
9082 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9083 used, only the last @var{compiler_name} is taken into account. However,
9084 all the additional switches are also taken into account. Thus,
9085 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9086 @option{--GCC="bar -x -y -z -t"}.
9088 @item --GNATBIND=@var{binder_name}
9089 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9090 Program used for binding. The default is `@code{gnatbind}'. You need to
9091 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9092 or other separator characters. As an example @option{--GNATBIND="bar -x
9093 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9094 binder. Binder switches that are normally appended by @command{gnatmake}
9095 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9096 A limitation of this syntax is that the name and path name of the executable
9097 itself must not include any embedded spaces.
9099 @item --GNATLINK=@var{linker_name}
9100 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9101 Program used for linking. The default is `@command{gnatlink}'. You need to
9102 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9103 or other separator characters. As an example @option{--GNATLINK="lan -x
9104 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9105 linker. Linker switches that are normally appended by @command{gnatmake} to
9106 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9107 A limitation of this syntax is that the name and path name of the executable
9108 itself must not include any embedded spaces.
9111 @item --subdirs=subdir
9112 Actual object directory of each project file is the subdirectory subdir of the
9113 object directory specified or defaulted in the project file.
9115 @item --single-compile-per-obj-dir
9116 Disallow simultaneous compilations in the same object directory when
9117 project files are used.
9119 @item --unchecked-shared-lib-imports
9120 By default, shared library projects are not allowed to import static library
9121 projects. When this switch is used on the command line, this restriction is
9122 relaxed.
9124 @item --source-info=<source info file>
9125 Specify a source info file. This switch is active only when project files
9126 are used. If the source info file is specified as a relative path, then it is
9127 relative to the object directory of the main project. If the source info file
9128 does not exist, then after the Project Manager has successfully parsed and
9129 processed the project files and found the sources, it creates the source info
9130 file. If the source info file already exists and can be read successfully,
9131 then the Project Manager will get all the needed information about the sources
9132 from the source info file and will not look for them. This reduces the time
9133 to process the project files, especially when looking for sources that take a
9134 long time. If the source info file exists but cannot be parsed successfully,
9135 the Project Manager will attempt to recreate it. If the Project Manager fails
9136 to create the source info file, a message is issued, but gnatmake does not
9137 fail. @command{gnatmake} "trusts" the source info file. This means that
9138 if the source files have changed (addition, deletion, moving to a different
9139 source directory), then the source info file need to be deleted and recreated.
9141 @item --create-map-file
9142 When linking an executable, create a map file. The name of the map file
9143 has the same name as the executable with extension ".map".
9145 @item --create-map-file=mapfile
9146 When linking an executable, create a map file. The name of the map file is
9147 "mapfile".
9150 @item -a
9151 @cindex @option{-a} (@command{gnatmake})
9152 Consider all files in the make process, even the GNAT internal system
9153 files (for example, the predefined Ada library files), as well as any
9154 locked files. Locked files are files whose ALI file is write-protected.
9155 By default,
9156 @command{gnatmake} does not check these files,
9157 because the assumption is that the GNAT internal files are properly up
9158 to date, and also that any write protected ALI files have been properly
9159 installed. Note that if there is an installation problem, such that one
9160 of these files is not up to date, it will be properly caught by the
9161 binder.
9162 You may have to specify this switch if you are working on GNAT
9163 itself. The switch @option{-a} is also useful
9164 in conjunction with @option{-f}
9165 if you need to recompile an entire application,
9166 including run-time files, using special configuration pragmas,
9167 such as a @code{Normalize_Scalars} pragma.
9169 By default
9170 @code{gnatmake -a} compiles all GNAT
9171 internal files with
9172 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9174 @item -b
9175 @cindex @option{-b} (@command{gnatmake})
9176 Bind only. Can be combined with @option{-c} to do
9177 compilation and binding, but no link.
9178 Can be combined with @option{-l}
9179 to do binding and linking. When not combined with
9180 @option{-c}
9181 all the units in the closure of the main program must have been previously
9182 compiled and must be up to date. The root unit specified by @var{file_name}
9183 may be given without extension, with the source extension or, if no GNAT
9184 Project File is specified, with the ALI file extension.
9186 @item -c
9187 @cindex @option{-c} (@command{gnatmake})
9188 Compile only. Do not perform binding, except when @option{-b}
9189 is also specified. Do not perform linking, except if both
9190 @option{-b} and
9191 @option{-l} are also specified.
9192 If the root unit specified by @var{file_name} is not a main unit, this is the
9193 default. Otherwise @command{gnatmake} will attempt binding and linking
9194 unless all objects are up to date and the executable is more recent than
9195 the objects.
9197 @item -C
9198 @cindex @option{-C} (@command{gnatmake})
9199 Use a temporary mapping file. A mapping file is a way to communicate
9200 to the compiler two mappings: from unit names to file names (without
9201 any directory information) and from file names to path names (with
9202 full directory information). A mapping file can make the compiler's
9203 file searches faster, especially if there are many source directories,
9204 or the sources are read over a slow network connection. If
9205 @option{-P} is used, a mapping file is always used, so
9206 @option{-C} is unnecessary; in this case the mapping file
9207 is initially populated based on the project file. If
9208 @option{-C} is used without
9209 @option{-P},
9210 the mapping file is initially empty. Each invocation of the compiler
9211 will add any newly accessed sources to the mapping file.
9213 @item -C=@var{file}
9214 @cindex @option{-C=} (@command{gnatmake})
9215 Use a specific mapping file. The file, specified as a path name (absolute or
9216 relative) by this switch, should already exist, otherwise the switch is
9217 ineffective. The specified mapping file will be communicated to the compiler.
9218 This switch is not compatible with a project file
9219 (-P@var{file}) or with multiple compiling processes
9220 (-jnnn, when nnn is greater than 1).
9222 @item -d
9223 @cindex @option{-d} (@command{gnatmake})
9224 Display progress for each source, up to date or not, as a single line
9226 @smallexample
9227 completed x out of y (zz%)
9228 @end smallexample
9230 If the file needs to be compiled this is displayed after the invocation of
9231 the compiler. These lines are displayed even in quiet output mode.
9233 @item -D @var{dir}
9234 @cindex @option{-D} (@command{gnatmake})
9235 Put all object files and ALI file in directory @var{dir}.
9236 If the @option{-D} switch is not used, all object files
9237 and ALI files go in the current working directory.
9239 This switch cannot be used when using a project file.
9241 @item -eInnn
9242 @cindex @option{-eI} (@command{gnatmake})
9243 Indicates that the main source is a multi-unit source and the rank of the unit
9244 in the source file is nnn. nnn needs to be a positive number and a valid
9245 index in the source. This switch cannot be used when @command{gnatmake} is
9246 invoked for several mains.
9248 @item -eL
9249 @cindex @option{-eL} (@command{gnatmake})
9250 @cindex symbolic links
9251 Follow all symbolic links when processing project files.
9252 This should be used if your project uses symbolic links for files or
9253 directories, but is not needed in other cases.
9255 @cindex naming scheme
9256 This also assumes that no directory matches the naming scheme for files (for
9257 instance that you do not have a directory called "sources.ads" when using the
9258 default GNAT naming scheme).
9260 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9261 save a lot of system calls (several per source file and object file), which
9262 can result in a significant speed up to load and manipulate a project file,
9263 especially when using source files from a remote system.
9266 @item -eS
9267 @cindex @option{-eS} (@command{gnatmake})
9268 Output the commands for the compiler, the binder and the linker
9269 on standard output,
9270 instead of standard error.
9272 @item -f
9273 @cindex @option{-f} (@command{gnatmake})
9274 Force recompilations. Recompile all sources, even though some object
9275 files may be up to date, but don't recompile predefined or GNAT internal
9276 files or locked files (files with a write-protected ALI file),
9277 unless the @option{-a} switch is also specified.
9279 @item -F
9280 @cindex @option{-F} (@command{gnatmake})
9281 When using project files, if some errors or warnings are detected during
9282 parsing and verbose mode is not in effect (no use of switch
9283 -v), then error lines start with the full path name of the project
9284 file, rather than its simple file name.
9286 @item -g
9287 @cindex @option{-g} (@command{gnatmake})
9288 Enable debugging. This switch is simply passed to the compiler and to the
9289 linker.
9291 @item -i
9292 @cindex @option{-i} (@command{gnatmake})
9293 In normal mode, @command{gnatmake} compiles all object files and ALI files
9294 into the current directory. If the @option{-i} switch is used,
9295 then instead object files and ALI files that already exist are overwritten
9296 in place. This means that once a large project is organized into separate
9297 directories in the desired manner, then @command{gnatmake} will automatically
9298 maintain and update this organization. If no ALI files are found on the
9299 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9300 the new object and ALI files are created in the
9301 directory containing the source being compiled. If another organization
9302 is desired, where objects and sources are kept in different directories,
9303 a useful technique is to create dummy ALI files in the desired directories.
9304 When detecting such a dummy file, @command{gnatmake} will be forced to
9305 recompile the corresponding source file, and it will be put the resulting
9306 object and ALI files in the directory where it found the dummy file.
9308 @item -j@var{n}
9309 @cindex @option{-j} (@command{gnatmake})
9310 @cindex Parallel make
9311 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9312 machine compilations will occur in parallel. If @var{n} is 0, then the
9313 maximum number of parallel compilations is the number of core processors
9314 on the platform. In the event of compilation errors, messages from various
9315 compilations might get interspersed (but @command{gnatmake} will give you the
9316 full ordered list of failing compiles at the end). If this is problematic,
9317 rerun the make process with n set to 1 to get a clean list of messages.
9319 @item -k
9320 @cindex @option{-k} (@command{gnatmake})
9321 Keep going. Continue as much as possible after a compilation error. To
9322 ease the programmer's task in case of compilation errors, the list of
9323 sources for which the compile fails is given when @command{gnatmake}
9324 terminates.
9326 If @command{gnatmake} is invoked with several @file{file_names} and with this
9327 switch, if there are compilation errors when building an executable,
9328 @command{gnatmake} will not attempt to build the following executables.
9330 @item -l
9331 @cindex @option{-l} (@command{gnatmake})
9332 Link only. Can be combined with @option{-b} to binding
9333 and linking. Linking will not be performed if combined with
9334 @option{-c}
9335 but not with @option{-b}.
9336 When not combined with @option{-b}
9337 all the units in the closure of the main program must have been previously
9338 compiled and must be up to date, and the main program needs to have been bound.
9339 The root unit specified by @var{file_name}
9340 may be given without extension, with the source extension or, if no GNAT
9341 Project File is specified, with the ALI file extension.
9343 @item -m
9344 @cindex @option{-m} (@command{gnatmake})
9345 Specify that the minimum necessary amount of recompilations
9346 be performed. In this mode @command{gnatmake} ignores time
9347 stamp differences when the only
9348 modifications to a source file consist in adding/removing comments,
9349 empty lines, spaces or tabs. This means that if you have changed the
9350 comments in a source file or have simply reformatted it, using this
9351 switch will tell @command{gnatmake} not to recompile files that depend on it
9352 (provided other sources on which these files depend have undergone no
9353 semantic modifications). Note that the debugging information may be
9354 out of date with respect to the sources if the @option{-m} switch causes
9355 a compilation to be switched, so the use of this switch represents a
9356 trade-off between compilation time and accurate debugging information.
9358 @item -M
9359 @cindex Dependencies, producing list
9360 @cindex @option{-M} (@command{gnatmake})
9361 Check if all objects are up to date. If they are, output the object
9362 dependences to @file{stdout} in a form that can be directly exploited in
9363 a @file{Makefile}. By default, each source file is prefixed with its
9364 (relative or absolute) directory name. This name is whatever you
9365 specified in the various @option{-aI}
9366 and @option{-I} switches. If you use
9367 @code{gnatmake -M}
9368 @option{-q}
9369 (see below), only the source file names,
9370 without relative paths, are output. If you just specify the
9371 @option{-M}
9372 switch, dependencies of the GNAT internal system files are omitted. This
9373 is typically what you want. If you also specify
9374 the @option{-a} switch,
9375 dependencies of the GNAT internal files are also listed. Note that
9376 dependencies of the objects in external Ada libraries (see switch
9377 @option{-aL}@var{dir} in the following list)
9378 are never reported.
9380 @item -n
9381 @cindex @option{-n} (@command{gnatmake})
9382 Don't compile, bind, or link. Checks if all objects are up to date.
9383 If they are not, the full name of the first file that needs to be
9384 recompiled is printed.
9385 Repeated use of this option, followed by compiling the indicated source
9386 file, will eventually result in recompiling all required units.
9388 @item -o @var{exec_name}
9389 @cindex @option{-o} (@command{gnatmake})
9390 Output executable name. The name of the final executable program will be
9391 @var{exec_name}. If the @option{-o} switch is omitted the default
9392 name for the executable will be the name of the input file in appropriate form
9393 for an executable file on the host system.
9395 This switch cannot be used when invoking @command{gnatmake} with several
9396 @file{file_names}.
9398 @item -p or --create-missing-dirs
9399 @cindex @option{-p} (@command{gnatmake})
9400 When using project files (-P@var{project}), create
9401 automatically missing object directories, library directories and exec
9402 directories.
9404 @item -P@var{project}
9405 @cindex @option{-P} (@command{gnatmake})
9406 Use project file @var{project}. Only one such switch can be used.
9407 @xref{gnatmake and Project Files}.
9409 @item -q
9410 @cindex @option{-q} (@command{gnatmake})
9411 Quiet. When this flag is not set, the commands carried out by
9412 @command{gnatmake} are displayed.
9414 @item -s
9415 @cindex @option{-s} (@command{gnatmake})
9416 Recompile if compiler switches have changed since last compilation.
9417 All compiler switches but -I and -o are taken into account in the
9418 following way:
9419 orders between different ``first letter'' switches are ignored, but
9420 orders between same switches are taken into account. For example,
9421 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9422 is equivalent to @option{-O -g}.
9424 This switch is recommended when Integrated Preprocessing is used.
9426 @item -u
9427 @cindex @option{-u} (@command{gnatmake})
9428 Unique. Recompile at most the main files. It implies -c. Combined with
9429 -f, it is equivalent to calling the compiler directly. Note that using
9430 -u with a project file and no main has a special meaning
9431 (@pxref{Project Files and Main Subprograms}).
9433 @item -U
9434 @cindex @option{-U} (@command{gnatmake})
9435 When used without a project file or with one or several mains on the command
9436 line, is equivalent to -u. When used with a project file and no main
9437 on the command line, all sources of all project files are checked and compiled
9438 if not up to date, and libraries are rebuilt, if necessary.
9440 @item -v
9441 @cindex @option{-v} (@command{gnatmake})
9442 Verbose. Display the reason for all recompilations @command{gnatmake}
9443 decides are necessary, with the highest verbosity level.
9445 @item -vl
9446 @cindex @option{-vl} (@command{gnatmake})
9447 Verbosity level Low. Display fewer lines than in verbosity Medium.
9449 @item -vm
9450 @cindex @option{-vm} (@command{gnatmake})
9451 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9453 @item -vh
9454 @cindex @option{-vm} (@command{gnatmake})
9455 Verbosity level High. Equivalent to -v.
9457 @item -vP@emph{x}
9458 Indicate the verbosity of the parsing of GNAT project files.
9459 @xref{Switches Related to Project Files}.
9461 @item -x
9462 @cindex @option{-x} (@command{gnatmake})
9463 Indicate that sources that are not part of any Project File may be compiled.
9464 Normally, when using Project Files, only sources that are part of a Project
9465 File may be compile. When this switch is used, a source outside of all Project
9466 Files may be compiled. The ALI file and the object file will be put in the
9467 object directory of the main Project. The compilation switches used will only
9468 be those specified on the command line. Even when
9469 @option{-x} is used, mains specified on the
9470 command line need to be sources of a project file.
9472 @item -X@var{name=value}
9473 Indicate that external variable @var{name} has the value @var{value}.
9474 The Project Manager will use this value for occurrences of
9475 @code{external(name)} when parsing the project file.
9476 @xref{Switches Related to Project Files}.
9478 @item -z
9479 @cindex @option{-z} (@command{gnatmake})
9480 No main subprogram. Bind and link the program even if the unit name
9481 given on the command line is a package name. The resulting executable
9482 will execute the elaboration routines of the package and its closure,
9483 then the finalization routines.
9485 @end table
9487 @table @asis
9488 @item @command{gcc} @asis{switches}
9489 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9490 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9491 @end table
9493 @noindent
9494 Source and library search path switches:
9496 @table @option
9497 @c !sort!
9498 @item -aI@var{dir}
9499 @cindex @option{-aI} (@command{gnatmake})
9500 When looking for source files also look in directory @var{dir}.
9501 The order in which source files search is undertaken is
9502 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9504 @item -aL@var{dir}
9505 @cindex @option{-aL} (@command{gnatmake})
9506 Consider @var{dir} as being an externally provided Ada library.
9507 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9508 files have been located in directory @var{dir}. This allows you to have
9509 missing bodies for the units in @var{dir} and to ignore out of date bodies
9510 for the same units. You still need to specify
9511 the location of the specs for these units by using the switches
9512 @option{-aI@var{dir}}
9513 or @option{-I@var{dir}}.
9514 Note: this switch is provided for compatibility with previous versions
9515 of @command{gnatmake}. The easier method of causing standard libraries
9516 to be excluded from consideration is to write-protect the corresponding
9517 ALI files.
9519 @item -aO@var{dir}
9520 @cindex @option{-aO} (@command{gnatmake})
9521 When searching for library and object files, look in directory
9522 @var{dir}. The order in which library files are searched is described in
9523 @ref{Search Paths for gnatbind}.
9525 @item -A@var{dir}
9526 @cindex Search paths, for @command{gnatmake}
9527 @cindex @option{-A} (@command{gnatmake})
9528 Equivalent to @option{-aL@var{dir}
9529 -aI@var{dir}}.
9531 @item -I@var{dir}
9532 @cindex @option{-I} (@command{gnatmake})
9533 Equivalent to @option{-aO@var{dir}
9534 -aI@var{dir}}.
9536 @item -I-
9537 @cindex @option{-I-} (@command{gnatmake})
9538 @cindex Source files, suppressing search
9539 Do not look for source files in the directory containing the source
9540 file named in the command line.
9541 Do not look for ALI or object files in the directory
9542 where @command{gnatmake} was invoked.
9544 @item -L@var{dir}
9545 @cindex @option{-L} (@command{gnatmake})
9546 @cindex Linker libraries
9547 Add directory @var{dir} to the list of directories in which the linker
9548 will search for libraries. This is equivalent to
9549 @option{-largs -L}@var{dir}.
9550 Furthermore, under Windows, the sources pointed to by the libraries path
9551 set in the registry are not searched for.
9553 @item -nostdinc
9554 @cindex @option{-nostdinc} (@command{gnatmake})
9555 Do not look for source files in the system default directory.
9557 @item -nostdlib
9558 @cindex @option{-nostdlib} (@command{gnatmake})
9559 Do not look for library files in the system default directory.
9561 @item --RTS=@var{rts-path}
9562 @cindex @option{--RTS} (@command{gnatmake})
9563 Specifies the default location of the runtime library. GNAT looks for the
9564 runtime
9565 in the following directories, and stops as soon as a valid runtime is found
9566 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9567 @file{ada_object_path} present):
9569 @itemize @bullet
9570 @item <current directory>/$rts_path
9572 @item <default-search-dir>/$rts_path
9574 @item <default-search-dir>/rts-$rts_path
9575 @end itemize
9577 @noindent
9578 The selected path is handled like a normal RTS path.
9580 @end table
9582 @node Mode Switches for gnatmake
9583 @section Mode Switches for @command{gnatmake}
9585 @noindent
9586 The mode switches (referred to as @code{mode_switches}) allow the
9587 inclusion of switches that are to be passed to the compiler itself, the
9588 binder or the linker. The effect of a mode switch is to cause all
9589 subsequent switches up to the end of the switch list, or up to the next
9590 mode switch, to be interpreted as switches to be passed on to the
9591 designated component of GNAT.
9593 @table @option
9594 @c !sort!
9595 @item -cargs @var{switches}
9596 @cindex @option{-cargs} (@command{gnatmake})
9597 Compiler switches. Here @var{switches} is a list of switches
9598 that are valid switches for @command{gcc}. They will be passed on to
9599 all compile steps performed by @command{gnatmake}.
9601 @item -bargs @var{switches}
9602 @cindex @option{-bargs} (@command{gnatmake})
9603 Binder switches. Here @var{switches} is a list of switches
9604 that are valid switches for @code{gnatbind}. They will be passed on to
9605 all bind steps performed by @command{gnatmake}.
9607 @item -largs @var{switches}
9608 @cindex @option{-largs} (@command{gnatmake})
9609 Linker switches. Here @var{switches} is a list of switches
9610 that are valid switches for @command{gnatlink}. They will be passed on to
9611 all link steps performed by @command{gnatmake}.
9613 @item -margs @var{switches}
9614 @cindex @option{-margs} (@command{gnatmake})
9615 Make switches. The switches are directly interpreted by @command{gnatmake},
9616 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9617 or @option{-largs}.
9618 @end table
9620 @node Notes on the Command Line
9621 @section Notes on the Command Line
9623 @noindent
9624 This section contains some additional useful notes on the operation
9625 of the @command{gnatmake} command.
9627 @itemize @bullet
9628 @item
9629 @cindex Recompilation, by @command{gnatmake}
9630 If @command{gnatmake} finds no ALI files, it recompiles the main program
9631 and all other units required by the main program.
9632 This means that @command{gnatmake}
9633 can be used for the initial compile, as well as during subsequent steps of
9634 the development cycle.
9636 @item
9637 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9638 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9639 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9640 warning.
9642 @item
9643 In @command{gnatmake} the switch @option{-I}
9644 is used to specify both source and
9645 library file paths. Use @option{-aI}
9646 instead if you just want to specify
9647 source paths only and @option{-aO}
9648 if you want to specify library paths
9649 only.
9651 @item
9652 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9653 This may conveniently be used to exclude standard libraries from
9654 consideration and in particular it means that the use of the
9655 @option{-f} switch will not recompile these files
9656 unless @option{-a} is also specified.
9658 @item
9659 @command{gnatmake} has been designed to make the use of Ada libraries
9660 particularly convenient. Assume you have an Ada library organized
9661 as follows: @i{obj-dir} contains the objects and ALI files for
9662 of your Ada compilation units,
9663 whereas @i{include-dir} contains the
9664 specs of these units, but no bodies. Then to compile a unit
9665 stored in @code{main.adb}, which uses this Ada library you would just type
9667 @smallexample
9668 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9669 @end smallexample
9671 @item
9672 Using @command{gnatmake} along with the
9673 @option{-m (minimal recompilation)}
9674 switch provides a mechanism for avoiding unnecessary recompilations. Using
9675 this switch,
9676 you can update the comments/format of your
9677 source files without having to recompile everything. Note, however, that
9678 adding or deleting lines in a source files may render its debugging
9679 info obsolete. If the file in question is a spec, the impact is rather
9680 limited, as that debugging info will only be useful during the
9681 elaboration phase of your program. For bodies the impact can be more
9682 significant. In all events, your debugger will warn you if a source file
9683 is more recent than the corresponding object, and alert you to the fact
9684 that the debugging information may be out of date.
9685 @end itemize
9687 @node How gnatmake Works
9688 @section How @command{gnatmake} Works
9690 @noindent
9691 Generally @command{gnatmake} automatically performs all necessary
9692 recompilations and you don't need to worry about how it works. However,
9693 it may be useful to have some basic understanding of the @command{gnatmake}
9694 approach and in particular to understand how it uses the results of
9695 previous compilations without incorrectly depending on them.
9697 First a definition: an object file is considered @dfn{up to date} if the
9698 corresponding ALI file exists and if all the source files listed in the
9699 dependency section of this ALI file have time stamps matching those in
9700 the ALI file. This means that neither the source file itself nor any
9701 files that it depends on have been modified, and hence there is no need
9702 to recompile this file.
9704 @command{gnatmake} works by first checking if the specified main unit is up
9705 to date. If so, no compilations are required for the main unit. If not,
9706 @command{gnatmake} compiles the main program to build a new ALI file that
9707 reflects the latest sources. Then the ALI file of the main unit is
9708 examined to find all the source files on which the main program depends,
9709 and @command{gnatmake} recursively applies the above procedure on all these
9710 files.
9712 This process ensures that @command{gnatmake} only trusts the dependencies
9713 in an existing ALI file if they are known to be correct. Otherwise it
9714 always recompiles to determine a new, guaranteed accurate set of
9715 dependencies. As a result the program is compiled ``upside down'' from what may
9716 be more familiar as the required order of compilation in some other Ada
9717 systems. In particular, clients are compiled before the units on which
9718 they depend. The ability of GNAT to compile in any order is critical in
9719 allowing an order of compilation to be chosen that guarantees that
9720 @command{gnatmake} will recompute a correct set of new dependencies if
9721 necessary.
9723 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9724 imported by several of the executables, it will be recompiled at most once.
9726 Note: when using non-standard naming conventions
9727 (@pxref{Using Other File Names}), changing through a configuration pragmas
9728 file the version of a source and invoking @command{gnatmake} to recompile may
9729 have no effect, if the previous version of the source is still accessible
9730 by @command{gnatmake}. It may be necessary to use the switch
9733 @node Examples of gnatmake Usage
9734 @section Examples of @command{gnatmake} Usage
9736 @table @code
9737 @item gnatmake hello.adb
9738 Compile all files necessary to bind and link the main program
9739 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9740 resulting object files to generate an executable file @file{hello}.
9742 @item gnatmake main1 main2 main3
9743 Compile all files necessary to bind and link the main programs
9744 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9745 (containing unit @code{Main2}) and @file{main3.adb}
9746 (containing unit @code{Main3}) and bind and link the resulting object files
9747 to generate three executable files @file{main1},
9748 @file{main2}
9749 and @file{main3}.
9751 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9753 Compile all files necessary to bind and link the main program unit
9754 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9755 be done with optimization level 2 and the order of elaboration will be
9756 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9757 displaying commands it is executing.
9758 @end table
9760 @c *************************
9761 @node Improving Performance
9762 @chapter Improving Performance
9763 @cindex Improving performance
9765 @noindent
9766 This chapter presents several topics related to program performance.
9767 It first describes some of the tradeoffs that need to be considered
9768 and some of the techniques for making your program run faster.
9769 It then documents
9770 @ifclear FSFEDITION
9771 the @command{gnatelim} tool and
9772 @end ifclear
9773 unused subprogram/data
9774 elimination feature, which can reduce the size of program executables.
9776 @ifnottex
9777 @menu
9778 * Performance Considerations::
9779 * Text_IO Suggestions::
9780 @ifclear FSFEDITION
9781 * Reducing Size of Ada Executables with gnatelim::
9782 @end ifclear
9783 * Reducing Size of Executables with unused subprogram/data elimination::
9784 @end menu
9785 @end ifnottex
9787 @c *****************************
9788 @node Performance Considerations
9789 @section Performance Considerations
9791 @noindent
9792 The GNAT system provides a number of options that allow a trade-off
9793 between
9795 @itemize @bullet
9796 @item
9797 performance of the generated code
9799 @item
9800 speed of compilation
9802 @item
9803 minimization of dependences and recompilation
9805 @item
9806 the degree of run-time checking.
9807 @end itemize
9809 @noindent
9810 The defaults (if no options are selected) aim at improving the speed
9811 of compilation and minimizing dependences, at the expense of performance
9812 of the generated code:
9814 @itemize @bullet
9815 @item
9816 no optimization
9818 @item
9819 no inlining of subprogram calls
9821 @item
9822 all run-time checks enabled except overflow and elaboration checks
9823 @end itemize
9825 @noindent
9826 These options are suitable for most program development purposes. This
9827 chapter describes how you can modify these choices, and also provides
9828 some guidelines on debugging optimized code.
9830 @menu
9831 * Controlling Run-Time Checks::
9832 * Use of Restrictions::
9833 * Optimization Levels::
9834 * Debugging Optimized Code::
9835 * Inlining of Subprograms::
9836 * Vectorization of loops::
9837 * Other Optimization Switches::
9838 * Optimization and Strict Aliasing::
9839 * Aliased Variables and Optimization::
9840 * Atomic Variables and Optimization::
9841 * Passive Task Optimization::
9843 @end menu
9845 @node Controlling Run-Time Checks
9846 @subsection Controlling Run-Time Checks
9848 @noindent
9849 By default, GNAT generates all run-time checks, except integer overflow
9850 checks, stack overflow checks, and checks for access before elaboration on
9851 subprogram calls. The latter are not required in default mode, because all
9852 necessary checking is done at compile time.
9853 @cindex @option{-gnatp} (@command{gcc})
9854 @cindex @option{-gnato} (@command{gcc})
9855 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9856 be modified. @xref{Run-Time Checks}.
9858 Our experience is that the default is suitable for most development
9859 purposes.
9861 We treat integer overflow specially because these
9862 are quite expensive and in our experience are not as important as other
9863 run-time checks in the development process. Note that division by zero
9864 is not considered an overflow check, and divide by zero checks are
9865 generated where required by default.
9867 Elaboration checks are off by default, and also not needed by default, since
9868 GNAT uses a static elaboration analysis approach that avoids the need for
9869 run-time checking. This manual contains a full chapter discussing the issue
9870 of elaboration checks, and if the default is not satisfactory for your use,
9871 you should read this chapter.
9873 For validity checks, the minimal checks required by the Ada Reference
9874 Manual (for case statements and assignments to array elements) are on
9875 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9876 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9877 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9878 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9879 are also suppressed entirely if @option{-gnatp} is used.
9881 @cindex Overflow checks
9882 @cindex Checks, overflow
9883 @findex Suppress
9884 @findex Unsuppress
9885 @cindex pragma Suppress
9886 @cindex pragma Unsuppress
9887 Note that the setting of the switches controls the default setting of
9888 the checks. They may be modified using either @code{pragma Suppress} (to
9889 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9890 checks) in the program source.
9892 @node Use of Restrictions
9893 @subsection Use of Restrictions
9895 @noindent
9896 The use of pragma Restrictions allows you to control which features are
9897 permitted in your program. Apart from the obvious point that if you avoid
9898 relatively expensive features like finalization (enforceable by the use
9899 of pragma Restrictions (No_Finalization), the use of this pragma does not
9900 affect the generated code in most cases.
9902 One notable exception to this rule is that the possibility of task abort
9903 results in some distributed overhead, particularly if finalization or
9904 exception handlers are used. The reason is that certain sections of code
9905 have to be marked as non-abortable.
9907 If you use neither the @code{abort} statement, nor asynchronous transfer
9908 of control (@code{select @dots{} then abort}), then this distributed overhead
9909 is removed, which may have a general positive effect in improving
9910 overall performance.  Especially code involving frequent use of tasking
9911 constructs and controlled types will show much improved performance.
9912 The relevant restrictions pragmas are
9914 @smallexample @c ada
9915    @b{pragma} Restrictions (No_Abort_Statements);
9916    @b{pragma} Restrictions (Max_Asynchronous_Select_Nesting => 0);
9917 @end smallexample
9919 @noindent
9920 It is recommended that these restriction pragmas be used if possible. Note
9921 that this also means that you can write code without worrying about the
9922 possibility of an immediate abort at any point.
9924 @node Optimization Levels
9925 @subsection Optimization Levels
9926 @cindex @option{-O} (@command{gcc})
9928 @noindent
9929 Without any optimization option,
9930 the compiler's goal is to reduce the cost of
9931 compilation and to make debugging produce the expected results.
9932 Statements are independent: if you stop the program with a breakpoint between
9933 statements, you can then assign a new value to any variable or change
9934 the program counter to any other statement in the subprogram and get exactly
9935 the results you would expect from the source code.
9937 Turning on optimization makes the compiler attempt to improve the
9938 performance and/or code size at the expense of compilation time and
9939 possibly the ability to debug the program.
9941 If you use multiple
9942 -O options, with or without level numbers,
9943 the last such option is the one that is effective.
9945 @noindent
9946 The default is optimization off. This results in the fastest compile
9947 times, but GNAT makes absolutely no attempt to optimize, and the
9948 generated programs are considerably larger and slower than when
9949 optimization is enabled. You can use the
9950 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9951 @option{-O2}, @option{-O3}, and @option{-Os})
9952 to @command{gcc} to control the optimization level:
9954 @table @option
9955 @item -O0
9956 No optimization (the default);
9957 generates unoptimized code but has
9958 the fastest compilation time.
9960 Note that many other compilers do fairly extensive optimization
9961 even if ``no optimization'' is specified. With gcc, it is
9962 very unusual to use -O0 for production if
9963 execution time is of any concern, since -O0
9964 really does mean no optimization at all. This difference between
9965 gcc and other compilers should be kept in mind when doing
9966 performance comparisons.
9968 @item -O1
9969 Moderate optimization;
9970 optimizes reasonably well but does not
9971 degrade compilation time significantly.
9973 @item -O2
9974 Full optimization;
9975 generates highly optimized code and has
9976 the slowest compilation time.
9978 @item -O3
9979 Full optimization as in @option{-O2};
9980 also uses more aggressive automatic inlining of subprograms within a unit
9981 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
9983 @item -Os
9984 Optimize space usage (code and data) of resulting program.
9985 @end table
9987 @noindent
9988 Higher optimization levels perform more global transformations on the
9989 program and apply more expensive analysis algorithms in order to generate
9990 faster and more compact code. The price in compilation time, and the
9991 resulting improvement in execution time,
9992 both depend on the particular application and the hardware environment.
9993 You should experiment to find the best level for your application.
9995 Since the precise set of optimizations done at each level will vary from
9996 release to release (and sometime from target to target), it is best to think
9997 of the optimization settings in general terms.
9998 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
9999 the GNU Compiler Collection (GCC)}, for details about
10000 the @option{-O} settings and a number of @option{-f} options that
10001 individually enable or disable specific optimizations.
10003 Unlike some other compilation systems, @command{gcc} has
10004 been tested extensively at all optimization levels. There are some bugs
10005 which appear only with optimization turned on, but there have also been
10006 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10007 level of optimization does not improve the reliability of the code
10008 generator, which in practice is highly reliable at all optimization
10009 levels.
10011 Note regarding the use of @option{-O3}: The use of this optimization level
10012 is generally discouraged with GNAT, since it often results in larger
10013 executables which may run more slowly. See further discussion of this point
10014 in @ref{Inlining of Subprograms}.
10016 @node Debugging Optimized Code
10017 @subsection Debugging Optimized Code
10018 @cindex Debugging optimized code
10019 @cindex Optimization and debugging
10021 @noindent
10022 Although it is possible to do a reasonable amount of debugging at
10023 nonzero optimization levels,
10024 the higher the level the more likely that
10025 source-level constructs will have been eliminated by optimization.
10026 For example, if a loop is strength-reduced, the loop
10027 control variable may be completely eliminated and thus cannot be
10028 displayed in the debugger.
10029 This can only happen at @option{-O2} or @option{-O3}.
10030 Explicit temporary variables that you code might be eliminated at
10031 level @option{-O1} or higher.
10033 The use of the @option{-g} switch,
10034 @cindex @option{-g} (@command{gcc})
10035 which is needed for source-level debugging,
10036 affects the size of the program executable on disk,
10037 and indeed the debugging information can be quite large.
10038 However, it has no effect on the generated code (and thus does not
10039 degrade performance)
10041 Since the compiler generates debugging tables for a compilation unit before
10042 it performs optimizations, the optimizing transformations may invalidate some
10043 of the debugging data.  You therefore need to anticipate certain
10044 anomalous situations that may arise while debugging optimized code.
10045 These are the most common cases:
10047 @enumerate
10048 @item
10049 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10050 commands show
10051 the PC bouncing back and forth in the code.  This may result from any of
10052 the following optimizations:
10054 @itemize @bullet
10055 @item
10056 @i{Common subexpression elimination:} using a single instance of code for a
10057 quantity that the source computes several times.  As a result you
10058 may not be able to stop on what looks like a statement.
10060 @item
10061 @i{Invariant code motion:} moving an expression that does not change within a
10062 loop, to the beginning of the loop.
10064 @item
10065 @i{Instruction scheduling:} moving instructions so as to
10066 overlap loads and stores (typically) with other code, or in
10067 general to move computations of values closer to their uses. Often
10068 this causes you to pass an assignment statement without the assignment
10069 happening and then later bounce back to the statement when the
10070 value is actually needed.  Placing a breakpoint on a line of code
10071 and then stepping over it may, therefore, not always cause all the
10072 expected side-effects.
10073 @end itemize
10075 @item
10076 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10077 two identical pieces of code are merged and the program counter suddenly
10078 jumps to a statement that is not supposed to be executed, simply because
10079 it (and the code following) translates to the same thing as the code
10080 that @emph{was} supposed to be executed.  This effect is typically seen in
10081 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10082 a @code{break} in a C @code{switch} statement.
10084 @item
10085 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10086 There are various reasons for this effect:
10088 @itemize @bullet
10089 @item
10090 In a subprogram prologue, a parameter may not yet have been moved to its
10091 ``home''.
10093 @item
10094 A variable may be dead, and its register re-used.  This is
10095 probably the most common cause.
10097 @item
10098 As mentioned above, the assignment of a value to a variable may
10099 have been moved.
10101 @item
10102 A variable may be eliminated entirely by value propagation or
10103 other means.  In this case, GCC may incorrectly generate debugging
10104 information for the variable
10105 @end itemize
10107 @noindent
10108 In general, when an unexpected value appears for a local variable or parameter
10109 you should first ascertain if that value was actually computed by
10110 your program, as opposed to being incorrectly reported by the debugger.
10111 Record fields or
10112 array elements in an object designated by an access value
10113 are generally less of a problem, once you have ascertained that the access
10114 value is sensible.
10115 Typically, this means checking variables in the preceding code and in the
10116 calling subprogram to verify that the value observed is explainable from other
10117 values (one must apply the procedure recursively to those
10118 other values); or re-running the code and stopping a little earlier
10119 (perhaps before the call) and stepping to better see how the variable obtained
10120 the value in question; or continuing to step @emph{from} the point of the
10121 strange value to see if code motion had simply moved the variable's
10122 assignments later.
10123 @end enumerate
10125 @noindent
10126 In light of such anomalies, a recommended technique is to use @option{-O0}
10127 early in the software development cycle, when extensive debugging capabilities
10128 are most needed, and then move to @option{-O1} and later @option{-O2} as
10129 the debugger becomes less critical.
10130 Whether to use the @option{-g} switch in the release version is
10131 a release management issue.
10132 Note that if you use @option{-g} you can then use the @command{strip} program
10133 on the resulting executable,
10134 which removes both debugging information and global symbols.
10136 @node Inlining of Subprograms
10137 @subsection Inlining of Subprograms
10139 @noindent
10140 A call to a subprogram in the current unit is inlined if all the
10141 following conditions are met:
10143 @itemize @bullet
10144 @item
10145 The optimization level is at least @option{-O1}.
10147 @item
10148 The called subprogram is suitable for inlining: It must be small enough
10149 and not contain something that @command{gcc} cannot support in inlined
10150 subprograms.
10152 @item
10153 @cindex pragma Inline
10154 @findex Inline
10155 Any one of the following applies: @code{pragma Inline} is applied to the
10156 subprogram and the @option{-gnatn} switch is specified; the
10157 subprogram is local to the unit and called once from within it; the
10158 subprogram is small and optimization level @option{-O2} is specified;
10159 optimization level @option{-O3} is specified.
10160 @end itemize
10162 @noindent
10163 Calls to subprograms in @code{with}'ed units are normally not inlined.
10164 To achieve actual inlining (that is, replacement of the call by the code
10165 in the body of the subprogram), the following conditions must all be true:
10167 @itemize @bullet
10168 @item
10169 The optimization level is at least @option{-O1}.
10171 @item
10172 The called subprogram is suitable for inlining: It must be small enough
10173 and not contain something that @command{gcc} cannot support in inlined
10174 subprograms.
10176 @item
10177 The call appears in a body (not in a package spec).
10179 @item
10180 There is a @code{pragma Inline} for the subprogram.
10182 @item
10183 The @option{-gnatn} switch is used on the command line.
10184 @end itemize
10186 Even if all these conditions are met, it may not be possible for
10187 the compiler to inline the call, due to the length of the body,
10188 or features in the body that make it impossible for the compiler
10189 to do the inlining.
10191 Note that specifying the @option{-gnatn} switch causes additional
10192 compilation dependencies. Consider the following:
10194 @smallexample @c ada
10195 @cartouche
10196 @b{package} R @b{is}
10197    @b{procedure} Q;
10198    @b{pragma} Inline (Q);
10199 @b{end} R;
10200 @b{package} @b{body} R @b{is}
10201    @dots{}
10202 @b{end} R;
10204 @b{with} R;
10205 @b{procedure} Main @b{is}
10206 @b{begin}
10207    @dots{}
10208    R.Q;
10209 @b{end} Main;
10210 @end cartouche
10211 @end smallexample
10213 @noindent
10214 With the default behavior (no @option{-gnatn} switch specified), the
10215 compilation of the @code{Main} procedure depends only on its own source,
10216 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10217 means that editing the body of @code{R} does not require recompiling
10218 @code{Main}.
10220 On the other hand, the call @code{R.Q} is not inlined under these
10221 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10222 is compiled, the call will be inlined if the body of @code{Q} is small
10223 enough, but now @code{Main} depends on the body of @code{R} in
10224 @file{r.adb} as well as on the spec. This means that if this body is edited,
10225 the main program must be recompiled. Note that this extra dependency
10226 occurs whether or not the call is in fact inlined by @command{gcc}.
10228 The use of front end inlining with @option{-gnatN} generates similar
10229 additional dependencies.
10231 @cindex @option{-fno-inline} (@command{gcc})
10232 Note: The @option{-fno-inline} switch
10233 can be used to prevent
10234 all inlining. This switch overrides all other conditions and ensures
10235 that no inlining occurs. The extra dependences resulting from
10236 @option{-gnatn} will still be active, even if
10237 this switch is used to suppress the resulting inlining actions.
10239 @cindex @option{-fno-inline-functions} (@command{gcc})
10240 Note: The @option{-fno-inline-functions} switch can be used to prevent
10241 automatic inlining of subprograms if @option{-O3} is used.
10243 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10244 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10245 automatic inlining of small subprograms if @option{-O2} is used.
10247 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10248 Note: The @option{-fno-inline-functions-called-once} switch
10249 can be used to prevent inlining of subprograms local to the unit
10250 and called once from within it if @option{-O1} is used.
10252 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10253 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10254 specified in lieu of it, @option{-gnatn} being translated into one of them
10255 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10256 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10257 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10258 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10259 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
10260 effect of inlining subprograms you did not think should be inlined. We have
10261 found that the use of @option{-O3} may slow down the compilation and increase
10262 the code size by performing excessive inlining, leading to increased
10263 instruction cache pressure from the increased code size and thus minor
10264 performance improvements. So the bottom line here is that you should not
10265 automatically assume that @option{-O3} is better than @option{-O2}, and
10266 indeed you should use @option{-O3} only if tests show that it actually
10267 improves performance for your program.
10269 @node Vectorization of loops
10270 @subsection Vectorization of loops
10271 @cindex Optimization Switches
10273 You can take advantage of the auto-vectorizer present in the @command{gcc}
10274 back end to vectorize loops with GNAT.  The corresponding command line switch
10275 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10276 and other aggressive optimizations helpful for vectorization also are enabled
10277 by default at this level, using @option{-O3} directly is recommended.
10279 You also need to make sure that the target architecture features a supported
10280 SIMD instruction set.  For example, for the x86 architecture, you should at
10281 least specify @option{-msse2} to get significant vectorization (but you don't
10282 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10283 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10285 The preferred loop form for vectorization is the @code{for} iteration scheme.
10286 Loops with a @code{while} iteration scheme can also be vectorized if they are
10287 very simple, but the vectorizer will quickly give up otherwise.  With either
10288 iteration scheme, the flow of control must be straight, in particular no
10289 @code{exit} statement may appear in the loop body.  The loop may however
10290 contain a single nested loop, if it can be vectorized when considered alone:
10292 @smallexample @c ada
10293 @cartouche
10294    A : @b{array} (1..4, 1..4) @b{of} Long_Float;
10295    S : @b{array} (1..4) @b{of} Long_Float;
10297    @b{procedure} Sum @b{is}
10298    @b{begin}
10299       @b{for} I @b{in} A'Range(1) @b{loop}
10300          @b{for} J @b{in} A'Range(2) @b{loop}
10301             S (I) := S (I) + A (I, J);
10302          @b{end} @b{loop};
10303       @b{end} @b{loop};
10304    @b{end} Sum;
10305 @end cartouche
10306 @end smallexample
10308 The vectorizable operations depend on the targeted SIMD instruction set, but
10309 the adding and some of the multiplying operators are generally supported, as
10310 well as the logical operators for modular types.  Note that, in the former
10311 case, enabling overflow checks, for example with @option{-gnato}, totally
10312 disables vectorization.  The other checks are not supposed to have the same
10313 definitive effect, although compiling with @option{-gnatp} might well reveal
10314 cases where some checks do thwart vectorization.
10316 Type conversions may also prevent vectorization if they involve semantics that
10317 are not directly supported by the code generator or the SIMD instruction set.
10318 A typical example is direct conversion from floating-point to integer types.
10319 The solution in this case is to use the following idiom:
10321 @smallexample @c ada
10322    Integer (S'Truncation (F))
10323 @end smallexample
10325 @noindent
10326 if @code{S} is the subtype of floating-point object @code{F}.
10328 In most cases, the vectorizable loops are loops that iterate over arrays.
10329 All kinds of array types are supported, i.e. constrained array types with
10330 static bounds:
10332 @smallexample @c ada
10333    @b{type} Array_Type @b{is} @b{array} (1 .. 4) @b{of} Long_Float;
10334 @end smallexample
10336 @noindent
10337 constrained array types with dynamic bounds:
10339 @smallexample @c ada
10340    @b{type} Array_Type @b{is} @b{array} (1 .. Q.N) @b{of} Long_Float;
10342    @b{type} Array_Type @b{is} @b{array} (Q.K .. 4) @b{of} Long_Float;
10344    @b{type} Array_Type @b{is} @b{array} (Q.K .. Q.N) @b{of} Long_Float;
10345 @end smallexample
10347 @noindent
10348 or unconstrained array types:
10350 @smallexample @c ada
10351   @b{type} Array_Type @b{is} @b{array} (Positive @b{range} <>) @b{of} Long_Float;
10352 @end smallexample
10354 @noindent
10355 The quality of the generated code decreases when the dynamic aspect of the
10356 array type increases, the worst code being generated for unconstrained array
10357 types.  This is so because, the less information the compiler has about the
10358 bounds of the array, the more fallback code it needs to generate in order to
10359 fix things up at run time.
10361 It is possible to specify that a given loop should be subject to vectorization
10362 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10364 @smallexample @c ada
10365   @b{pragma} Loop_Optimize (Vector);
10366 @end smallexample
10368 @noindent
10369 placed immediately within the loop will convey the appropriate hint to the
10370 compiler for this loop.
10372 It is also possible to help the compiler generate better vectorized code
10373 for a given loop by asserting that there are no loop-carried dependencies
10374 in the loop.  Consider for example the procedure:
10376 @smallexample @c ada
10377   @b{type} Arr @b{is} @b{array} (1 .. 4) @b{of} Long_Float;
10379   @b{procedure} Add (X, Y : @b{not} @b{null} @b{access} Arr; R : @b{not} @b{null} @b{access} Arr) @b{is}
10380   @b{begin}
10381     @b{for} I @b{in} Arr'Range @b{loop}
10382       R(I) := X(I) + Y(I);
10383     @b{end} @b{loop};
10384   @b{end};
10385 @end smallexample
10387 @noindent
10388 By default, the compiler cannot unconditionally vectorize the loop because
10389 assigning to a component of the array designated by R in one iteration could
10390 change the value read from the components of the array designated by X or Y
10391 in a later iteration.  As a result, the compiler will generate two versions
10392 of the loop in the object code, one vectorized and the other not vectorized,
10393 as well as a test to select the appropriate version at run time.  This can
10394 be overcome by another hint:
10396 @smallexample @c ada
10397   @b{pragma} Loop_Optimize (Ivdep);
10398 @end smallexample
10400 @noindent
10401 placed immediately within the loop will tell the compiler that it can safely
10402 omit the non-vectorized version of the loop as well as the run-time test.
10404 @node Other Optimization Switches
10405 @subsection Other Optimization Switches
10406 @cindex Optimization Switches
10408 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10409 @command{gcc} optimization switches are potentially usable. These switches
10410 have not been extensively tested with GNAT but can generally be expected
10411 to work. Examples of switches in this category are @option{-funroll-loops}
10412 and the various target-specific @option{-m} options (in particular, it has
10413 been observed that @option{-march=xxx} can significantly improve performance
10414 on appropriate machines). For full details of these switches, see
10415 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10416 the GNU Compiler Collection (GCC)}.
10418 @node Optimization and Strict Aliasing
10419 @subsection Optimization and Strict Aliasing
10420 @cindex Aliasing
10421 @cindex Strict Aliasing
10422 @cindex No_Strict_Aliasing
10424 @noindent
10425 The strong typing capabilities of Ada allow an optimizer to generate
10426 efficient code in situations where other languages would be forced to
10427 make worst case assumptions preventing such optimizations. Consider
10428 the following example:
10430 @smallexample @c ada
10431 @cartouche
10432 @b{procedure} R @b{is}
10433    @b{type} Int1 @b{is} @b{new} Integer;
10434    @b{type} Int2 @b{is} @b{new} Integer;
10435    @b{type} Int1A @b{is} @b{access} Int1;
10436    @b{type} Int2A @b{is} @b{access} Int2;
10437    Int1V : Int1A;
10438    Int2V : Int2A;
10439    @dots{}
10441 @b{begin}
10442    @dots{}
10443    @b{for} J @b{in} Data'Range @b{loop}
10444       @b{if} Data (J) = Int1V.@b{all} @b{then}
10445          Int2V.@b{all} := Int2V.@b{all} + 1;
10446       @b{end} @b{if};
10447    @b{end} @b{loop};
10448    @dots{}
10449 @b{end} R;
10450 @end cartouche
10451 @end smallexample
10453 @noindent
10454 In this example, since the variable @code{Int1V} can only access objects
10455 of type @code{Int1}, and @code{Int2V} can only access objects of type
10456 @code{Int2}, there is no possibility that the assignment to
10457 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10458 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10459 for all iterations of the loop and avoid the extra memory reference
10460 required to dereference it each time through the loop.
10462 This kind of optimization, called strict aliasing analysis, is
10463 triggered by specifying an optimization level of @option{-O2} or
10464 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10465 when access values are involved.
10467 However, although this optimization is always correct in terms of
10468 the formal semantics of the Ada Reference Manual, difficulties can
10469 arise if features like @code{Unchecked_Conversion} are used to break
10470 the typing system. Consider the following complete program example:
10472 @smallexample @c ada
10473 @cartouche
10474 @b{package} p1 @b{is}
10475    @b{type} int1 @b{is} @b{new} integer;
10476    @b{type} int2 @b{is} @b{new} integer;
10477    @b{type} a1 @b{is} @b{access} int1;
10478    @b{type} a2 @b{is} @b{access} int2;
10479 @b{end} p1;
10481 @b{with} p1; @b{use} p1;
10482 @b{package} p2 @b{is}
10483    @b{function} to_a2 (Input : a1) @b{return} a2;
10484 @b{end} p2;
10486 @b{with} Unchecked_Conversion;
10487 @b{package} @b{body} p2 @b{is}
10488    @b{function} to_a2 (Input : a1) @b{return} a2 @b{is}
10489       @b{function} to_a2u @b{is}
10490         @b{new} Unchecked_Conversion (a1, a2);
10491    @b{begin}
10492       @b{return} to_a2u (Input);
10493    @b{end} to_a2;
10494 @b{end} p2;
10496 @b{with} p2; @b{use} p2;
10497 @b{with} p1; @b{use} p1;
10498 @b{with} Text_IO; @b{use} Text_IO;
10499 @b{procedure} m @b{is}
10500    v1 : a1 := @b{new} int1;
10501    v2 : a2 := to_a2 (v1);
10502 @b{begin}
10503    v1.@b{all} := 1;
10504    v2.@b{all} := 0;
10505    put_line (int1'image (v1.@b{all}));
10506 @b{end};
10507 @end cartouche
10508 @end smallexample
10510 @noindent
10511 This program prints out 0 in @option{-O0} or @option{-O1}
10512 mode, but it prints out 1 in @option{-O2} mode. That's
10513 because in strict aliasing mode, the compiler can and
10514 does assume that the assignment to @code{v2.all} could not
10515 affect the value of @code{v1.all}, since different types
10516 are involved.
10518 This behavior is not a case of non-conformance with the standard, since
10519 the Ada RM specifies that an unchecked conversion where the resulting
10520 bit pattern is not a correct value of the target type can result in an
10521 abnormal value and attempting to reference an abnormal value makes the
10522 execution of a program erroneous.  That's the case here since the result
10523 does not point to an object of type @code{int2}.  This means that the
10524 effect is entirely unpredictable.
10526 However, although that explanation may satisfy a language
10527 lawyer, in practice an applications programmer expects an
10528 unchecked conversion involving pointers to create true
10529 aliases and the behavior of printing 1 seems plain wrong.
10530 In this case, the strict aliasing optimization is unwelcome.
10532 Indeed the compiler recognizes this possibility, and the
10533 unchecked conversion generates a warning:
10535 @smallexample
10536 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10537 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10538 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10539 @end smallexample
10541 @noindent
10542 Unfortunately the problem is recognized when compiling the body of
10543 package @code{p2}, but the actual "bad" code is generated while
10544 compiling the body of @code{m} and this latter compilation does not see
10545 the suspicious @code{Unchecked_Conversion}.
10547 As implied by the warning message, there are approaches you can use to
10548 avoid the unwanted strict aliasing optimization in a case like this.
10550 One possibility is to simply avoid the use of @option{-O2}, but
10551 that is a bit drastic, since it throws away a number of useful
10552 optimizations that do not involve strict aliasing assumptions.
10554 A less drastic approach is to compile the program using the
10555 option @option{-fno-strict-aliasing}. Actually it is only the
10556 unit containing the dereferencing of the suspicious pointer
10557 that needs to be compiled. So in this case, if we compile
10558 unit @code{m} with this switch, then we get the expected
10559 value of zero printed. Analyzing which units might need
10560 the switch can be painful, so a more reasonable approach
10561 is to compile the entire program with options @option{-O2}
10562 and @option{-fno-strict-aliasing}. If the performance is
10563 satisfactory with this combination of options, then the
10564 advantage is that the entire issue of possible "wrong"
10565 optimization due to strict aliasing is avoided.
10567 To avoid the use of compiler switches, the configuration
10568 pragma @code{No_Strict_Aliasing} with no parameters may be
10569 used to specify that for all access types, the strict
10570 aliasing optimization should be suppressed.
10572 However, these approaches are still overkill, in that they causes
10573 all manipulations of all access values to be deoptimized. A more
10574 refined approach is to concentrate attention on the specific
10575 access type identified as problematic.
10577 First, if a careful analysis of uses of the pointer shows
10578 that there are no possible problematic references, then
10579 the warning can be suppressed by bracketing the
10580 instantiation of @code{Unchecked_Conversion} to turn
10581 the warning off:
10583 @smallexample @c ada
10584    @b{pragma} Warnings (Off);
10585    @b{function} to_a2u @b{is}
10586      @b{new} Unchecked_Conversion (a1, a2);
10587    @b{pragma} Warnings (On);
10588 @end smallexample
10590 @noindent
10591 Of course that approach is not appropriate for this particular
10592 example, since indeed there is a problematic reference. In this
10593 case we can take one of two other approaches.
10595 The first possibility is to move the instantiation of unchecked
10596 conversion to the unit in which the type is declared. In
10597 this example, we would move the instantiation of
10598 @code{Unchecked_Conversion} from the body of package
10599 @code{p2} to the spec of package @code{p1}. Now the
10600 warning disappears. That's because any use of the
10601 access type knows there is a suspicious unchecked
10602 conversion, and the strict aliasing optimization
10603 is automatically suppressed for the type.
10605 If it is not practical to move the unchecked conversion to the same unit
10606 in which the destination access type is declared (perhaps because the
10607 source type is not visible in that unit), you may use pragma
10608 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10609 same declarative sequence as the declaration of the access type:
10611 @smallexample @c ada
10612    @b{type} a2 @b{is} @b{access} int2;
10613    @b{pragma} No_Strict_Aliasing (a2);
10614 @end smallexample
10616 @noindent
10617 Here again, the compiler now knows that the strict aliasing optimization
10618 should be suppressed for any reference to type @code{a2} and the
10619 expected behavior is obtained.
10621 Finally, note that although the compiler can generate warnings for
10622 simple cases of unchecked conversions, there are tricker and more
10623 indirect ways of creating type incorrect aliases which the compiler
10624 cannot detect. Examples are the use of address overlays and unchecked
10625 conversions involving composite types containing access types as
10626 components. In such cases, no warnings are generated, but there can
10627 still be aliasing problems. One safe coding practice is to forbid the
10628 use of address clauses for type overlaying, and to allow unchecked
10629 conversion only for primitive types. This is not really a significant
10630 restriction since any possible desired effect can be achieved by
10631 unchecked conversion of access values.
10633 The aliasing analysis done in strict aliasing mode can certainly
10634 have significant benefits. We have seen cases of large scale
10635 application code where the time is increased by up to 5% by turning
10636 this optimization off. If you have code that includes significant
10637 usage of unchecked conversion, you might want to just stick with
10638 @option{-O1} and avoid the entire issue. If you get adequate
10639 performance at this level of optimization level, that's probably
10640 the safest approach. If tests show that you really need higher
10641 levels of optimization, then you can experiment with @option{-O2}
10642 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10643 has on size and speed of the code. If you really need to use
10644 @option{-O2} with strict aliasing in effect, then you should
10645 review any uses of unchecked conversion of access types,
10646 particularly if you are getting the warnings described above.
10648 @node Aliased Variables and Optimization
10649 @subsection Aliased Variables and Optimization
10650 @cindex Aliasing
10651 There are scenarios in which programs may
10652 use low level techniques to modify variables
10653 that otherwise might be considered to be unassigned. For example,
10654 a variable can be passed to a procedure by reference, which takes
10655 the address of the parameter and uses the address to modify the
10656 variable's value, even though it is passed as an IN parameter.
10657 Consider the following example:
10659 @smallexample @c ada
10660 @b{procedure} P @b{is}
10661    Max_Length : @b{constant} Natural := 16;
10662    @b{type} Char_Ptr @b{is} @b{access} @b{all} Character;
10664    @b{procedure} Get_String(Buffer: Char_Ptr; Size : Integer);
10665    @b{pragma} Import (C, Get_String, "get_string");
10667    Name : @b{aliased} String (1 .. Max_Length) := (@b{others} => ' ');
10668    Temp : Char_Ptr;
10670    @b{function} Addr (S : String) @b{return} Char_Ptr @b{is}
10671       @b{function} To_Char_Ptr @b{is}
10672         @b{new} Ada.Unchecked_Conversion (System.Address, Char_Ptr);
10673    @b{begin}
10674       @b{return} To_Char_Ptr (S (S'First)'Address);
10675    @b{end};
10677 @b{begin}
10678    Temp := Addr (Name);
10679    Get_String (Temp, Max_Length);
10680 @b{end};
10681 @end smallexample
10683 @noindent
10684 where Get_String is a C function that uses the address in Temp to
10685 modify the variable @code{Name}. This code is dubious, and arguably
10686 erroneous, and the compiler would be entitled to assume that
10687 @code{Name} is never modified, and generate code accordingly.
10689 However, in practice, this would cause some existing code that
10690 seems to work with no optimization to start failing at high
10691 levels of optimzization.
10693 What the compiler does for such cases is to assume that marking
10694 a variable as aliased indicates that some "funny business" may
10695 be going on. The optimizer recognizes the aliased keyword and
10696 inhibits optimizations that assume the value cannot be assigned.
10697 This means that the above example will in fact "work" reliably,
10698 that is, it will produce the expected results.
10700 @node Atomic Variables and Optimization
10701 @subsection Atomic Variables and Optimization
10702 @cindex Atomic
10703 There are two considerations with regard to performance when
10704 atomic variables are used.
10706 First, the RM only guarantees that access to atomic variables
10707 be atomic, it has nothing to say about how this is achieved,
10708 though there is a strong implication that this should not be
10709 achieved by explicit locking code. Indeed GNAT will never
10710 generate any locking code for atomic variable access (it will
10711 simply reject any attempt to make a variable or type atomic
10712 if the atomic access cannot be achieved without such locking code).
10714 That being said, it is important to understand that you cannot
10715 assume that the entire variable will always be accessed. Consider
10716 this example:
10718 @smallexample @c ada
10719 @b{type} R @b{is} @b{record}
10720    A,B,C,D : Character;
10721 @b{end} @b{record};
10722 @b{for} R'Size @b{use} 32;
10723 @b{for} R'Alignment @b{use} 4;
10725 RV : R;
10726 @b{pragma} Atomic (RV);
10727 X : Character;
10729 X := RV.B;
10730 @end smallexample
10732 @noindent
10733 You cannot assume that the reference to @code{RV.B}
10734 will read the entire 32-bit
10735 variable with a single load instruction. It is perfectly legitimate if
10736 the hardware allows it to do a byte read of just the B field. This read
10737 is still atomic, which is all the RM requires. GNAT can and does take
10738 advantage of this, depending on the architecture and optimization level.
10739 Any assumption to the contrary is non-portable and risky. Even if you
10740 examine the assembly language and see a full 32-bit load, this might
10741 change in a future version of the compiler.
10743 If your application requires that all accesses to @code{RV} in this
10744 example be full 32-bit loads, you need to make a copy for the access
10745 as in:
10747 @smallexample @c ada
10748 @b{declare}
10749    RV_Copy : @b{constant} R := RV;
10750 @b{begin}
10751    X := RV_Copy.B;
10752 @b{end};
10753 @end smallexample
10756 @noindent
10757 Now the reference to RV must read the whole variable.
10758 Actually one can imagine some compiler which figures
10759 out that the whole copy is not required (because only
10760 the B field is actually accessed), but GNAT
10761 certainly won't do that, and we don't know of any
10762 compiler that would not handle this right, and the
10763 above code will in practice work portably across
10764 all architectures (that permit the Atomic declaration).
10766 The second issue with atomic variables has to do with
10767 the possible requirement of generating synchronization
10768 code. For more details on this, consult the sections on
10769 the pragmas Enable/Disable_Atomic_Synchronization in the
10770 GNAT Reference Manual. If performance is critical, and
10771 such synchronization code is not required, it may be
10772 useful to disable it.
10774 @node Passive Task Optimization
10775 @subsection Passive Task Optimization
10776 @cindex Passive Task
10778 A passive task is one which is sufficiently simple that
10779 in theory a compiler could recognize it an implement it
10780 efficiently without creating a new thread. The original design
10781 of Ada 83 had in mind this kind of passive task optimization, but
10782 only a few Ada 83 compilers attempted it. The problem was that
10783 it was difficult to determine the exact conditions under which
10784 the optimization was possible. The result is a very fragile
10785 optimization where a very minor change in the program can
10786 suddenly silently make a task non-optimizable.
10788 With the revisiting of this issue in Ada 95, there was general
10789 agreement that this approach was fundamentally flawed, and the
10790 notion of protected types was introduced. When using protected
10791 types, the restrictions are well defined, and you KNOW that the
10792 operations will be optimized, and furthermore this optimized
10793 performance is fully portable.
10795 Although it would theoretically be possible for GNAT to attempt to
10796 do this optimization, but it really doesn't make sense in the
10797 context of Ada 95, and none of the Ada 95 compilers implement
10798 this optimization as far as we know. In particular GNAT never
10799 attempts to perform this optimization.
10801 In any new Ada 95 code that is written, you should always
10802 use protected types in place of tasks that might be able to
10803 be optimized in this manner.
10804 Of course this does not help if you have legacy Ada 83 code
10805 that depends on this optimization, but it is unusual to encounter
10806 a case where the performance gains from this optimization
10807 are significant.
10809 Your program should work correctly without this optimization. If
10810 you have performance problems, then the most practical
10811 approach is to figure out exactly where these performance problems
10812 arise, and update those particular tasks to be protected types. Note
10813 that typically clients of the tasks who call entries, will not have
10814 to be modified, only the task definition itself.
10818 @node Text_IO Suggestions
10819 @section @code{Text_IO} Suggestions
10820 @cindex @code{Text_IO} and performance
10822 @noindent
10823 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10824 the requirement of maintaining page and line counts. If performance
10825 is critical, a recommendation is to use @code{Stream_IO} instead of
10826 @code{Text_IO} for volume output, since this package has less overhead.
10828 If @code{Text_IO} must be used, note that by default output to the standard
10829 output and standard error files is unbuffered (this provides better
10830 behavior when output statements are used for debugging, or if the
10831 progress of a program is observed by tracking the output, e.g. by
10832 using the Unix @command{tail -f} command to watch redirected output.
10834 If you are generating large volumes of output with @code{Text_IO} and
10835 performance is an important factor, use a designated file instead
10836 of the standard output file, or change the standard output file to
10837 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10840 @ifclear FSFEDITION
10841 @node Reducing Size of Ada Executables with gnatelim
10842 @section Reducing Size of Ada Executables with @code{gnatelim}
10843 @findex gnatelim
10845 @noindent
10846 This section describes @command{gnatelim}, a tool which detects unused
10847 subprograms and helps the compiler to create a smaller executable for your
10848 program.
10850 @menu
10851 * About gnatelim::
10852 * Running gnatelim::
10853 * Processing Precompiled Libraries::
10854 * Correcting the List of Eliminate Pragmas::
10855 * Making Your Executables Smaller::
10856 * Summary of the gnatelim Usage Cycle::
10857 @end menu
10859 @node About gnatelim
10860 @subsection About @code{gnatelim}
10862 @noindent
10863 When a program shares a set of Ada
10864 packages with other programs, it may happen that this program uses
10865 only a fraction of the subprograms defined in these packages. The code
10866 created for these unused subprograms increases the size of the executable.
10868 @code{gnatelim} tracks unused subprograms in an Ada program and
10869 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10870 subprograms that are declared but never called. By placing the list of
10871 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10872 recompiling your program, you may decrease the size of its executable,
10873 because the compiler will not generate the code for 'eliminated' subprograms.
10874 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10875 information about this pragma.
10877 @code{gnatelim} needs as its input data the name of the main subprogram.
10879 If a set of source files is specified as @code{gnatelim} arguments, it
10880 treats these files as a complete set of sources making up a program to
10881 analyse, and analyses only these sources.
10883 After a full successful build of the main subprogram @code{gnatelim} can be
10884 called without  specifying sources to analyse, in this case it computes
10885 the source closure of the main unit from the @file{ALI} files.
10887 If the set of sources to be processed by @code{gnatelim} contains sources with
10888 preprocessing directives
10889 then the needed options should be provided to run preprocessor as a part of
10890 the @command{gnatelim} call, and the generated set of pragmas @code{Eliminate}
10891 will correspond to preprocessed sources.
10893 The following command will create the set of @file{ALI} files needed for
10894 @code{gnatelim}:
10896 @smallexample
10897 $ gnatmake -c Main_Prog
10898 @end smallexample
10900 Note that @code{gnatelim} does not need object files.
10902 @node Running gnatelim
10903 @subsection Running @code{gnatelim}
10905 @noindent
10906 @code{gnatelim} has the following command-line interface:
10908 @smallexample
10909 $ gnatelim [@var{switches}] -main=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10910 @end smallexample
10912 @noindent
10913 @var{main_unit_name} should be a name of a source file that contains the main
10914 subprogram of a program (partition).
10916 Each @var{filename} is the name (including the extension) of a source
10917 file to process. ``Wildcards'' are allowed, and
10918 the file name may contain path information.
10920 @samp{@var{gcc_switches}} is a list of switches for
10921 @command{gcc}. They will be passed on to all compiler invocations made by
10922 @command{gnatelim} to generate the ASIS trees. Here you can provide
10923 @option{-I} switches to form the source search path,
10924 use the @option{-gnatec} switch to set the configuration file,
10925 use the @option{-gnat05} switch if sources should be compiled in
10926 Ada 2005 mode etc.
10928 @code{gnatelim} has the following switches:
10930 @table @option
10931 @c !sort!
10932 @item --version
10933 @cindex @option{--version} @command{gnatelim}
10934 Display Copyright and version, then exit disregarding all other options.
10936 @item --help
10937 @cindex @option{--help} @command{gnatelim}
10938 Display usage, then exit disregarding all other options.
10940 @item -P @var{file}
10941 @cindex @option{-P} @command{gnatelim}
10942 Indicates the name of the project file that describes the set of sources
10943 to be processed.
10945 @item -X@var{name}=@var{value}
10946 @cindex @option{-X} @command{gnatelim}
10947 Indicates that external variable @var{name} in the argument project
10948 has the value @var{value}. Has no effect if no project is specified as
10949 tool argument.
10951 @item --RTS=@var{rts-path}
10952 @cindex @option{--RTS} (@command{gnatelim})
10953 Specifies the default location of the runtime library. Same meaning as the
10954 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
10956 @item -files=@var{filename}
10957 @cindex @option{-files} (@code{gnatelim})
10958 Take the argument source files from the specified file. This file should be an
10959 ordinary text file containing file names separated by spaces or
10960 line breaks. You can use this switch more than once in the same call to
10961 @command{gnatelim}. You also can combine this switch with
10962 an explicit list of files.
10964 @item -log
10965 @cindex @option{-log} (@command{gnatelim})
10966 Duplicate all the output sent to @file{stderr} into a log file. The log file
10967 is named @file{gnatelim.log} and is located in the current directory.
10969 @ignore
10970 @item -log=@var{filename}
10971 @cindex @option{-log} (@command{gnatelim})
10972 Duplicate all the output sent to @file{stderr} into a specified log file.
10973 @end ignore
10975 @cindex @option{--no-elim-dispatch} (@command{gnatelim})
10976 @item --no-elim-dispatch
10977 Do not generate pragmas for dispatching operations.
10979 @item --ignore=@var{filename}
10980 @cindex @option{--ignore} (@command{gnatelim})
10981 Do not generate pragmas for subprograms declared in the sources
10982 listed in a specified file
10984 @cindex @option{-o} (@command{gnatelim})
10985 @item -o=@var{report_file}
10986 Put @command{gnatelim} output into a specified file. If this file already exists,
10987 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10988 into @file{stderr}
10990 @item -j@var{n}
10991 @cindex @option{-j} (@command{gnatelim})
10992 Use @var{n} processes to carry out the tree creations (internal representations
10993 of the argument sources). On a multiprocessor machine this speeds up processing
10994 of big sets of argument sources. If @var{n} is 0, then the maximum number of
10995 parallel tree creations is the number of core processors on the platform.
10997 @item -q
10998 @cindex @option{-q} (@command{gnatelim})
10999 Quiet mode: by default @code{gnatelim} outputs to the standard error
11000 stream the number of program units left to be processed. This option turns
11001 this trace off.
11003 @cindex @option{-t} (@command{gnatelim})
11004 @item -t
11005 Print out execution time.
11007 @item -v
11008 @cindex @option{-v} (@command{gnatelim})
11009 Verbose mode: @code{gnatelim} version information is printed as Ada
11010 comments to the standard output stream. Also, in addition to the number of
11011 program units left @code{gnatelim} will output the name of the current unit
11012 being processed.
11014 @item -wq
11015 @cindex @option{-wq} (@command{gnatelim})
11016 Quiet warning mode - some warnings are suppressed. In particular warnings that
11017 indicate that the analysed set of sources is incomplete to make up a
11018 partition and that some subprogram bodies are missing are not generated.
11019 @end table
11021 @noindent
11022 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11023 driver (see @ref{The GNAT Driver and Project Files}).
11025 @node Processing Precompiled Libraries
11026 @subsection Processing Precompiled Libraries
11028 @noindent
11029 If some program uses a precompiled Ada library, it can be processed by
11030 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11031 Eliminate pragma for a subprogram if the body of this subprogram has not
11032 been analysed, this is a typical case for subprograms from precompiled
11033 libraries. Switch @option{-wq} may be used to suppress
11034 warnings about missing source files and non-analyzed subprogram bodies
11035 that can be generated when processing precompiled Ada libraries.
11037 @node Correcting the List of Eliminate Pragmas
11038 @subsection Correcting the List of Eliminate Pragmas
11040 @noindent
11041 In some rare cases @code{gnatelim} may try to eliminate
11042 subprograms that are actually called in the program. In this case, the
11043 compiler will generate an error message of the form:
11045 @smallexample
11046 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11047 @end smallexample
11049 @noindent
11050 You will need to manually remove the wrong @code{Eliminate} pragmas from
11051 the configuration file indicated in the error message. You should recompile
11052 your program from scratch after that, because you need a consistent
11053 configuration file(s) during the entire compilation.
11055 @node Making Your Executables Smaller
11056 @subsection Making Your Executables Smaller
11058 @noindent
11059 In order to get a smaller executable for your program you now have to
11060 recompile the program completely with the configuration file containing
11061 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11062 @file{gnat.adc} file located in your current directory, just do:
11064 @smallexample
11065 $ gnatmake -f main_prog
11066 @end smallexample
11068 @noindent
11069 (Use the @option{-f} option for @command{gnatmake} to
11070 recompile everything
11071 with the set of pragmas @code{Eliminate} that you have obtained with
11072 @command{gnatelim}).
11074 Be aware that the set of @code{Eliminate} pragmas is specific to each
11075 program. It is not recommended to merge sets of @code{Eliminate}
11076 pragmas created for different programs in one configuration file.
11078 @node Summary of the gnatelim Usage Cycle
11079 @subsection Summary of the @code{gnatelim} Usage Cycle
11081 @noindent
11082 Here is a quick summary of the steps to be taken in order to reduce
11083 the size of your executables with @code{gnatelim}. You may use
11084 other GNAT options to control the optimization level,
11085 to produce the debugging information, to set search path, etc.
11087 @enumerate
11088 @item
11089 Create a complete set of @file{ALI} files (if the program has not been
11090 built already)
11092 @smallexample
11093 $ gnatmake -c main_prog
11094 @end smallexample
11096 @item
11097 Generate a list of @code{Eliminate} pragmas in default configuration file
11098 @file{gnat.adc} in the current directory
11099 @smallexample
11100 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11101 @end smallexample
11103 @item
11104 Recompile the application
11106 @smallexample
11107 $ gnatmake -f main_prog
11108 @end smallexample
11110 @end enumerate
11111 @end ifclear
11113 @node Reducing Size of Executables with unused subprogram/data elimination
11114 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11115 @findex unused subprogram/data elimination
11117 @noindent
11118 This section describes how you can eliminate unused subprograms and data from
11119 your executable just by setting options at compilation time.
11121 @menu
11122 * About unused subprogram/data elimination::
11123 * Compilation options::
11124 * Example of unused subprogram/data elimination::
11125 @end menu
11127 @node About unused subprogram/data elimination
11128 @subsection About unused subprogram/data elimination
11130 @noindent
11131 By default, an executable contains all code and data of its composing objects
11132 (directly linked or coming from statically linked libraries), even data or code
11133 never used by this executable.
11135 This feature will allow you to eliminate such unused code from your
11136 executable, making it smaller (in disk and in memory).
11138 This functionality is available on all Linux platforms except for the IA-64
11139 architecture and on all cross platforms using the ELF binary file format.
11140 In both cases GNU binutils version 2.16 or later are required to enable it.
11142 @node Compilation options
11143 @subsection Compilation options
11145 @noindent
11146 The operation of eliminating the unused code and data from the final executable
11147 is directly performed by the linker.
11149 In order to do this, it has to work with objects compiled with the
11150 following options:
11151 @option{-ffunction-sections} @option{-fdata-sections}.
11152 @cindex @option{-ffunction-sections} (@command{gcc})
11153 @cindex @option{-fdata-sections} (@command{gcc})
11154 These options are usable with C and Ada files.
11155 They will place respectively each
11156 function or data in a separate section in the resulting object file.
11158 Once the objects and static libraries are created with these options, the
11159 linker can perform the dead code elimination. You can do this by setting
11160 the @option{-Wl,--gc-sections} option to gcc command or in the
11161 @option{-largs} section of @command{gnatmake}. This will perform a
11162 garbage collection of code and data never referenced.
11164 If the linker performs a partial link (@option{-r} linker option), then you
11165 will need to provide the entry point using the @option{-e} / @option{--entry}
11166 linker option.
11168 Note that objects compiled without the @option{-ffunction-sections} and
11169 @option{-fdata-sections} options can still be linked with the executable.
11170 However, no dead code elimination will be performed on those objects (they will
11171 be linked as is).
11173 The GNAT static library is now compiled with -ffunction-sections and
11174 -fdata-sections on some platforms. This allows you to eliminate the unused code
11175 and data of the GNAT library from your executable.
11177 @node Example of unused subprogram/data elimination
11178 @subsection Example of unused subprogram/data elimination
11180 @noindent
11181 Here is a simple example:
11183 @smallexample @c ada
11184 @b{with} Aux;
11186 @b{procedure} Test @b{is}
11187 @b{begin}
11188    Aux.Used (10);
11189 @b{end} Test;
11191 @b{package} Aux @b{is}
11192    Used_Data   : Integer;
11193    Unused_Data : Integer;
11195    @b{procedure} Used   (Data : Integer);
11196    @b{procedure} Unused (Data : Integer);
11197 @b{end} Aux;
11199 @b{package} @b{body} Aux @b{is}
11200    @b{procedure} Used (Data : Integer) @b{is}
11201    @b{begin}
11202       Used_Data := Data;
11203    @b{end} Used;
11205    @b{procedure} Unused (Data : Integer) @b{is}
11206    @b{begin}
11207       Unused_Data := Data;
11208    @b{end} Unused;
11209 @b{end} Aux;
11210 @end smallexample
11212 @noindent
11213 @code{Unused} and @code{Unused_Data} are never referenced in this code
11214 excerpt, and hence they may be safely removed from the final executable.
11216 @smallexample
11217 $ gnatmake test
11219 $ nm test | grep used
11220 020015f0 T aux__unused
11221 02005d88 B aux__unused_data
11222 020015cc T aux__used
11223 02005d84 B aux__used_data
11225 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11226      -largs -Wl,--gc-sections
11228 $ nm test | grep used
11229 02005350 T aux__used
11230 0201ffe0 B aux__used_data
11231 @end smallexample
11233 @noindent
11234 It can be observed that the procedure @code{Unused} and the object
11235 @code{Unused_Data} are removed by the linker when using the
11236 appropriate options.
11238 @c ********************************
11239 @node Renaming Files with gnatchop
11240 @chapter Renaming Files with @code{gnatchop}
11241 @findex gnatchop
11243 @noindent
11244 This chapter discusses how to handle files with multiple units by using
11245 the @code{gnatchop} utility. This utility is also useful in renaming
11246 files to meet the standard GNAT default file naming conventions.
11248 @menu
11249 * Handling Files with Multiple Units::
11250 * Operating gnatchop in Compilation Mode::
11251 * Command Line for gnatchop::
11252 * Switches for gnatchop::
11253 * Examples of gnatchop Usage::
11254 @end menu
11256 @node Handling Files with Multiple Units
11257 @section Handling Files with Multiple Units
11259 @noindent
11260 The basic compilation model of GNAT requires that a file submitted to the
11261 compiler have only one unit and there be a strict correspondence
11262 between the file name and the unit name.
11264 The @code{gnatchop} utility allows both of these rules to be relaxed,
11265 allowing GNAT to process files which contain multiple compilation units
11266 and files with arbitrary file names. @code{gnatchop}
11267 reads the specified file and generates one or more output files,
11268 containing one unit per file. The unit and the file name correspond,
11269 as required by GNAT.
11271 If you want to permanently restructure a set of ``foreign'' files so that
11272 they match the GNAT rules, and do the remaining development using the
11273 GNAT structure, you can simply use @command{gnatchop} once, generate the
11274 new set of files and work with them from that point on.
11276 Alternatively, if you want to keep your files in the ``foreign'' format,
11277 perhaps to maintain compatibility with some other Ada compilation
11278 system, you can set up a procedure where you use @command{gnatchop} each
11279 time you compile, regarding the source files that it writes as temporary
11280 files that you throw away.
11282 Note that if your file containing multiple units starts with a byte order
11283 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11284 will each start with a copy of this BOM, meaning that they can be compiled
11285 automatically in UTF-8 mode without needing to specify an explicit encoding.
11287 @node Operating gnatchop in Compilation Mode
11288 @section Operating gnatchop in Compilation Mode
11290 @noindent
11291 The basic function of @code{gnatchop} is to take a file with multiple units
11292 and split it into separate files. The boundary between files is reasonably
11293 clear, except for the issue of comments and pragmas. In default mode, the
11294 rule is that any pragmas between units belong to the previous unit, except
11295 that configuration pragmas always belong to the following unit. Any comments
11296 belong to the following unit. These rules
11297 almost always result in the right choice of
11298 the split point without needing to mark it explicitly and most users will
11299 find this default to be what they want. In this default mode it is incorrect to
11300 submit a file containing only configuration pragmas, or one that ends in
11301 configuration pragmas, to @code{gnatchop}.
11303 However, using a special option to activate ``compilation mode'',
11304 @code{gnatchop}
11305 can perform another function, which is to provide exactly the semantics
11306 required by the RM for handling of configuration pragmas in a compilation.
11307 In the absence of configuration pragmas (at the main file level), this
11308 option has no effect, but it causes such configuration pragmas to be handled
11309 in a quite different manner.
11311 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11312 only configuration pragmas, then this file is appended to the
11313 @file{gnat.adc} file in the current directory. This behavior provides
11314 the required behavior described in the RM for the actions to be taken
11315 on submitting such a file to the compiler, namely that these pragmas
11316 should apply to all subsequent compilations in the same compilation
11317 environment. Using GNAT, the current directory, possibly containing a
11318 @file{gnat.adc} file is the representation
11319 of a compilation environment. For more information on the
11320 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11322 Second, in compilation mode, if @code{gnatchop}
11323 is given a file that starts with
11324 configuration pragmas, and contains one or more units, then these
11325 configuration pragmas are prepended to each of the chopped files. This
11326 behavior provides the required behavior described in the RM for the
11327 actions to be taken on compiling such a file, namely that the pragmas
11328 apply to all units in the compilation, but not to subsequently compiled
11329 units.
11331 Finally, if configuration pragmas appear between units, they are appended
11332 to the previous unit. This results in the previous unit being illegal,
11333 since the compiler does not accept configuration pragmas that follow
11334 a unit. This provides the required RM behavior that forbids configuration
11335 pragmas other than those preceding the first compilation unit of a
11336 compilation.
11338 For most purposes, @code{gnatchop} will be used in default mode. The
11339 compilation mode described above is used only if you need exactly
11340 accurate behavior with respect to compilations, and you have files
11341 that contain multiple units and configuration pragmas. In this
11342 circumstance the use of @code{gnatchop} with the compilation mode
11343 switch provides the required behavior, and is for example the mode
11344 in which GNAT processes the ACVC tests.
11346 @node Command Line for gnatchop
11347 @section Command Line for @code{gnatchop}
11349 @noindent
11350 The @code{gnatchop} command has the form:
11352 @smallexample
11353 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11354 @c      @ovar{directory}
11355 @c Expanding @ovar macro inline (explanation in macro def comments)
11356 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11357       @r{[}@var{directory}@r{]}
11358 @end smallexample
11360 @noindent
11361 The only required argument is the file name of the file to be chopped.
11362 There are no restrictions on the form of this file name. The file itself
11363 contains one or more Ada units, in normal GNAT format, concatenated
11364 together. As shown, more than one file may be presented to be chopped.
11366 When run in default mode, @code{gnatchop} generates one output file in
11367 the current directory for each unit in each of the files.
11369 @var{directory}, if specified, gives the name of the directory to which
11370 the output files will be written. If it is not specified, all files are
11371 written to the current directory.
11373 For example, given a
11374 file called @file{hellofiles} containing
11376 @smallexample @c ada
11377 @group
11378 @cartouche
11379 @b{procedure} hello;
11381 @b{with} Text_IO; @b{use} Text_IO;
11382 @b{procedure} hello @b{is}
11383 @b{begin}
11384    Put_Line ("Hello");
11385 @b{end} hello;
11386 @end cartouche
11387 @end group
11388 @end smallexample
11390 @noindent
11391 the command
11393 @smallexample
11394 $ gnatchop hellofiles
11395 @end smallexample
11397 @noindent
11398 generates two files in the current directory, one called
11399 @file{hello.ads} containing the single line that is the procedure spec,
11400 and the other called @file{hello.adb} containing the remaining text. The
11401 original file is not affected. The generated files can be compiled in
11402 the normal manner.
11404 @noindent
11405 When gnatchop is invoked on a file that is empty or that contains only empty
11406 lines and/or comments, gnatchop will not fail, but will not produce any
11407 new sources.
11409 For example, given a
11410 file called @file{toto.txt} containing
11412 @smallexample @c ada
11413 @group
11414 @cartouche
11415 --@i{  Just a comment}
11416 @end cartouche
11417 @end group
11418 @end smallexample
11420 @noindent
11421 the command
11423 @smallexample
11424 $ gnatchop toto.txt
11425 @end smallexample
11427 @noindent
11428 will not produce any new file and will result in the following warnings:
11430 @smallexample
11431 toto.txt:1:01: warning: empty file, contains no compilation units
11432 no compilation units found
11433 no source files written
11434 @end smallexample
11436 @node Switches for gnatchop
11437 @section Switches for @code{gnatchop}
11439 @noindent
11440 @command{gnatchop} recognizes the following switches:
11442 @table @option
11443 @c !sort!
11445 @item --version
11446 @cindex @option{--version} @command{gnatchop}
11447 Display Copyright and version, then exit disregarding all other options.
11449 @item --help
11450 @cindex @option{--help} @command{gnatchop}
11451 If @option{--version} was not used, display usage, then exit disregarding
11452 all other options.
11454 @item -c
11455 @cindex @option{-c} (@code{gnatchop})
11456 Causes @code{gnatchop} to operate in compilation mode, in which
11457 configuration pragmas are handled according to strict RM rules. See
11458 previous section for a full description of this mode.
11460 @item -gnat@var{xxx}
11461 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11462 used to parse the given file. Not all @var{xxx} options make sense,
11463 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11464 process a source file that uses Latin-2 coding for identifiers.
11466 @item -h
11467 Causes @code{gnatchop} to generate a brief help summary to the standard
11468 output file showing usage information.
11470 @item -k@var{mm}
11471 @cindex @option{-k} (@code{gnatchop})
11472 Limit generated file names to the specified number @code{mm}
11473 of characters.
11474 This is useful if the
11475 resulting set of files is required to be interoperable with systems
11476 which limit the length of file names.
11477 No space is allowed between the @option{-k} and the numeric value. The numeric
11478 value may be omitted in which case a default of @option{-k8},
11479 suitable for use
11480 with DOS-like file systems, is used. If no @option{-k} switch
11481 is present then
11482 there is no limit on the length of file names.
11484 @item -p
11485 @cindex @option{-p} (@code{gnatchop})
11486 Causes the file modification time stamp of the input file to be
11487 preserved and used for the time stamp of the output file(s). This may be
11488 useful for preserving coherency of time stamps in an environment where
11489 @code{gnatchop} is used as part of a standard build process.
11491 @item -q
11492 @cindex @option{-q} (@code{gnatchop})
11493 Causes output of informational messages indicating the set of generated
11494 files to be suppressed. Warnings and error messages are unaffected.
11496 @item -r
11497 @cindex @option{-r} (@code{gnatchop})
11498 @findex Source_Reference
11499 Generate @code{Source_Reference} pragmas. Use this switch if the output
11500 files are regarded as temporary and development is to be done in terms
11501 of the original unchopped file. This switch causes
11502 @code{Source_Reference} pragmas to be inserted into each of the
11503 generated files to refers back to the original file name and line number.
11504 The result is that all error messages refer back to the original
11505 unchopped file.
11506 In addition, the debugging information placed into the object file (when
11507 the @option{-g} switch of @command{gcc} or @command{gnatmake} is
11508 specified)
11509 also refers back to this original file so that tools like profilers and
11510 debuggers will give information in terms of the original unchopped file.
11512 If the original file to be chopped itself contains
11513 a @code{Source_Reference}
11514 pragma referencing a third file, then gnatchop respects
11515 this pragma, and the generated @code{Source_Reference} pragmas
11516 in the chopped file refer to the original file, with appropriate
11517 line numbers. This is particularly useful when @code{gnatchop}
11518 is used in conjunction with @code{gnatprep} to compile files that
11519 contain preprocessing statements and multiple units.
11521 @item -v
11522 @cindex @option{-v} (@code{gnatchop})
11523 Causes @code{gnatchop} to operate in verbose mode. The version
11524 number and copyright notice are output, as well as exact copies of
11525 the gnat1 commands spawned to obtain the chop control information.
11527 @item -w
11528 @cindex @option{-w} (@code{gnatchop})
11529 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11530 fatal error if there is already a file with the same name as a
11531 file it would otherwise output, in other words if the files to be
11532 chopped contain duplicated units. This switch bypasses this
11533 check, and causes all but the last instance of such duplicated
11534 units to be skipped.
11536 @item --GCC=@var{xxxx}
11537 @cindex @option{--GCC=} (@code{gnatchop})
11538 Specify the path of the GNAT parser to be used. When this switch is used,
11539 no attempt is made to add the prefix to the GNAT parser executable.
11540 @end table
11542 @node Examples of gnatchop Usage
11543 @section Examples of @code{gnatchop} Usage
11545 @table @code
11546 @item gnatchop -w hello_s.ada prerelease/files
11548 Chops the source file @file{hello_s.ada}. The output files will be
11549 placed in the directory @file{prerelease/files},
11550 overwriting any
11551 files with matching names in that directory (no files in the current
11552 directory are modified).
11554 @item gnatchop archive
11555 Chops the source file @file{archive}
11556 into the current directory. One
11557 useful application of @code{gnatchop} is in sending sets of sources
11558 around, for example in email messages. The required sources are simply
11559 concatenated (for example, using a Unix @code{cat}
11560 command), and then
11561 @command{gnatchop} is used at the other end to reconstitute the original
11562 file names.
11564 @item gnatchop file1 file2 file3 direc
11565 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11566 the resulting files in the directory @file{direc}. Note that if any units
11567 occur more than once anywhere within this set of files, an error message
11568 is generated, and no files are written. To override this check, use the
11569 @option{-w} switch,
11570 in which case the last occurrence in the last file will
11571 be the one that is output, and earlier duplicate occurrences for a given
11572 unit will be skipped.
11573 @end table
11575 @node Configuration Pragmas
11576 @chapter Configuration Pragmas
11577 @cindex Configuration pragmas
11578 @cindex Pragmas, configuration
11580 @menu
11581 * Handling of Configuration Pragmas::
11582 * The Configuration Pragmas Files::
11583 @end menu
11585 @noindent
11586 Configuration pragmas include those pragmas described as
11587 such in the Ada Reference Manual, as well as
11588 implementation-dependent pragmas that are configuration pragmas.
11589 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11590 for details on these additional GNAT-specific configuration pragmas.
11591 Most notably, the pragma @code{Source_File_Name}, which allows
11592 specifying non-default names for source files, is a configuration
11593 pragma. The following is a complete list of configuration pragmas
11594 recognized by GNAT:
11596 @smallexample
11597    Ada_83
11598    Ada_95
11599    Ada_05
11600    Ada_2005
11601    Ada_12
11602    Ada_2012
11603    Allow_Integer_Address
11604    Annotate
11605    Assertion_Policy
11606    Assume_No_Invalid_Values
11607    C_Pass_By_Copy
11608    Check_Name
11609    Check_Policy
11610    Compile_Time_Error
11611    Compile_Time_Warning
11612    Compiler_Unit
11613    Component_Alignment
11614    Convention_Identifier
11615    Debug_Policy
11616    Detect_Blocking
11617    Default_Storage_Pool
11618    Discard_Names
11619    Elaboration_Checks
11620    Eliminate
11621    Extend_System
11622    Extensions_Allowed
11623    External_Name_Casing
11624    Fast_Math
11625    Favor_Top_Level
11626    Float_Representation
11627    Implicit_Packing
11628    Initialize_Scalars
11629    Interrupt_State
11630    License
11631    Locking_Policy
11632    Long_Float
11633    No_Run_Time
11634    No_Strict_Aliasing
11635    Normalize_Scalars
11636    Optimize_Alignment
11637    Persistent_BSS
11638    Polling
11639    Priority_Specific_Dispatching
11640    Profile
11641    Profile_Warnings
11642    Propagate_Exceptions
11643    Queuing_Policy
11644    Ravenscar
11645    Restricted_Run_Time
11646    Restrictions
11647    Restrictions_Warnings
11648    Reviewable
11649    Short_Circuit_And_Or
11650    Source_File_Name
11651    Source_File_Name_Project
11652    SPARK_Mode
11653    Style_Checks
11654    Suppress
11655    Suppress_Exception_Locations
11656    Task_Dispatching_Policy
11657    Universal_Data
11658    Unsuppress
11659    Use_VADS_Size
11660    Validity_Checks
11661    Warnings
11662    Wide_Character_Encoding
11663 @end smallexample
11665 @node Handling of Configuration Pragmas
11666 @section Handling of Configuration Pragmas
11668 Configuration pragmas may either appear at the start of a compilation
11669 unit, or they can appear in a configuration pragma file to apply to
11670 all compilations performed in a given compilation environment.
11672 GNAT also provides the @code{gnatchop} utility to provide an automatic
11673 way to handle configuration pragmas following the semantics for
11674 compilations (that is, files with multiple units), described in the RM.
11675 See @ref{Operating gnatchop in Compilation Mode} for details.
11676 However, for most purposes, it will be more convenient to edit the
11677 @file{gnat.adc} file that contains configuration pragmas directly,
11678 as described in the following section.
11680 In the case of @code{Restrictions} pragmas appearing as configuration
11681 pragmas in individual compilation units, the exact handling depends on
11682 the type of restriction.
11684 Restrictions that require partition-wide consistency (like
11685 @code{No_Tasking}) are
11686 recognized wherever they appear
11687 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11688 unit. This makes sense since the binder will in any case insist on seeing
11689 consistent use, so any unit not conforming to any restrictions that are
11690 anywhere in the partition will be rejected, and you might as well find
11691 that out at compile time rather than at bind time.
11693 For restrictions that do not require partition-wide consistency, e.g.
11694 SPARK or No_Implementation_Attributes, in general the restriction applies
11695 only to the unit in which the pragma appears, and not to any other units.
11697 The exception is No_Elaboration_Code which always applies to the entire
11698 object file from a compilation, i.e. to the body, spec, and all subunits.
11699 This restriction can be specified in a configuration pragma file, or it
11700 can be on the body and/or the spec (in eithe case it applies to all the
11701 relevant units). It can appear on a subunit only if it has previously
11702 appeared in the body of spec.
11704 @node The Configuration Pragmas Files
11705 @section The Configuration Pragmas Files
11706 @cindex @file{gnat.adc}
11708 @noindent
11709 In GNAT a compilation environment is defined by the current
11710 directory at the time that a compile command is given. This current
11711 directory is searched for a file whose name is @file{gnat.adc}. If
11712 this file is present, it is expected to contain one or more
11713 configuration pragmas that will be applied to the current compilation.
11714 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11715 considered. When taken into account, @file{gnat.adc} is added to the
11716 dependencies, so that if @file{gnat.adc} is modified later, an invocation of
11717 @command{gnatmake} will recompile the source.
11719 Configuration pragmas may be entered into the @file{gnat.adc} file
11720 either by running @code{gnatchop} on a source file that consists only of
11721 configuration pragmas, or more conveniently by direct editing of the
11722 @file{gnat.adc} file, which is a standard format source file.
11724 In addition to @file{gnat.adc}, additional files containing configuration
11725 pragmas may be applied to the current compilation using the switch
11726 @option{-gnatec=}@var{path}. @var{path} must designate an existing file that
11727 contains only configuration pragmas. These configuration pragmas are
11728 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11729 is present and switch @option{-gnatA} is not used).
11731 It is allowable to specify several switches @option{-gnatec=}, all of which
11732 will be taken into account.
11734 Files containing configuration pragmas specified with switches
11735 @option{-gnatec=} are added to the dependencies, unless they are
11736 temporary files. A file is considered temporary if its name ends in
11737 @file{.tmp} or @file{.TMP}. Certain tools follow this naming
11738 convention because they pass information to @command{gcc} via
11739 temporary files that are immediately deleted; it doesn't make sense to
11740 depend on a file that no longer exists. Such tools include
11741 @command{gprbuild}, @command{gnatmake}, and @command{gnatcheck}.
11743 If you are using project file, a separate mechanism is provided using
11744 project attributes, see @ref{Specifying Configuration Pragmas} for more
11745 details.
11748 @node Handling Arbitrary File Naming Conventions with gnatname
11749 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
11750 @cindex Arbitrary File Naming Conventions
11752 @menu
11753 * Arbitrary File Naming Conventions::
11754 * Running gnatname::
11755 * Switches for gnatname::
11756 * Examples of gnatname Usage::
11757 @end menu
11759 @node Arbitrary File Naming Conventions
11760 @section Arbitrary File Naming Conventions
11762 @noindent
11763 The GNAT compiler must be able to know the source file name of a compilation
11764 unit.  When using the standard GNAT default file naming conventions
11765 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11766 does not need additional information.
11768 @noindent
11769 When the source file names do not follow the standard GNAT default file naming
11770 conventions, the GNAT compiler must be given additional information through
11771 a configuration pragmas file (@pxref{Configuration Pragmas})
11772 or a project file.
11773 When the non-standard file naming conventions are well-defined,
11774 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11775 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11776 if the file naming conventions are irregular or arbitrary, a number
11777 of pragma @code{Source_File_Name} for individual compilation units
11778 must be defined.
11779 To help maintain the correspondence between compilation unit names and
11780 source file names within the compiler,
11781 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11782 set of files.
11784 @node Running gnatname
11785 @section Running @code{gnatname}
11787 @noindent
11788 The usual form of the @code{gnatname} command is
11790 @smallexample
11791 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11792 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11793 @c Expanding @ovar macro inline (explanation in macro def comments)
11794 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11795       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11796 @end smallexample
11798 @noindent
11799 All of the arguments are optional. If invoked without any argument,
11800 @code{gnatname} will display its usage.
11802 @noindent
11803 When used with at least one naming pattern, @code{gnatname} will attempt to
11804 find all the compilation units in files that follow at least one of the
11805 naming patterns. To find these compilation units,
11806 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11807 regular files.
11809 @noindent
11810 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11811 Each Naming Pattern is enclosed between double quotes (or single
11812 quotes on Windows).
11813 A Naming Pattern is a regular expression similar to the wildcard patterns
11814 used in file names by the Unix shells or the DOS prompt.
11816 @noindent
11817 @code{gnatname} may be called with several sections of directories/patterns.
11818 Sections are separated by switch @code{--and}. In each section, there must be
11819 at least one pattern. If no directory is specified in a section, the current
11820 directory (or the project directory is @code{-P} is used) is implied.
11821 The options other that the directory switches and the patterns apply globally
11822 even if they are in different sections.
11824 @noindent
11825 Examples of Naming Patterns are
11827 @smallexample
11828    "*.[12].ada"
11829    "*.ad[sb]*"
11830    "body_*"    "spec_*"
11831 @end smallexample
11833 @noindent
11834 For a more complete description of the syntax of Naming Patterns,
11835 see the second kind of regular expressions described in @file{g-regexp.ads}
11836 (the ``Glob'' regular expressions).
11838 @noindent
11839 When invoked with no switch @code{-P}, @code{gnatname} will create a
11840 configuration pragmas file @file{gnat.adc} in the current working directory,
11841 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11842 unit.
11844 @node Switches for gnatname
11845 @section Switches for @code{gnatname}
11847 @noindent
11848 Switches for @code{gnatname} must precede any specified Naming Pattern.
11850 @noindent
11851 You may specify any of the following switches to @code{gnatname}:
11853 @table @option
11854 @c !sort!
11856 @item --version
11857 @cindex @option{--version} @command{gnatname}
11858 Display Copyright and version, then exit disregarding all other options.
11860 @item --help
11861 @cindex @option{--help} @command{gnatname}
11862 If @option{--version} was not used, display usage, then exit disregarding
11863 all other options.
11865 @item --subdirs=<dir>
11866 Real object, library or exec directories are subdirectories <dir> of the
11867 specified ones.
11869 @item --no-backup
11870 Do not create a backup copy of an existing project file.
11872 @item --and
11873 Start another section of directories/patterns.
11875 @item -c@file{file}
11876 @cindex @option{-c} (@code{gnatname})
11877 Create a configuration pragmas file @file{file} (instead of the default
11878 @file{gnat.adc}).
11879 There may be zero, one or more space between @option{-c} and
11880 @file{file}.
11881 @file{file} may include directory information. @file{file} must be
11882 writable. There may be only one switch @option{-c}.
11883 When a switch @option{-c} is
11884 specified, no switch @option{-P} may be specified (see below).
11886 @item -d@file{dir}
11887 @cindex @option{-d} (@code{gnatname})
11888 Look for source files in directory @file{dir}. There may be zero, one or more
11889 spaces between @option{-d} and @file{dir}.
11890 @file{dir} may end with @code{/**}, that is it may be of the form
11891 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
11892 subdirectories, recursively, have to be searched for sources.
11893 When a switch @option{-d}
11894 is specified, the current working directory will not be searched for source
11895 files, unless it is explicitly specified with a @option{-d}
11896 or @option{-D} switch.
11897 Several switches @option{-d} may be specified.
11898 If @file{dir} is a relative path, it is relative to the directory of
11899 the configuration pragmas file specified with switch
11900 @option{-c},
11901 or to the directory of the project file specified with switch
11902 @option{-P} or,
11903 if neither switch @option{-c}
11904 nor switch @option{-P} are specified, it is relative to the
11905 current working directory. The directory
11906 specified with switch @option{-d} must exist and be readable.
11908 @item -D@file{file}
11909 @cindex @option{-D} (@code{gnatname})
11910 Look for source files in all directories listed in text file @file{file}.
11911 There may be zero, one or more spaces between @option{-D}
11912 and @file{file}.
11913 @file{file} must be an existing, readable text file.
11914 Each nonempty line in @file{file} must be a directory.
11915 Specifying switch @option{-D} is equivalent to specifying as many
11916 switches @option{-d} as there are nonempty lines in
11917 @file{file}.
11919 @item -eL
11920 Follow symbolic links when processing project files.
11922 @item -f@file{pattern}
11923 @cindex @option{-f} (@code{gnatname})
11924 Foreign patterns. Using this switch, it is possible to add sources of languages
11925 other than Ada to the list of sources of a project file.
11926 It is only useful if a -P switch is used.
11927 For example,
11928 @smallexample
11929 gnatname -Pprj -f"*.c" "*.ada"
11930 @end smallexample
11931 @noindent
11932 will look for Ada units in all files with the @file{.ada} extension,
11933 and will add to the list of file for project @file{prj.gpr} the C files
11934 with extension @file{.c}.
11936 @item -h
11937 @cindex @option{-h} (@code{gnatname})
11938 Output usage (help) information. The output is written to @file{stdout}.
11940 @item -P@file{proj}
11941 @cindex @option{-P} (@code{gnatname})
11942 Create or update project file @file{proj}. There may be zero, one or more space
11943 between @option{-P} and @file{proj}. @file{proj} may include directory
11944 information. @file{proj} must be writable.
11945 There may be only one switch @option{-P}.
11946 When a switch @option{-P} is specified,
11947 no switch @option{-c} may be specified.
11948 On all platforms, except on VMS, when @code{gnatname} is invoked for an
11949 existing project file <proj>.gpr, a backup copy of the project file is created
11950 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
11951 non negative number that makes this backup copy a new file.
11953 @item -v
11954 @cindex @option{-v} (@code{gnatname})
11955 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11956 This includes name of the file written, the name of the directories to search
11957 and, for each file in those directories whose name matches at least one of
11958 the Naming Patterns, an indication of whether the file contains a unit,
11959 and if so the name of the unit.
11961 @item -v -v
11962 @cindex @option{-v -v} (@code{gnatname})
11963 Very Verbose mode. In addition to the output produced in verbose mode,
11964 for each file in the searched directories whose name matches none of
11965 the Naming Patterns, an indication is given that there is no match.
11967 @item -x@file{pattern}
11968 @cindex @option{-x} (@code{gnatname})
11969 Excluded patterns. Using this switch, it is possible to exclude some files
11970 that would match the name patterns. For example,
11971 @smallexample
11972 gnatname -x "*_nt.ada" "*.ada"
11973 @end smallexample
11974 @noindent
11975 will look for Ada units in all files with the @file{.ada} extension,
11976 except those whose names end with @file{_nt.ada}.
11978 @end table
11980 @node Examples of gnatname Usage
11981 @section Examples of @code{gnatname} Usage
11984 @smallexample
11985 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11986 @end smallexample
11988 @noindent
11989 In this example, the directory @file{/home/me} must already exist
11990 and be writable. In addition, the directory
11991 @file{/home/me/sources} (specified by
11992 @option{-d sources}) must exist and be readable.
11994 Note the optional spaces after @option{-c} and @option{-d}.
11996 @smallexample
11997 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11998   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11999 @end smallexample
12001 Note that several switches @option{-d} may be used,
12002 even in conjunction with one or several switches
12003 @option{-D}. Several Naming Patterns and one excluded pattern
12004 are used in this example.
12006 @c *****************************************
12007 @c * G N A T  P r o j e c t  M a n a g e r *
12008 @c *****************************************
12010 @c ------ macros for projects.texi
12011 @c These macros are needed when building the gprbuild documentation, but
12012 @c should have no effect in the gnat user's guide
12014 @macro CODESAMPLE{TXT}
12015 @smallexample
12016 @group
12017 \TXT\
12018 @end group
12019 @end smallexample
12020 @end macro
12022 @macro PROJECTFILE{TXT}
12023 @CODESAMPLE{\TXT\}
12024 @end macro
12026 @c simulates a newline when in a @CODESAMPLE
12027 @macro NL{}
12028 @end macro
12030 @macro TIP{TXT}
12031 @quotation
12032 @noindent
12033 \TXT\
12034 @end quotation
12035 @end macro
12037 @macro TIPHTML{TXT}
12038 \TXT\
12039 @end macro
12041 @macro IMPORTANT{TXT}
12042 @quotation
12043 @noindent
12044 \TXT\
12045 @end quotation
12047 @end macro
12049 @macro NOTE{TXT}
12050 @quotation
12051 @noindent
12052 \TXT\
12053 @end quotation
12054 @end macro
12056 @include projects.texi
12058 @c ---------------------------------------------
12059 @c Tools Supporting Project Files
12060 @c ---------------------------------------------
12062 @node Tools Supporting Project Files
12063 @chapter Tools Supporting Project Files
12065 @noindent
12067 @menu
12068 * gnatmake and Project Files::
12069 * The GNAT Driver and Project Files::
12070 @end menu
12072 @c ---------------------------------------------
12073 @node gnatmake and Project Files
12074 @section gnatmake and Project Files
12075 @c ---------------------------------------------
12077 @noindent
12078 This section covers several topics related to @command{gnatmake} and
12079 project files: defining switches for @command{gnatmake}
12080 and for the tools that it invokes; specifying configuration pragmas;
12081 the use of the @code{Main} attribute; building and rebuilding library project
12082 files.
12084 @menu
12085 * Switches Related to Project Files::
12086 * Switches and Project Files::
12087 * Specifying Configuration Pragmas::
12088 * Project Files and Main Subprograms::
12089 * Library Project Files::
12090 @end menu
12092 @c ---------------------------------------------
12093 @node Switches Related to Project Files
12094 @subsection Switches Related to Project Files
12095 @c ---------------------------------------------
12097 @noindent
12098 The following switches are used by GNAT tools that support project files:
12100 @table @option
12102 @item -P@var{project}
12103 @cindex @option{-P} (any project-aware tool)
12104 Indicates the name of a project file. This project file will be parsed with
12105 the verbosity indicated by @option{-vP@emph{x}},
12106 if any, and using the external references indicated
12107 by @option{-X} switches, if any.
12108 There may zero, one or more spaces between @option{-P} and @var{project}.
12110 There must be only one @option{-P} switch on the command line.
12112 Since the Project Manager parses the project file only after all the switches
12113 on the command line are checked, the order of the switches
12114 @option{-P},
12115 @option{-vP@emph{x}}
12116 or @option{-X} is not significant.
12118 @item -X@var{name=value}
12119 @cindex @option{-X} (any project-aware tool)
12120 Indicates that external variable @var{name} has the value @var{value}.
12121 The Project Manager will use this value for occurrences of
12122 @code{external(name)} when parsing the project file.
12124 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12125 put between quotes.
12126 @smallexample
12127   -XOS=NT
12128   -X"user=John Doe"
12129 @end smallexample
12131 Several @option{-X} switches can be used simultaneously.
12132 If several @option{-X} switches specify the same
12133 @var{name}, only the last one is used.
12135 An external variable specified with a @option{-X} switch
12136 takes precedence over the value of the same name in the environment.
12138 @item -vP@emph{x}
12139 @cindex @option{-vP} (any project-aware tool)
12140 Indicates the verbosity of the parsing of GNAT project files.
12142 @option{-vP0} means Default;
12143 @option{-vP1} means Medium;
12144 @option{-vP2} means High.
12147 The default is Default: no output for syntactically correct
12148 project files.
12149 If several @option{-vP@emph{x}} switches are present,
12150 only the last one is used.
12152 @item -aP<dir>
12153 @cindex @option{-aP} (any project-aware tool)
12154 Add directory <dir> at the beginning of the project search path, in order,
12155 after the current working directory.
12157 @item -eL
12158 @cindex @option{-eL} (any project-aware tool)
12159 Follow all symbolic links when processing project files.
12161 @item --subdirs=<subdir>
12162 @cindex @option{--subdirs=} (gnatmake and gnatclean)
12163 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12164 indicate that the real directories (except the source directories) are the
12165 subdirectories <subdir> of the directories specified in the project files.
12166 This applies in particular to object directories, library directories and
12167 exec directories. If the subdirectories do not exist, they are created
12168 automatically.
12170 @end table
12172 @c ---------------------------------------------
12173 @node Switches and Project Files
12174 @subsection Switches and Project Files
12175 @c ---------------------------------------------
12177 @noindent
12179 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12180 @code{Linker}, you can specify a @code{Default_Switches}
12181 attribute, a @code{Switches} attribute, or both;
12182 as their names imply, these switch-related
12183 attributes affect the switches that are used for each of these GNAT
12184 components when
12185 @command{gnatmake} is invoked.  As will be explained below, these
12186 component-specific switches precede
12187 the switches provided on the @command{gnatmake} command line.
12189 The @code{Default_Switches} attribute is an attribute
12190 indexed by language name (case insensitive) whose value is a string list.
12191 For example:
12193 @smallexample @c projectfile
12194 @group
12195 @b{package} Compiler @b{is}
12196   @b{for} Default_Switches ("Ada")
12197       @b{use} ("-gnaty",
12198            "-v");
12199 @b{end} Compiler;
12200 @end group
12201 @end smallexample
12203 @noindent
12204 The @code{Switches} attribute is indexed on a file name (which may or may
12205 not be case sensitive, depending
12206 on the operating system) whose value is a string list.  For example:
12208 @smallexample @c projectfile
12209 @group
12210 @b{package} Builder @b{is}
12211    @b{for} Switches ("main1.adb")
12212        @b{use} ("-O2");
12213    @b{for} Switches ("main2.adb")
12214        @b{use} ("-g");
12215 @b{end} Builder;
12216 @end group
12217 @end smallexample
12219 @noindent
12220 For the @code{Builder} package, the file names must designate source files
12221 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12222 file names must designate @file{ALI} or source files for main subprograms.
12223 In each case just the file name without an explicit extension is acceptable.
12225 For each tool used in a program build (@command{gnatmake}, the compiler, the
12226 binder, and the linker), the corresponding package @dfn{contributes} a set of
12227 switches for each file on which the tool is invoked, based on the
12228 switch-related attributes defined in the package.
12229 In particular, the switches
12230 that each of these packages contributes for a given file @var{f} comprise:
12232 @itemize @bullet
12233 @item the value of attribute @code{Switches (@var{f})},
12234   if it is specified in the package for the given file,
12235 @item otherwise, the value of @code{Default_Switches ("Ada")},
12236   if it is specified in the package.
12238 @end itemize
12240 @noindent
12241 If neither of these attributes is defined in the package, then the package does
12242 not contribute any switches for the given file.
12244 When @command{gnatmake} is invoked on a file, the switches comprise
12245 two sets, in the following order: those contributed for the file
12246 by the @code{Builder} package;
12247 and the switches passed on the command line.
12249 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12250 the switches passed to the tool comprise three sets,
12251 in the following order:
12253 @enumerate
12254 @item
12255 the applicable switches contributed for the file
12256 by the @code{Builder} package in the project file supplied on the command line;
12258 @item
12259 those contributed for the file by the package (in the relevant project file --
12260 see below) corresponding to the tool; and
12262 @item
12263 the applicable switches passed on the command line.
12264 @end enumerate
12266 The term @emph{applicable switches} reflects the fact that
12267 @command{gnatmake} switches may or may not be passed to individual
12268 tools, depending on the individual switch.
12270 @command{gnatmake} may invoke the compiler on source files from different
12271 projects. The Project Manager will use the appropriate project file to
12272 determine the @code{Compiler} package for each source file being compiled.
12273 Likewise for the @code{Binder} and @code{Linker} packages.
12275 As an example, consider the following package in a project file:
12277 @smallexample @c projectfile
12278 @group
12279 @b{project} Proj1 @b{is}
12280    @b{package} Compiler @b{is}
12281       @b{for} Default_Switches ("Ada")
12282           @b{use} ("-g");
12283       @b{for} Switches ("a.adb")
12284           @b{use} ("-O1");
12285       @b{for} Switches ("b.adb")
12286           @b{use} ("-O2",
12287                "-gnaty");
12288    @b{end} Compiler;
12289 @b{end} Proj1;
12290 @end group
12291 @end smallexample
12293 @noindent
12294 If @command{gnatmake} is invoked with this project file, and it needs to
12295 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12296 @file{a.adb} will be compiled with the switch
12297 @option{-O1},
12298 @file{b.adb} with switches
12299 @option{-O2}
12300 and @option{-gnaty},
12301 and @file{c.adb} with @option{-g}.
12303 The following example illustrates the ordering of the switches
12304 contributed by different packages:
12306 @smallexample @c projectfile
12307 @group
12308 @b{project} Proj2 @b{is}
12309    @b{package} Builder @b{is}
12310       @b{for} Switches ("main.adb")
12311           @b{use} ("-g",
12312                "-O1",
12313                "-f");
12314    @b{end} Builder;
12315 @end group
12317 @group
12318    @b{package} Compiler @b{is}
12319       @b{for} Switches ("main.adb")
12320           @b{use} ("-O2");
12321    @b{end} Compiler;
12322 @b{end} Proj2;
12323 @end group
12324 @end smallexample
12326 @noindent
12327 If you issue the command:
12329 @smallexample
12330     gnatmake -Pproj2 -O0 main
12331 @end smallexample
12333 @noindent
12334 then the compiler will be invoked on @file{main.adb} with the following
12335 sequence of switches
12337 @smallexample
12338    -g -O1 -O2 -O0
12339 @end smallexample
12341 @noindent
12342 with the last @option{-O}
12343 switch having precedence over the earlier ones;
12344 several other switches
12345 (such as @option{-c}) are added implicitly.
12347 The switches
12348 @option{-g}
12349 and @option{-O1} are contributed by package
12350 @code{Builder},  @option{-O2} is contributed
12351 by the package @code{Compiler}
12352 and @option{-O0} comes from the command line.
12354 The @option{-g}
12355 switch will also be passed in the invocation of
12356 @command{Gnatlink.}
12358 A final example illustrates switch contributions from packages in different
12359 project files:
12361 @smallexample @c projectfile
12362 @group
12363 @b{project} Proj3 @b{is}
12364    @b{for} Source_Files @b{use} ("pack.ads", "pack.adb");
12365    @b{package} Compiler @b{is}
12366       @b{for} Default_Switches ("Ada")
12367           @b{use} ("-gnata");
12368    @b{end} Compiler;
12369 @b{end} Proj3;
12370 @end group
12372 @group
12373 @b{with} "Proj3";
12374 @b{project} Proj4 @b{is}
12375    @b{for} Source_Files @b{use} ("foo_main.adb", "bar_main.adb");
12376    @b{package} Builder @b{is}
12377       @b{for} Switches ("foo_main.adb")
12378           @b{use} ("-s",
12379                "-g");
12380    @b{end} Builder;
12381 @b{end} Proj4;
12382 @end group
12384 @group
12385 --@i{ Ada source file:}
12386 @b{with} Pack;
12387 @b{procedure} Foo_Main @b{is}
12388    @dots{}
12389 @b{end} Foo_Main;
12390 @end group
12391 @end smallexample
12393 @noindent
12394 If the command is
12395 @smallexample
12396 gnatmake -PProj4 foo_main.adb -cargs -gnato
12397 @end smallexample
12399 @noindent
12400 then the switches passed to the compiler for @file{foo_main.adb} are
12401 @option{-g} (contributed by the package @code{Proj4.Builder}) and
12402 @option{-gnato} (passed on the command line).
12403 When the imported package @code{Pack} is compiled, the switches used
12404 are @option{-g} from @code{Proj4.Builder},
12405 @option{-gnata} (contributed from package @code{Proj3.Compiler},
12406 and @option{-gnato} from the command line.
12408 When using @command{gnatmake} with project files, some switches or
12409 arguments may be expressed as relative paths. As the working directory where
12410 compilation occurs may change, these relative paths are converted to absolute
12411 paths. For the switches found in a project file, the relative paths
12412 are relative to the project file directory, for the switches on the command
12413 line, they are relative to the directory where @command{gnatmake} is invoked.
12414 The switches for which this occurs are:
12418 -aO,
12419 -aL,
12420 -aI, as well as all arguments that are not switches (arguments to
12421 switch
12422 -o, object files specified in package @code{Linker} or after
12423 -largs on the command line). The exception to this rule is the switch
12424 --RTS= for which a relative path argument is never converted.
12426 @c ---------------------------------------------
12427 @node Specifying Configuration Pragmas
12428 @subsection Specifying Configuration Pragmas
12429 @c ---------------------------------------------
12431 @noindent
12432 When using @command{gnatmake} with project files, if there exists a file
12433 @file{gnat.adc} that contains configuration pragmas, this file will be
12434 ignored.
12436 Configuration pragmas can be defined by means of the following attributes in
12437 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12438 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12440 Both these attributes are single string attributes. Their values is the path
12441 name of a file containing configuration pragmas. If a path name is relative,
12442 then it is relative to the project directory of the project file where the
12443 attribute is defined.
12445 When compiling a source, the configuration pragmas used are, in order,
12446 those listed in the file designated by attribute
12447 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12448 project file, if it is specified, and those listed in the file designated by
12449 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12450 the project file of the source, if it exists.
12452 @c ---------------------------------------------
12453 @node Project Files and Main Subprograms
12454 @subsection Project Files and Main Subprograms
12455 @c ---------------------------------------------
12457 @noindent
12458 When using a project file, you can invoke @command{gnatmake}
12459 with one or several main subprograms, by specifying their source files on the
12460 command line.
12462 @smallexample
12463     gnatmake -Pprj main1.adb main2.adb main3.adb
12464 @end smallexample
12466 @noindent
12467 Each of these needs to be a source file of the same project, except
12468 when the switch -u is used.
12470 When -u is not used, all the mains need to be sources of the
12471 same project, one of the project in the tree rooted at the project specified
12472 on the command line. The package @code{Builder} of this common project, the
12473 "main project" is the one that is considered by @command{gnatmake}.
12475 When -u is used, the specified source files may be in projects
12476 imported directly or indirectly by the project specified on the command line.
12477 Note that if such a source file is not part of the project specified on the
12478 command line, the switches found in package @code{Builder} of the
12479 project specified on the command line, if any, that are transmitted
12480 to the compiler will still be used, not those found in the project file of
12481 the source file.
12483 When using a project file, you can also invoke @command{gnatmake} without
12484 explicitly specifying any main, and the effect depends on whether you have
12485 defined the @code{Main} attribute.  This attribute has a string list value,
12486 where each element in the list is the name of a source file (the file
12487 extension is optional) that contains a unit that can be a main subprogram.
12489 If the @code{Main} attribute is defined in a project file as a non-empty
12490 string list and the switch @option{-u} is not used on the command
12491 line, then invoking @command{gnatmake} with this project file but without any
12492 main on the command line is equivalent to invoking @command{gnatmake} with all
12493 the file names in the @code{Main} attribute on the command line.
12495 Example:
12496 @smallexample @c projectfile
12497 @group
12498    @b{project} Prj @b{is}
12499       @b{for} Main @b{use} ("main1.adb", "main2.adb", "main3.adb");
12500    @b{end} Prj;
12501 @end group
12502 @end smallexample
12504 @noindent
12505 With this project file, @code{"gnatmake -Pprj"}
12506 is equivalent to
12507 @code{"gnatmake -Pprj main1.adb main2.adb main3.adb"}.
12509 When the project attribute @code{Main} is not specified, or is specified
12510 as an empty string list, or when the switch @option{-u} is used on the command
12511 line, then invoking @command{gnatmake} with no main on the command line will
12512 result in all immediate sources of the project file being checked, and
12513 potentially recompiled. Depending on the presence of the switch @option{-u},
12514 sources from other project files on which the immediate sources of the main
12515 project file depend are also checked and potentially recompiled. In other
12516 words, the @option{-u} switch is applied to all of the immediate sources of the
12517 main project file.
12519 When no main is specified on the command line and attribute @code{Main} exists
12520 and includes several mains, or when several mains are specified on the
12521 command line, the default switches in package @code{Builder} will
12522 be used for all mains, even if there are specific switches
12523 specified for one or several mains.
12525 But the switches from package @code{Binder} or @code{Linker} will be
12526 the specific switches for each main, if they are specified.
12528 @c ---------------------------------------------
12529 @node Library Project Files
12530 @subsection Library Project Files
12531 @c ---------------------------------------------
12533 @noindent
12534 When @command{gnatmake} is invoked with a main project file that is a library
12535 project file, it is not allowed to specify one or more mains on the command
12536 line.
12538 When a library project file is specified, switches -b and
12539 -l have special meanings.
12541 @itemize @bullet
12542 @item -b is only allowed for stand-alone libraries. It indicates
12543   to @command{gnatmake} that @command{gnatbind} should be invoked for the
12544   library.
12546 @item -l may be used for all library projects. It indicates
12547   to @command{gnatmake} that the binder generated file should be compiled
12548   (in the case of a stand-alone library) and that the library should be built.
12549 @end itemize
12551 @c ---------------------------------------------
12552 @node The GNAT Driver and Project Files
12553 @section The GNAT Driver and Project Files
12554 @c ---------------------------------------------
12556 @noindent
12557 A number of GNAT tools, other than @command{gnatmake}
12558 can benefit from project files:
12559 (@command{gnatbind},
12560 @ifclear FSFEDITION
12561 @command{gnatcheck},
12562 @end ifclear
12563 @command{gnatclean},
12564 @ifclear FSFEDITION
12565 @command{gnatelim},
12566 @end ifclear
12567 @command{gnatfind},
12568 @command{gnatlink},
12569 @command{gnatls},
12570 @ifclear FSFEDITION
12571 @command{gnatmetric},
12572 @command{gnatpp},
12573 @command{gnatstub},
12574 @end ifclear
12575 and @command{gnatxref}). However, none of these tools can be invoked
12576 directly with a project file switch (@option{-P}).
12577 They must be invoked through the @command{gnat} driver.
12579 The @command{gnat} driver is a wrapper that accepts a number of commands and
12580 calls the corresponding tool. It was designed initially for VMS platforms (to
12581 convert VMS qualifiers to Unix-style switches), but it is now available on all
12582 GNAT platforms.
12584 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12585 (case insensitive):
12587 @itemize @bullet
12588 @item BIND to invoke @command{gnatbind}
12589 @item CHOP to invoke @command{gnatchop}
12590 @item CLEAN to invoke @command{gnatclean}
12591 @item COMP or COMPILE to invoke the compiler
12592 @ifclear FSFEDITION
12593 @item ELIM to invoke @command{gnatelim}
12594 @end ifclear
12595 @item FIND to invoke @command{gnatfind}
12596 @item KR or KRUNCH to invoke @command{gnatkr}
12597 @item LINK to invoke @command{gnatlink}
12598 @item LS or LIST to invoke @command{gnatls}
12599 @item MAKE to invoke @command{gnatmake}
12600 @item NAME to invoke @command{gnatname}
12601 @item PREP or PREPROCESS to invoke @command{gnatprep}
12602 @ifclear FSFEDITION
12603 @item PP or PRETTY to invoke @command{gnatpp}
12604 @item METRIC to invoke @command{gnatmetric}
12605 @item STUB to invoke @command{gnatstub}
12606 @end ifclear
12607 @item XREF to invoke @command{gnatxref}
12609 @end itemize
12611 @noindent
12612 (note that the compiler is invoked using the command
12613 @command{gnatmake -f -u -c}).
12615 On non-VMS platforms, between @command{gnat} and the command, two
12616 special switches may be used:
12618 @itemize @bullet
12619 @item @command{-v} to display the invocation of the tool.
12620 @item @command{-dn} to prevent the @command{gnat} driver from removing
12621   the temporary files it has created. These temporary files are
12622   configuration files and temporary file list files.
12624 @end itemize
12626 @noindent
12627 The command may be followed by switches and arguments for the invoked
12628 tool.
12630 @smallexample
12631   gnat bind -C main.ali
12632   gnat ls -a main
12633   gnat chop foo.txt
12634 @end smallexample
12636 @noindent
12637 Switches may also be put in text files, one switch per line, and the text
12638 files may be specified with their path name preceded by '@@'.
12640 @smallexample
12641    gnat bind @@args.txt main.ali
12642 @end smallexample
12644 @noindent
12645 In addition, for commands BIND, COMP or COMPILE, FIND,
12646 @ifclear FSFEDITION
12647 ELIM,
12648 @end ifclear
12649 LS or LIST, LINK,
12650 @ifclear FSFEDITION
12651 METRIC,
12652 PP or PRETTY,
12653 STUB,
12654 @end ifclear
12655 and XREF, the project file related switches
12656 (@option{-P},
12657 @option{-X} and
12658 @option{-vPx}) may be used in addition to
12659 the switches of the invoking tool.
12661 @ifclear FSFEDITION
12662 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12663 specified on the command line, it invokes @command{gnatpp} with all
12664 the immediate sources of the specified project file.
12665 @end ifclear
12667 @ifclear FSFEDITION
12668 When GNAT METRIC is used with a project file, but with no source
12669 specified on the command line, it invokes @command{gnatmetric}
12670 with all the immediate sources of the specified project file and with
12671 @option{-d} with the parameter pointing to the object directory
12672 of the project.
12673 @end ifclear
12675 @ifclear FSFEDITION
12676 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12677 a project file, no source is specified on the command line and
12678 switch -U is specified on the command line, then
12679 the underlying tool (gnatpp or
12680 gnatmetric) is invoked for all sources of all projects,
12681 not only for the immediate sources of the main project.
12682 (-U stands for Universal or Union of the project files of the project tree)
12683 @end ifclear
12685 For each of the following commands, there is optionally a corresponding
12686 package in the main project.
12688 @itemize @bullet
12689 @item package @code{Binder} for command BIND (invoking @code{gnatbind})
12691 @ifclear FSFEDITION
12692 @item package @code{Check} for command CHECK (invoking
12693   @code{gnatcheck})
12694 @end ifclear
12696 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12698 @item package @code{Cross_Reference} for command XREF (invoking
12699   @code{gnatxref})
12701 @ifclear FSFEDITION
12702 @item package @code{Eliminate} for command ELIM (invoking
12703   @code{gnatelim})
12704 @end ifclear
12706 @item package @code{Finder} for command FIND (invoking @code{gnatfind})
12708 @item package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
12710 @ifclear FSFEDITION
12711 @item package @code{Gnatstub} for command STUB
12712   (invoking @code{gnatstub})
12713 @end ifclear
12715 @item package @code{Linker} for command LINK (invoking @code{gnatlink})
12717 @ifclear FSFEDITION
12718 @item package @code{Check} for command CHECK
12719   (invoking @code{gnatcheck})
12720 @end ifclear
12722 @ifclear FSFEDITION
12723 @item package @code{Metrics} for command METRIC
12724   (invoking @code{gnatmetric})
12725 @end ifclear
12727 @ifclear FSFEDITION
12728 @item package @code{Pretty_Printer} for command PP or PRETTY
12729   (invoking @code{gnatpp})
12730 @end ifclear
12732 @end itemize
12734 @noindent
12735 Package @code{Gnatls} has a unique attribute @code{Switches},
12736 a simple variable with a string list value. It contains switches
12737 for the invocation of @code{gnatls}.
12739 @smallexample @c projectfile
12740 @group
12741 @b{project} Proj1 @b{is}
12742    @b{package} gnatls @b{is}
12743       @b{for} Switches
12744           @b{use} ("-a",
12745                "-v");
12746    @b{end} gnatls;
12747 @b{end} Proj1;
12748 @end group
12749 @end smallexample
12751 @noindent
12752 All other packages have two attribute @code{Switches} and
12753 @code{Default_Switches}.
12755 @code{Switches} is an indexed attribute, indexed by the
12756 source file name, that has a string list value: the switches to be
12757 used when the tool corresponding to the package is invoked for the specific
12758 source file.
12760 @code{Default_Switches} is an attribute,
12761 indexed by  the programming language that has a string list value.
12762 @code{Default_Switches ("Ada")} contains the
12763 switches for the invocation of the tool corresponding
12764 to the package, except if a specific @code{Switches} attribute
12765 is specified for the source file.
12767 @smallexample @c projectfile
12768 @group
12769 @b{project} Proj @b{is}
12771    @b{for} Source_Dirs @b{use} ("**");
12773    @b{package} gnatls @b{is}
12774       @b{for} Switches @b{use}
12775           ("-a",
12776            "-v");
12777    @b{end} gnatls;
12778 @end group
12779 @group
12781    @b{package} Compiler @b{is}
12782       @b{for} Default_Switches ("Ada")
12783           @b{use} ("-gnatv",
12784                "-gnatwa");
12785    @b{end} Binder;
12786 @end group
12787 @group
12789    @b{package} Binder @b{is}
12790       @b{for} Default_Switches ("Ada")
12791           @b{use} ("-C",
12792                "-e");
12793    @b{end} Binder;
12794 @end group
12795 @group
12797    @b{package} Linker @b{is}
12798       @b{for} Default_Switches ("Ada")
12799           @b{use} ("-C");
12800       @b{for} Switches ("main.adb")
12801           @b{use} ("-C",
12802                "-v",
12803                "-v");
12804    @b{end} Linker;
12805 @end group
12806 @group
12808    @b{package} Finder @b{is}
12809       @b{for} Default_Switches ("Ada")
12810            @b{use} ("-a",
12811                 "-f");
12812    @b{end} Finder;
12813 @end group
12814 @group
12816    @b{package} Cross_Reference @b{is}
12817       @b{for} Default_Switches ("Ada")
12818           @b{use} ("-a",
12819                "-f",
12820                "-d",
12821                "-u");
12822    @b{end} Cross_Reference;
12823 @b{end} Proj;
12824 @end group
12825 @end smallexample
12827 @noindent
12828 With the above project file, commands such as
12830 @smallexample
12831    gnat comp -Pproj main
12832    gnat ls -Pproj main
12833    gnat xref -Pproj main
12834    gnat bind -Pproj main.ali
12835    gnat link -Pproj main.ali
12836 @end smallexample
12838 @noindent
12839 will set up the environment properly and invoke the tool with the switches
12840 found in the package corresponding to the tool:
12841 @code{Default_Switches ("Ada")} for all tools,
12842 except @code{Switches ("main.adb")}
12843 for @code{gnatlink}.
12844 @ifclear FSFEDITION
12845 It is also possible to invoke some of the tools,
12846 (@code{gnatcheck},
12847 @code{gnatmetric},
12848 and @code{gnatpp})
12849 on a set of project units thanks to the combination of the switches
12850 @option{-P}, @option{-U} and possibly the main unit when one is interested
12851 in its closure. For instance,
12852 @smallexample
12853 gnat metric -Pproj
12854 @end smallexample
12856 @noindent
12857 will compute the metrics for all the immediate units of project
12858 @code{proj}.
12859 @smallexample
12860 gnat metric -Pproj -U
12861 @end smallexample
12863 @noindent
12864 will compute the metrics for all the units of the closure of projects
12865 rooted at @code{proj}.
12866 @smallexample
12867 gnat metric -Pproj -U main_unit
12868 @end smallexample
12870 @noindent
12871 will compute the metrics for the closure of units rooted at
12872 @code{main_unit}. This last possibility relies implicitly
12873 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
12874 tool invoked by the @command{gnat} driver are explicitly  specified
12875 either directly or through the tool @option{-files} option, then the tool
12876 is called only for these explicitly specified files.
12877 @end ifclear
12879 @c *****************************************
12880 @c * Cross-referencing tools
12881 @c *****************************************
12883 @node The Cross-Referencing Tools gnatxref and gnatfind
12884 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12885 @findex gnatxref
12886 @findex gnatfind
12888 @noindent
12889 The compiler generates cross-referencing information (unless
12890 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12891 This information indicates where in the source each entity is declared and
12892 referenced. Note that entities in package Standard are not included, but
12893 entities in all other predefined units are included in the output.
12895 Before using any of these two tools, you need to compile successfully your
12896 application, so that GNAT gets a chance to generate the cross-referencing
12897 information.
12899 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12900 information to provide the user with the capability to easily locate the
12901 declaration and references to an entity. These tools are quite similar,
12902 the difference being that @code{gnatfind} is intended for locating
12903 definitions and/or references to a specified entity or entities, whereas
12904 @code{gnatxref} is oriented to generating a full report of all
12905 cross-references.
12907 To use these tools, you must not compile your application using the
12908 @option{-gnatx} switch on the @command{gnatmake} command line
12909 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12910 information will not be generated.
12912 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12913 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12915 @menu
12916 * Switches for gnatxref::
12917 * Switches for gnatfind::
12918 * Project Files for gnatxref and gnatfind::
12919 * Regular Expressions in gnatfind and gnatxref::
12920 * Examples of gnatxref Usage::
12921 * Examples of gnatfind Usage::
12922 @end menu
12924 @node Switches for gnatxref
12925 @section @code{gnatxref} Switches
12927 @noindent
12928 The command invocation for @code{gnatxref} is:
12929 @smallexample
12930 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12931 @c Expanding @ovar macro inline (explanation in macro def comments)
12932 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12933 @end smallexample
12935 @noindent
12936 where
12938 @table @var
12939 @item sourcefile1
12940 @itemx sourcefile2
12941 identifies the source files for which a report is to be generated. The
12942 ``with''ed units will be processed too. You must provide at least one file.
12944 These file names are considered to be regular expressions, so for instance
12945 specifying @file{source*.adb} is the same as giving every file in the current
12946 directory whose name starts with @file{source} and whose extension is
12947 @file{adb}.
12949 You shouldn't specify any directory name, just base names. @command{gnatxref}
12950 and @command{gnatfind} will be able to locate these files by themselves using
12951 the source path. If you specify directories, no result is produced.
12953 @end table
12955 @noindent
12956 The switches can be:
12957 @table @option
12958 @c !sort!
12959 @item --version
12960 @cindex @option{--version} @command{gnatxref}
12961 Display Copyright and version, then exit disregarding all other options.
12963 @item --help
12964 @cindex @option{--help} @command{gnatxref}
12965 If @option{--version} was not used, display usage, then exit disregarding
12966 all other options.
12968 @item -a
12969 @cindex @option{-a} (@command{gnatxref})
12970 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12971 the read-only files found in the library search path. Otherwise, these files
12972 will be ignored. This option can be used to protect Gnat sources or your own
12973 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12974 much faster, and their output much smaller. Read-only here refers to access
12975 or permissions status in the file system for the current user.
12977 @item -aIDIR
12978 @cindex @option{-aIDIR} (@command{gnatxref})
12979 When looking for source files also look in directory DIR. The order in which
12980 source file search is undertaken is the same as for @command{gnatmake}.
12982 @item -aODIR
12983 @cindex @option{-aODIR} (@command{gnatxref})
12984 When searching for library and object files, look in directory
12985 DIR. The order in which library files are searched is the same as for
12986 @command{gnatmake}.
12988 @item -nostdinc
12989 @cindex @option{-nostdinc} (@command{gnatxref})
12990 Do not look for sources in the system default directory.
12992 @item -nostdlib
12993 @cindex @option{-nostdlib} (@command{gnatxref})
12994 Do not look for library files in the system default directory.
12996 @item --ext=@var{extension}
12997 @cindex @option{--ext} (@command{gnatxref})
12998 Specify an alternate ali file extension. The default is @code{ali} and other
12999 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13000 may be specified via this switch. Note that if this switch overrides the
13001 default, which means that only the new extension will be considered.
13003 @item --RTS=@var{rts-path}
13004 @cindex @option{--RTS} (@command{gnatxref})
13005 Specifies the default location of the runtime library. Same meaning as the
13006 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13008 @item -d
13009 @cindex @option{-d} (@command{gnatxref})
13010 If this switch is set @code{gnatxref} will output the parent type
13011 reference for each matching derived types.
13013 @item -f
13014 @cindex @option{-f} (@command{gnatxref})
13015 If this switch is set, the output file names will be preceded by their
13016 directory (if the file was found in the search path). If this switch is
13017 not set, the directory will not be printed.
13019 @item -g
13020 @cindex @option{-g} (@command{gnatxref})
13021 If this switch is set, information is output only for library-level
13022 entities, ignoring local entities. The use of this switch may accelerate
13023 @code{gnatfind} and @code{gnatxref}.
13025 @item -IDIR
13026 @cindex @option{-IDIR} (@command{gnatxref})
13027 Equivalent to @samp{-aODIR -aIDIR}.
13029 @item -pFILE
13030 @cindex @option{-pFILE} (@command{gnatxref})
13031 Specify a project file to use @xref{GNAT Project Manager}.
13032 If you need to use the @file{.gpr}
13033 project files, you should use gnatxref through the GNAT driver
13034 (@command{gnat xref -Pproject}).
13036 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13037 project file in the current directory.
13039 If a project file is either specified or found by the tools, then the content
13040 of the source directory and object directory lines are added as if they
13041 had been specified respectively by @samp{-aI}
13042 and @samp{-aO}.
13043 @item -u
13044 Output only unused symbols. This may be really useful if you give your
13045 main compilation unit on the command line, as @code{gnatxref} will then
13046 display every unused entity and 'with'ed package.
13048 @item -v
13049 Instead of producing the default output, @code{gnatxref} will generate a
13050 @file{tags} file that can be used by vi. For examples how to use this
13051 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13052 to the standard output, thus you will have to redirect it to a file.
13054 @end table
13056 @noindent
13057 All these switches may be in any order on the command line, and may even
13058 appear after the file names. They need not be separated by spaces, thus
13059 you can say @samp{gnatxref -ag} instead of
13060 @samp{gnatxref -a -g}.
13062 @node Switches for gnatfind
13063 @section @code{gnatfind} Switches
13065 @noindent
13066 The command line for @code{gnatfind} is:
13068 @smallexample
13069 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13070 @c       @r{[}@var{file1} @var{file2} @dots{}]
13071 @c Expanding @ovar macro inline (explanation in macro def comments)
13072 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13073       @r{[}@var{file1} @var{file2} @dots{}@r{]}
13074 @end smallexample
13076 @noindent
13077 where
13079 @table @var
13080 @item pattern
13081 An entity will be output only if it matches the regular expression found
13082 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13084 Omitting the pattern is equivalent to specifying @samp{*}, which
13085 will match any entity. Note that if you do not provide a pattern, you
13086 have to provide both a sourcefile and a line.
13088 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13089 for matching purposes. At the current time there is no support for
13090 8-bit codes other than Latin-1, or for wide characters in identifiers.
13092 @item sourcefile
13093 @code{gnatfind} will look for references, bodies or declarations
13094 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13095 and column @var{column}. See @ref{Examples of gnatfind Usage}
13096 for syntax examples.
13098 @item line
13099 is a decimal integer identifying the line number containing
13100 the reference to the entity (or entities) to be located.
13102 @item column
13103 is a decimal integer identifying the exact location on the
13104 line of the first character of the identifier for the
13105 entity reference. Columns are numbered from 1.
13107 @item file1 file2 @dots{}
13108 The search will be restricted to these source files. If none are given, then
13109 the search will be done for every library file in the search path.
13110 These file must appear only after the pattern or sourcefile.
13112 These file names are considered to be regular expressions, so for instance
13113 specifying @file{source*.adb} is the same as giving every file in the current
13114 directory whose name starts with @file{source} and whose extension is
13115 @file{adb}.
13117 The location of the spec of the entity will always be displayed, even if it
13118 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
13119 occurrences of the entity in the separate units of the ones given on the
13120 command line will also be displayed.
13122 Note that if you specify at least one file in this part, @code{gnatfind} may
13123 sometimes not be able to find the body of the subprograms.
13125 @end table
13127 @noindent
13128 At least one of 'sourcefile' or 'pattern' has to be present on
13129 the command line.
13131 The following switches are available:
13132 @table @option
13133 @c !sort!
13135 @cindex @option{--version} @command{gnatfind}
13136 Display Copyright and version, then exit disregarding all other options.
13138 @item --help
13139 @cindex @option{--help} @command{gnatfind}
13140 If @option{--version} was not used, display usage, then exit disregarding
13141 all other options.
13143 @item -a
13144 @cindex @option{-a} (@command{gnatfind})
13145 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13146 the read-only files found in the library search path. Otherwise, these files
13147 will be ignored. This option can be used to protect Gnat sources or your own
13148 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13149 much faster, and their output much smaller. Read-only here refers to access
13150 or permission status in the file system for the current user.
13152 @item -aIDIR
13153 @cindex @option{-aIDIR} (@command{gnatfind})
13154 When looking for source files also look in directory DIR. The order in which
13155 source file search is undertaken is the same as for @command{gnatmake}.
13157 @item -aODIR
13158 @cindex @option{-aODIR} (@command{gnatfind})
13159 When searching for library and object files, look in directory
13160 DIR. The order in which library files are searched is the same as for
13161 @command{gnatmake}.
13163 @item -nostdinc
13164 @cindex @option{-nostdinc} (@command{gnatfind})
13165 Do not look for sources in the system default directory.
13167 @item -nostdlib
13168 @cindex @option{-nostdlib} (@command{gnatfind})
13169 Do not look for library files in the system default directory.
13171 @item --ext=@var{extension}
13172 @cindex @option{--ext} (@command{gnatfind})
13173 Specify an alternate ali file extension. The default is @code{ali} and other
13174 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13175 may be specified via this switch. Note that if this switch overrides the
13176 default, which means that only the new extension will be considered.
13178 @item --RTS=@var{rts-path}
13179 @cindex @option{--RTS} (@command{gnatfind})
13180 Specifies the default location of the runtime library. Same meaning as the
13181 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13183 @item -d
13184 @cindex @option{-d} (@code{gnatfind})
13185 If this switch is set, then @code{gnatfind} will output the parent type
13186 reference for each matching derived types.
13188 @item -e
13189 @cindex @option{-e} (@command{gnatfind})
13190 By default, @code{gnatfind} accept the simple regular expression set for
13191 @samp{pattern}. If this switch is set, then the pattern will be
13192 considered as full Unix-style regular expression.
13194 @item -f
13195 @cindex @option{-f} (@command{gnatfind})
13196 If this switch is set, the output file names will be preceded by their
13197 directory (if the file was found in the search path). If this switch is
13198 not set, the directory will not be printed.
13200 @item -g
13201 @cindex @option{-g} (@command{gnatfind})
13202 If this switch is set, information is output only for library-level
13203 entities, ignoring local entities. The use of this switch may accelerate
13204 @code{gnatfind} and @code{gnatxref}.
13206 @item -IDIR
13207 @cindex @option{-IDIR} (@command{gnatfind})
13208 Equivalent to @samp{-aODIR -aIDIR}.
13210 @item -pFILE
13211 @cindex @option{-pFILE} (@command{gnatfind})
13212 Specify a project file (@pxref{GNAT Project Manager}) to use.
13213 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13214 project file in the current directory.
13216 If a project file is either specified or found by the tools, then the content
13217 of the source directory and object directory lines are added as if they
13218 had been specified respectively by @samp{-aI} and
13219 @samp{-aO}.
13221 @item -r
13222 @cindex @option{-r} (@command{gnatfind})
13223 By default, @code{gnatfind} will output only the information about the
13224 declaration, body or type completion of the entities. If this switch is
13225 set, the @code{gnatfind} will locate every reference to the entities in
13226 the files specified on the command line (or in every file in the search
13227 path if no file is given on the command line).
13229 @item -s
13230 @cindex @option{-s} (@command{gnatfind})
13231 If this switch is set, then @code{gnatfind} will output the content
13232 of the Ada source file lines were the entity was found.
13234 @item -t
13235 @cindex @option{-t} (@command{gnatfind})
13236 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13237 the specified type. It act like -d option but recursively from parent
13238 type to parent type. When this switch is set it is not possible to
13239 specify more than one file.
13241 @end table
13243 @noindent
13244 All these switches may be in any order on the command line, and may even
13245 appear after the file names. They need not be separated by spaces, thus
13246 you can say @samp{gnatxref -ag} instead of
13247 @samp{gnatxref -a -g}.
13249 As stated previously, gnatfind will search in every directory in the
13250 search path. You can force it to look only in the current directory if
13251 you specify @code{*} at the end of the command line.
13253 @node Project Files for gnatxref and gnatfind
13254 @section Project Files for @command{gnatxref} and @command{gnatfind}
13256 @noindent
13257 Project files allow a programmer to specify how to compile its
13258 application, where to find sources, etc.  These files are used
13259 primarily by GPS, but they can also be used
13260 by the two tools
13261 @code{gnatxref} and @code{gnatfind}.
13263 A project file name must end with @file{.gpr}. If a single one is
13264 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13265 extract the information from it. If multiple project files are found, none of
13266 them is read, and you have to use the @samp{-p} switch to specify the one
13267 you want to use.
13269 The following lines can be included, even though most of them have default
13270 values which can be used in most cases.
13271 The lines can be entered in any order in the file.
13272 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13273 each line. If you have multiple instances, only the last one is taken into
13274 account.
13276 @table @code
13277 @item src_dir=DIR
13278 [default: @code{"./"}]
13279 specifies a directory where to look for source files. Multiple @code{src_dir}
13280 lines can be specified and they will be searched in the order they
13281 are specified.
13283 @item obj_dir=DIR
13284 [default: @code{"./"}]
13285 specifies a directory where to look for object and library files. Multiple
13286 @code{obj_dir} lines can be specified, and they will be searched in the order
13287 they are specified
13289 @item comp_opt=SWITCHES
13290 [default: @code{""}]
13291 creates a variable which can be referred to subsequently by using
13292 the @code{$@{comp_opt@}} notation. This is intended to store the default
13293 switches given to @command{gnatmake} and @command{gcc}.
13295 @item bind_opt=SWITCHES
13296 [default: @code{""}]
13297 creates a variable which can be referred to subsequently by using
13298 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13299 switches given to @command{gnatbind}.
13301 @item link_opt=SWITCHES
13302 [default: @code{""}]
13303 creates a variable which can be referred to subsequently by using
13304 the @samp{$@{link_opt@}} notation. This is intended to store the default
13305 switches given to @command{gnatlink}.
13307 @item main=EXECUTABLE
13308 [default: @code{""}]
13309 specifies the name of the executable for the application. This variable can
13310 be referred to in the following lines by using the @samp{$@{main@}} notation.
13312 @item comp_cmd=COMMAND
13313 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13314 specifies the command used to compile a single file in the application.
13316 @item make_cmd=COMMAND
13317 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13318 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13319 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13320 specifies the command used to recompile the whole application.
13322 @item run_cmd=COMMAND
13323 [default: @code{"$@{main@}"}]
13324 specifies the command used to run the application.
13326 @item debug_cmd=COMMAND
13327 [default: @code{"gdb $@{main@}"}]
13328 specifies the command used to debug the application
13330 @end table
13332 @noindent
13333 @command{gnatxref} and @command{gnatfind} only take into account the
13334 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13336 @node Regular Expressions in gnatfind and gnatxref
13337 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13339 @noindent
13340 As specified in the section about @command{gnatfind}, the pattern can be a
13341 regular expression. Actually, there are to set of regular expressions
13342 which are recognized by the program:
13344 @table @code
13345 @item globbing patterns
13346 These are the most usual regular expression. They are the same that you
13347 generally used in a Unix shell command line, or in a DOS session.
13349 Here is a more formal grammar:
13350 @smallexample
13351 @group
13352 @iftex
13353 @leftskip=.5cm
13354 @end iftex
13355 regexp ::= term
13356 term   ::= elmt            -- matches elmt
13357 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13358 term   ::= *               -- any string of 0 or more characters
13359 term   ::= ?               -- matches any character
13360 term   ::= [char @{char@}]   -- matches any character listed
13361 term   ::= [char - char]   -- matches any character in range
13362 @end group
13363 @end smallexample
13365 @item full regular expression
13366 The second set of regular expressions is much more powerful. This is the
13367 type of regular expressions recognized by utilities such a @file{grep}.
13369 The following is the form of a regular expression, expressed in Ada
13370 reference manual style BNF is as follows
13372 @smallexample
13373 @iftex
13374 @leftskip=.5cm
13375 @end iftex
13376 @group
13377 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
13379 term ::= item @{item@}       -- concatenation (item then item)
13381 item ::= elmt              -- match elmt
13382 item ::= elmt *            -- zero or more elmt's
13383 item ::= elmt +            -- one or more elmt's
13384 item ::= elmt ?            -- matches elmt or nothing
13385 @end group
13386 @group
13387 elmt ::= nschar            -- matches given character
13388 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13389 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
13390 elmt ::= [char - char]     -- matches chars in given range
13391 elmt ::= \ char            -- matches given character
13392 elmt ::= .                 -- matches any single character
13393 elmt ::= ( regexp )        -- parens used for grouping
13395 char ::= any character, including special characters
13396 nschar ::= any character except ()[].*+?^
13397 @end group
13398 @end smallexample
13400 Following are a few examples:
13402 @table @samp
13403 @item abcde|fghi
13404 will match any of the two strings @samp{abcde} and @samp{fghi},
13406 @item abc*d
13407 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13408 @samp{abcccd}, and so on,
13410 @item [a-z]+
13411 will match any string which has only lowercase characters in it (and at
13412 least one character.
13414 @end table
13415 @end table
13417 @node Examples of gnatxref Usage
13418 @section Examples of @code{gnatxref} Usage
13420 @subsection General Usage
13422 @noindent
13423 For the following examples, we will consider the following units:
13425 @smallexample @c ada
13426 @group
13427 @cartouche
13428 main.ads:
13429 1: @b{with} Bar;
13430 2: @b{package} Main @b{is}
13431 3:     @b{procedure} Foo (B : @b{in} Integer);
13432 4:     C : Integer;
13433 5: @b{private}
13434 6:     D : Integer;
13435 7: @b{end} Main;
13437 main.adb:
13438 1: @b{package} @b{body} Main @b{is}
13439 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13440 3:     @b{begin}
13441 4:        C := B;
13442 5:        D := B;
13443 6:        Bar.Print (B);
13444 7:        Bar.Print (C);
13445 8:     @b{end} Foo;
13446 9: @b{end} Main;
13448 bar.ads:
13449 1: @b{package} Bar @b{is}
13450 2:     @b{procedure} Print (B : Integer);
13451 3: @b{end} bar;
13452 @end cartouche
13453 @end group
13454 @end smallexample
13456 @table @code
13458 @noindent
13459 The first thing to do is to recompile your application (for instance, in
13460 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13461 the cross-referencing information.
13462 You can then issue any of the following commands:
13464 @item gnatxref main.adb
13465 @code{gnatxref} generates cross-reference information for main.adb
13466 and every unit 'with'ed by main.adb.
13468 The output would be:
13469 @smallexample
13470 @iftex
13471 @leftskip=0cm
13472 @end iftex
13473 B                                                      Type: Integer
13474   Decl: bar.ads           2:22
13475 B                                                      Type: Integer
13476   Decl: main.ads          3:20
13477   Body: main.adb          2:20
13478   Ref:  main.adb          4:13     5:13     6:19
13479 Bar                                                    Type: Unit
13480   Decl: bar.ads           1:9
13481   Ref:  main.adb          6:8      7:8
13482        main.ads           1:6
13483 C                                                      Type: Integer
13484   Decl: main.ads          4:5
13485   Modi: main.adb          4:8
13486   Ref:  main.adb          7:19
13487 D                                                      Type: Integer
13488   Decl: main.ads          6:5
13489   Modi: main.adb          5:8
13490 Foo                                                    Type: Unit
13491   Decl: main.ads          3:15
13492   Body: main.adb          2:15
13493 Main                                                    Type: Unit
13494   Decl: main.ads          2:9
13495   Body: main.adb          1:14
13496 Print                                                   Type: Unit
13497   Decl: bar.ads           2:15
13498   Ref:  main.adb          6:12     7:12
13499 @end smallexample
13501 @noindent
13502 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13503 its body is in main.adb, line 1, column 14 and is not referenced any where.
13505 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13506 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13508 @item gnatxref package1.adb package2.ads
13509 @code{gnatxref} will generates cross-reference information for
13510 package1.adb, package2.ads and any other package 'with'ed by any
13511 of these.
13513 @end table
13515 @subsection Using gnatxref with vi
13517 @code{gnatxref} can generate a tags file output, which can be used
13518 directly from @command{vi}. Note that the standard version of @command{vi}
13519 will not work properly with overloaded symbols. Consider using another
13520 free implementation of @command{vi}, such as @command{vim}.
13522 @smallexample
13523 $ gnatxref -v gnatfind.adb > tags
13524 @end smallexample
13526 @noindent
13527 will generate the tags file for @code{gnatfind} itself (if the sources
13528 are in the search path!).
13530 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13531 (replacing @var{entity} by whatever you are looking for), and vi will
13532 display a new file with the corresponding declaration of entity.
13534 @node Examples of gnatfind Usage
13535 @section Examples of @code{gnatfind} Usage
13537 @table @code
13539 @item gnatfind -f xyz:main.adb
13540 Find declarations for all entities xyz referenced at least once in
13541 main.adb. The references are search in every library file in the search
13542 path.
13544 The directories will be printed as well (as the @samp{-f}
13545 switch is set)
13547 The output will look like:
13548 @smallexample
13549 directory/main.ads:106:14: xyz <= declaration
13550 directory/main.adb:24:10: xyz <= body
13551 directory/foo.ads:45:23: xyz <= declaration
13552 @end smallexample
13554 @noindent
13555 that is to say, one of the entities xyz found in main.adb is declared at
13556 line 12 of main.ads (and its body is in main.adb), and another one is
13557 declared at line 45 of foo.ads
13559 @item gnatfind -fs xyz:main.adb
13560 This is the same command as the previous one, instead @code{gnatfind} will
13561 display the content of the Ada source file lines.
13563 The output will look like:
13565 @smallexample
13566 directory/main.ads:106:14: xyz <= declaration
13567    procedure xyz;
13568 directory/main.adb:24:10: xyz <= body
13569    procedure xyz is
13570 directory/foo.ads:45:23: xyz <= declaration
13571    xyz : Integer;
13572 @end smallexample
13574 @noindent
13575 This can make it easier to find exactly the location your are looking
13576 for.
13578 @item gnatfind -r "*x*":main.ads:123 foo.adb
13579 Find references to all entities containing an x that are
13580 referenced on line 123 of main.ads.
13581 The references will be searched only in main.ads and foo.adb.
13583 @item gnatfind main.ads:123
13584 Find declarations and bodies for all entities that are referenced on
13585 line 123 of main.ads.
13587 This is the same as @code{gnatfind "*":main.adb:123}.
13589 @item gnatfind mydir/main.adb:123:45
13590 Find the declaration for the entity referenced at column 45 in
13591 line 123 of file main.adb in directory mydir. Note that it
13592 is usual to omit the identifier name when the column is given,
13593 since the column position identifies a unique reference.
13595 The column has to be the beginning of the identifier, and should not
13596 point to any character in the middle of the identifier.
13598 @end table
13600 @ifclear FSFEDITION
13601 @c *********************************
13602 @node The GNAT Pretty-Printer gnatpp
13603 @chapter The GNAT Pretty-Printer @command{gnatpp}
13604 @findex gnatpp
13605 @cindex Pretty-Printer
13607 @menu
13608 * Switches for gnatpp::
13609 * Formatting Rules::
13610 @end menu
13612 @noindent
13613 The @command{gnatpp} tool is an ASIS-based utility
13614 for source reformatting / pretty-printing.
13615 It takes an Ada source file as input and generates a reformatted
13616 version as output.
13617 You can specify various style directives via switches; e.g.,
13618 identifier case conventions, rules of indentation, and comment layout.
13620 Note: A newly-redesigned set of formatting algorithms used by gnatpp
13621 is now available.
13622 To invoke the old formatting algorithms, use the @option{--pp-old} switch.
13623 Support for @option{--pp-old} will be removed in some future version.
13625 To produce a reformatted file, @command{gnatpp} invokes the Ada
13626 compiler and generates and uses the ASIS tree for the input source;
13627 thus the input must be legal Ada code, and the tool should have all the
13628 information needed to compile the input source. To provide this information,
13629 you may specify as a tool parameter the project file the input source belongs to
13630 (or you may call @command{gnatpp}
13631 through the @command{gnat} driver (see @ref{The GNAT Driver and
13632 Project Files}). Another possibility is to specify the source search
13633 path and needed configuration files in @option{-cargs} section of @command{gnatpp}
13634 call, see the description of the @command{gnatpp} switches below.
13636 @command{gnatpp} cannot process sources that contain
13637 preprocessing directives.
13639 The @command{gnatpp} command has the form
13641 @smallexample
13642 @c $ gnatpp @ovar{switches} @var{filename}
13643 @c Expanding @ovar macro inline (explanation in macro def comments)
13644 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13645 @end smallexample
13647 @noindent
13648 where
13649 @itemize @bullet
13650 @item
13651 @var{switches} is an optional sequence of switches defining such properties as
13652 the formatting rules, the source search path, and the destination for the
13653 output source file
13655 @item
13656 @var{filename} is the name (including the extension) of the source file to
13657 reformat; wildcards or several file names on the same gnatpp command are
13658 allowed. The file name may contain path information; it does not have to
13659 follow the GNAT file naming rules
13661 @item
13662 @samp{@var{gcc_switches}} is a list of switches for
13663 @command{gcc}. They will be passed on to all compiler invocations made by
13664 @command{gnatpp} to generate the ASIS trees. Here you can provide
13665 @option{-I} switches to form the source search path,
13666 use the @option{-gnatec} switch to set the configuration file, etc.
13667 @end itemize
13669 @node Switches for gnatpp
13670 @section Switches for @command{gnatpp}
13672 @noindent
13673 The following subsections describe the various switches accepted by
13674 @command{gnatpp}, organized by category.
13676 You specify a switch by supplying a name and generally also a value.
13677 In many cases the values for a switch with a given name are incompatible with
13678 each other
13679 (for example the switch that controls the casing of a reserved word may have
13680 exactly one value: upper case, lower case, or
13681 mixed case) and thus exactly one such switch can be in effect for an
13682 invocation of @command{gnatpp}.
13683 If more than one is supplied, the last one is used.
13684 However, some values for the same switch are mutually compatible.
13685 You may supply several such switches to @command{gnatpp}, but then
13686 each must be specified in full, with both the name and the value.
13687 Abbreviated forms (the name appearing once, followed by each value) are
13688 not permitted.
13691 @menu
13692 * Alignment Control::
13693 * Casing Control::
13694 * General Text Layout Control::
13695 * Other Formatting Options::
13696 * Setting the Source Search Path::
13697 * Output File Control::
13698 * Other gnatpp Switches::
13699 @end menu
13701 @node Alignment Control
13702 @subsection Alignment Control
13703 @cindex Alignment control in @command{gnatpp}
13705 @noindent
13706 Programs can be easier to read if certain constructs are vertically aligned.
13707 By default alignment of the following constructs is set ON:
13708 @code{:} in declarations, @code{:=} in initializations in declarations
13709 @code{:=} in assignment statements, @code{=>} in associations, and
13710 @code{at} keywords in the component clauses in record
13711 representation clauses.
13713 @table @option
13714 @cindex @option{-A@var{n}} (@command{gnatpp})
13716 @item -A0
13717 Set alignment to OFF
13719 @item -A1
13720 Set alignment to ON
13721 @end table
13723 @node Casing Control
13724 @subsection Casing Control
13725 @cindex Casing control in @command{gnatpp}
13727 @noindent
13728 @command{gnatpp} allows you to specify the casing for reserved words,
13729 pragma names, attribute designators and identifiers.
13730 For identifiers you may define a
13731 general rule for name casing but also override this rule
13732 via a set of dictionary files.
13734 Three types of casing are supported: lower case, upper case, and mixed case.
13735 ``Mixed case'' means that the first letter, and also each letter immediately
13736 following an underscore, are converted to their uppercase forms;
13737 all the other letters are converted to their lowercase forms.
13739 @table @option
13740 @cindex @option{-a@var{x}} (@command{gnatpp})
13741 @item -aL
13742 Attribute designators are lower case
13744 @item -aU
13745 Attribute designators are upper case
13747 @item -aM
13748 Attribute designators are mixed case (this is the default)
13750 @cindex @option{-k@var{x}} (@command{gnatpp})
13751 @item -kL
13752 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13753 lower case (this is the default)
13755 @item -kU
13756 Keywords are upper case
13758 @cindex @option{-n@var{x}} (@command{gnatpp})
13759 @item -nD
13760 Name casing for defining occurrences are as they appear in the source file
13761 (this is the default)
13763 @item -nU
13764 Names are in upper case
13766 @item -nL
13767 Names are in lower case
13769 @item -nM
13770 Names are in mixed case
13772 @cindex @option{-ne@var{x}} (@command{gnatpp})
13773 @item -neD
13774 Enumeration literal casing for defining occurrences are as they appear in the
13775 source file. Overrides -n casing setting.
13777 @item -neU
13778 Enumeration literals are in upper case.  Overrides -n casing
13779 setting.
13781 @item -neL
13782 Enumeration literals are in lower case. Overrides -n casing
13783 setting.
13785 @item -neM
13786 Enumeration literals are in mixed case. Overrides -n casing
13787 setting.
13789 @cindex @option{-nt@var{x}} (@command{gnatpp})
13790 @item -neD
13791 Names introduced by type and subtype declarations are always
13792 cased as they appear in the declaration in the source file.
13793 Overrides -n casing setting.
13795 @item -ntU
13796 Names introduced by type and subtype declarations are always in
13797 upper case. Overrides -n casing setting.
13799 @item -ntL
13800 Names introduced by type and subtype declarations are always in
13801 lower case. Overrides -n casing setting.
13803 @item -ntM
13804 Names introduced by type and subtype declarations are always in
13805 mixed case. Overrides -n casing setting.
13807 @item -nnU
13808 Names introduced by number declarations are always in
13809 upper case. Overrides -n casing setting.
13811 @item -nnL
13812 Names introduced by number declarations are always in
13813 lower case. Overrides -n casing setting.
13815 @item -nnM
13816 Names introduced by number declarations are always in
13817 mixed case. Overrides -n casing setting.
13819 @cindex @option{-p@var{x}} (@command{gnatpp})
13820 @item -pL
13821 Pragma names are lower case
13823 @item -pU
13824 Pragma names are upper case
13826 @item -pM
13827 Pragma names are mixed case (this is the default)
13829 @item -D@var{file}
13830 @cindex @option{-D} (@command{gnatpp})
13831 Use @var{file} as a @emph{dictionary file} that defines
13832 the casing for a set of specified names,
13833 thereby overriding the effect on these names by
13834 any explicit or implicit
13835 -n switch.
13836 To supply more than one dictionary file,
13837 use several @option{-D} switches.
13839 @noindent
13840 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13841 to define the casing for the Ada predefined names and
13842 the names declared in the GNAT libraries.
13844 @item -D-
13845 @cindex @option{-D-} (@command{gnatpp})
13846 Do not use the default dictionary file;
13847 instead, use the casing
13848 defined by a @option{-n} switch and any explicit
13849 dictionary file(s)
13850 @end table
13852 @noindent
13853 The structure of a dictionary file, and details on the conventions
13854 used in the default dictionary file, are defined in @ref{Name Casing}.
13856 The @option{-D-} and
13857 @option{-D@var{file}} switches are mutually
13858 compatible.
13860 @noindent
13861 This group of @command{gnatpp} switches controls the layout of comments and
13862 complex syntactic constructs.  See @ref{Formatting Comments} for details
13863 on their effect.
13865 @table @option
13866 @cindex @option{-c@var{n}} (@command{gnatpp})
13867 @item -c0
13868 All comments remain unchanged.
13870 @item -c1
13871 GNAT-style comment line indentation.
13872 This is the default.
13874 @item -c3
13875 GNAT-style comment beginning.
13877 @item -c4
13878 Fill comment blocks.
13880 @item -c5
13881 Keep unchanged special form comments.
13882 This is the default.
13884 @item --comments-only
13885 @cindex @option{--comments-only} @command{gnatpp}
13886 Format just the comments.
13888 @cindex @option{--no-separate-is} (@command{gnatpp})
13889 @item --no-separate-is
13890 Do not place the keyword @code{is} on a separate line in a subprogram body in
13891 case if the spec occupies more than one line.
13893 @cindex @option{--separate-loop-then} (@command{gnatpp})
13894 @item --separate-loop-then
13895 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13896 keyword @code{then} in IF statements on a separate line.
13898 @cindex @option{--no-separate-loop-then} (@command{gnatpp})
13899 @item --no-separate-loop-then
13900 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13901 keyword @code{then} in IF statements on a separate line. This option is
13902 incompatible with @option{--separate-loop-then} option.
13904 @cindex @option{--use-on-new-line} (@command{gnatpp})
13905 @item --use-on-new-line
13906 Start each USE clause in a context clause from a separate line.
13908 @cindex @option{--insert-blank-lines} (@command{gnatpp})
13909 @item --insert-blank-lines
13910 Insert blank lines where appropriate (between bodies and other large
13911 constructs).
13913 @cindex @option{--preserve-blank-lines} (@command{gnatpp})
13914 @item --preserve-blank-lines
13915 Preserve blank lines in the input. By default, gnatpp will squeeze
13916 multiple blank lines down to one.
13918 @end table
13920 @noindent
13921 The @option{-c} switches are compatible with one another, except that
13922 the @option{-c0} switch disables all other comment formatting
13923 switches.
13926 @node General Text Layout Control
13927 @subsection General Text Layout Control
13929 @noindent
13930 These switches allow control over line length and indentation.
13932 @table @option
13933 @item -M@var{nnn}
13934 @cindex @option{-M} (@command{gnatpp})
13935 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13937 @item -i@var{nnn}
13938 @cindex @option{-i} (@command{gnatpp})
13939 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13941 @item -cl@var{nnn}
13942 @cindex @option{-cl} (@command{gnatpp})
13943 Indentation level for continuation lines (relative to the line being
13944 continued), @var{nnn} from 1@dots{}9.
13945 The default
13946 value is one less than the (normal) indentation level, unless the
13947 indentation is set to 1 (in which case the default value for continuation
13948 line indentation is also 1)
13949 @end table
13951 @node Other Formatting Options
13952 @subsection Other Formatting Options
13954 @noindent
13955 These switches control other formatting not listed above.
13957 @table @option
13958 @item --decimal-grouping=@var{n}
13959 @cindex @option{--decimal-grouping} @command{gnatpp}
13960 Put underscores in decimal literals (numeric literals without a base)
13961 every @var{n} characters. If a literal already has one or more
13962 underscores, it is not modified. For example, with
13963 @code{--decimal-grouping=3}, @code{1000000} will be changed to
13964 @code{1_000_000}.
13966 @item --based-grouping=@var{n}
13967 @cindex @option{--based-grouping} @command{gnatpp}
13968 Same as @code{--decimal-grouping}, but for based literals. For
13969 example, with @code{--based-grouping=4}, @code{16#0001FFFE#} will be
13970 changed to @code{16#0001_FFFE#}.
13972 @item --split-line-before-op
13973 @cindex @option{--split-line-before-op} (@command{gnatpp})
13974 If it is necessary to split a line at a binary operator, by default
13975 the line is split after the operator. With this option, it is split
13976 before the operator.
13978 @item --RM-style-spacing
13979 @cindex @option{--RM-style-spacing} (@command{gnatpp})
13980 Do not insert an extra blank before various occurrences of
13981 `(' and `:'. This also turns off alignment.
13983 @item -ff
13984 @cindex @option{-ff} (@command{gnatpp})
13985 Insert a Form Feed character after a pragma Page.
13987 @item --call_threshold=@var{nnn}
13988 @cindex @option{--call_threshold} (@command{gnatpp})
13989 If the number of parameter associations is greater than @var{nnn} and if at
13990 least one association uses named notation, start each association from
13991 a new line. If @var{nnn} is 0, no check for the number of associations
13992 is made; this is the default.
13994 @item --par_threshold=@var{nnn}
13995 @cindex @option{--par_threshold} (@command{gnatpp})
13996 If the number of parameter specifications is greater than @var{nnn}
13997 (or equal to @var{nnn} in case of a function), start each specification from
13998 a new line. This feature is disabled by default.
13999 @end table
14001 @node Setting the Source Search Path
14002 @subsection Setting the Source Search Path
14004 @noindent
14005 To define the search path for the input source file, @command{gnatpp}
14006 uses the same switches as the GNAT compiler, with the same effects:
14008 @table @option
14009 @item -I@var{dir}
14010 @cindex @option{-I} (@command{gnatpp})
14012 @item -I-
14013 @cindex @option{-I-} (@command{gnatpp})
14015 @item -gnatec=@var{path}
14016 @cindex @option{-gnatec} (@command{gnatpp})
14018 @end table
14020 @node Output File Control
14021 @subsection Output File Control
14023 @noindent
14024 By default the output is sent to a file whose name is obtained by appending
14025 the @file{.pp} suffix to the name of the input file.
14026 If the file with this name already exists, it is overwritten.
14027 Thus if the input file is @file{my_ada_proc.adb} then
14028 @command{gnatpp} will produce @file{my_ada_proc.adb.pp}
14029 as output file.
14030 The output may be redirected by the following switches:
14032 @table @option
14033 @item --output-dir=@var{dir}
14034 @cindex @option{--output-dir} (@command{gnatpp})
14035 Generate output file in directory @file{dir} with the same name as the input
14036 file. If @file{dir} is the same as the directory containing the input file,
14037 the input file is not processed; use @option{-rnb}
14038 if you want to update the input file in place.
14040 @item -pipe
14041 @cindex @option{-pipe} (@command{gnatpp})
14042 Send the output to @code{Standard_Output}
14044 @item -o @var{output_file}
14045 @cindex @option{-o} (@code{gnatpp})
14046 Write the output into @var{output_file}.
14047 If @var{output_file} already exists, @command{gnatpp} terminates without
14048 reading or processing the input file.
14050 @item -of @var{output_file}
14051 @cindex @option{-of} (@command{gnatpp})
14052 Write the output into @var{output_file}, overwriting the existing file
14053 (if one is present).
14055 @item -r
14056 @cindex @option{-r} (@command{gnatpp})
14057 Replace the input source file with the reformatted output, and copy the
14058 original input source into the file whose name is obtained by appending the
14059 @file{.npp} suffix to the name of the input file.
14060 If a file with this name already exists, @command{gnatpp} terminates without
14061 reading or processing the input file.
14063 @item -rf
14064 @cindex @option{-rf} (@code{gnatpp})
14065 Like @option{-r} except that if the file with the specified name
14066 already exists, it is overwritten.
14068 @item -rnb
14069 @cindex @option{-rnb} (@command{gnatpp})
14070 Replace the input source file with the reformatted output without
14071 creating any backup copy of the input source.
14073 @item --eol=@var{xxx}
14074 @cindex @option{--eol} (@code{gnatpp})
14075 Specifies the line-ending style of the reformatted output file. The @var{xxx}
14076 string specified with the switch may be:
14077 @itemize @bullet
14078 @item ``@option{dos}'' MS DOS style, lines end with CR LF characters
14079 @item ``@option{crlf}''
14080 the same as @option{dos}
14081 @item ``@option{unix}'' UNIX style, lines end with LF character
14082 @item ``@option{lf}''
14083 the same as @option{unix}
14084 @end itemize
14086 @item -W@var{e}
14087 @cindex @option{-W} (@command{gnatpp})
14088 Specify the wide character encoding method for the input and output files.
14089 @var{e} is one of the following:
14091 @itemize @bullet
14093 @item h
14094 Hex encoding
14096 @item u
14097 Upper half encoding
14099 @item s
14100 Shift/JIS encoding
14102 @item e
14103 EUC encoding
14105 @item 8
14106 UTF-8 encoding
14108 @item b
14109 Brackets encoding (default value)
14110 @end itemize
14112 @end table
14114 @noindent
14115 Options @option{-o} and
14116 @option{-of} are allowed only if the call to gnatpp
14117 contains only one file to reformat.
14118 Option
14119 @option{--eol}
14121 @option{-W}
14122 cannot be used together
14123 with @option{-pipe} option.
14125 @node Other gnatpp Switches
14126 @subsection Other @code{gnatpp} Switches
14128 @noindent
14129 The additional @command{gnatpp} switches are defined in this subsection.
14131 @table @option
14132 @item --version
14133 @cindex @option{--version} @command{gnatpp}
14134 Display copyright and version, then exit disregarding all other options.
14136 @item --help
14137 @cindex @option{--help} @command{gnatpp}
14138 Display usage, then exit disregarding all other options.
14140 @item -P @var{file}
14141 @cindex @option{-P} @command{gnatpp}
14142 Indicates the name of the project file that describes the set of sources
14143 to be processed. The exact set of argument sources depends on other options
14144 specified; see below.
14146 @item -U
14147 @cindex @option{-U} @command{gnatpp}
14148 If a project file is specified and no argument source is explicitly
14149 specified (either directly or by means of @option{-files} option), process
14150 all the units of the closure of the argument project. Otherwise this option
14151 has no effect.
14153 @item -U @var{main_unit}
14154 If a project file is specified and no argument source is explicitly
14155 specified (either directly or by means of @option{-files} option), process
14156 the closure of units rooted at @var{main_unit}. Otherwise this option
14157 has no effect.
14159 @item -X@var{name}=@var{value}
14160 @cindex @option{-X} @command{gnatpp}
14161 Indicates that external variable @var{name} in the argument project
14162 has the value @var{value}. Has no effect if no project is specified as
14163 tool argument.
14165 @item --RTS=@var{rts-path}
14166 @cindex @option{--RTS} (@command{gnatpp})
14167 Specifies the default location of the runtime library. Same meaning as the
14168 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14170 @item --incremental
14171 @cindex @option{--incremental} @command{gnatpp}
14172 Incremental processing on a per-file basis. Source files are only
14173 processed if they have been modified, or if files they depend on have
14174 been modified. This is similar to the way gnatmake/gprbuild only
14175 compiles files that need to be recompiled. A project file is required
14176 in this mode, and the gnat driver (as in @command{gnat pretty}) is not
14177 supported.
14179 @item --pp-off=@var{xxx}
14180 @cindex @option{--pp-off} @command{gnatpp}
14181 Use @code{--xxx} as the command to turn off pretty printing, instead
14182 of the default @code{--!pp off}.
14184 @item --pp-on=@var{xxx}
14185 @cindex @option{--pp-on} @command{gnatpp}
14186 Use @code{--xxx} as the command to turn pretty printing back on, instead
14187 of the default @code{--!pp on}.
14189 @item --pp-old
14190 @cindex @option{--pp-old} @command{gnatpp}
14191 Use the old formatting algorithms.
14193 @item -files @var{filename}
14194 @cindex @option{-files} (@code{gnatpp})
14195 Take the argument source files from the specified file. This file should be an
14196 ordinary text file containing file names separated by spaces or
14197 line breaks. You can use this switch more than once in the same call to
14198 @command{gnatpp}. You also can combine this switch with an explicit list of
14199 files.
14201 @item -j@var{n}
14202 @cindex @option{-j} (@command{gnatpp})
14203 Without @option{--incremental}, use @var{n} processes to carry out the
14204 tree creations (internal representations of the argument sources). On
14205 a multiprocessor machine this speeds up processing of big sets of
14206 argument sources. If @var{n} is 0, then the maximum number of parallel
14207 tree creations is the number of core processors on the platform. This
14208 option cannot be used together with @option{-r},
14209 @option{-rf} or
14210 @option{-rnb} option.
14212 With @option{--incremental}, use @var{n} @command{gnatpp} processes to
14213 perform pretty-printing in parallel. @var{n} = 0 means the same as
14214 above. In this case, @option{-r},
14215 @option{-rf} or
14216 @option{-rnb} options are allowed.
14218 @cindex @option{-t} (@command{gnatpp})
14219 @item -t
14220 Print out execution time.
14222 @item -v
14223 @cindex @option{-v} (@command{gnatpp})
14224 Verbose mode
14226 @item -q
14227 @cindex @option{-q} (@command{gnatpp})
14228 Quiet mode
14229 @end table
14231 @noindent
14232 If a project file is specified and no argument source is explicitly
14233 specified (either directly or by means of @option{-files} option), and no
14234 @option{-U} is specified, then the set of processed sources is
14235 all the immediate units of the argument project.
14238 @node Formatting Rules
14239 @section Formatting Rules
14241 @noindent
14242 The following subsections show how @command{gnatpp} treats white space,
14243 comments, program layout, and name casing.
14244 They provide detailed descriptions of the switches shown above.
14246 @menu
14247 * Disabling Pretty Printing::
14248 * White Space and Empty Lines::
14249 * Formatting Comments::
14250 * Name Casing::
14251 @end menu
14253 @node Disabling Pretty Printing
14254 @subsection Disabling Pretty Printing
14256 @noindent
14257 Pretty printing is highly heuristic in nature, and sometimes doesn't
14258 do exactly what you want. If you wish to format a certain region of
14259 code by hand, you can turn off pretty printing in that region by
14260 surrounding it with special comments that start with @code{--!pp off}
14261 and @code{--!pp on}. The text in that region will then be reproduced
14262 verbatim in the output with no formatting.
14264 To disable pretty printing for the whole file, put @code{--!pp off} at
14265 the top, with no following @code{--!pp on}.
14267 The comments must appear on a line by themselves, with nothing
14268 preceding except spaces. The initial text of the comment must be
14269 exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14270 be followed by arbitrary additional text. For example:
14272 @smallexample @c ada
14273 @cartouche
14274 @b{package} Interrupts @b{is}
14275    --@i{!pp off -- turn off pretty printing so "Interrupt_Kind" lines up}
14276    @b{type}            Interrupt_Kind @b{is}
14277      (Asynchronous_Interrupt_Kind,
14278        Synchronous_Interrupt_Kind,
14279              Green_Interrupt_Kind);
14280    --@i{!pp on -- reenable pretty printing}
14282    ...
14283 @end cartouche
14284 @end smallexample
14286 You can specify different comment strings using the @code{--pp-off}
14287 and @code{--pp-on} switches. For example, if you say @code{gnatpp
14288 --pp-off=' pp-' *.ad?} then gnatpp will recognize comments of the form
14289 @code{-- pp-} instead of @code{--!pp off} for disabling pretty
14290 printing. Note that the leading @code{--} of the comment is not
14291 included in the argument to these switches.
14293 @node White Space and Empty Lines
14294 @subsection White Space and Empty Lines
14296 @noindent
14297 @command{gnatpp} does not have an option to control space characters.
14298 It will add or remove spaces according to the style illustrated by the
14299 examples in the @cite{Ada Reference Manual}.
14300 The output file will contain no lines with trailing white space.
14302 By default, a sequence of one or more blank lines in the input is
14303 converted to a single blank line in the output; multiple blank lines
14304 are squeezed down to one.
14305 The @option{--preserve-blank-lines} option
14306 turns off the squeezing; each blank line in the input is copied
14307 to the output.
14308 The @option{--insert-blank-lines} option
14309 causes additional blank lines to be inserted if not already
14310 present in the input (e.g. between bodies).
14312 @node Formatting Comments
14313 @subsection Formatting Comments
14315 @noindent
14316 Comments in Ada code are of two kinds:
14317 @itemize @bullet
14318 @item
14319 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14320 white space) on a line
14322 @item
14323 an @emph{end-of-line comment}, which follows some other Ada code on
14324 the same line.
14325 @end itemize
14327 @noindent
14328 A whole-line comment is indented according to the surrounding code,
14329 with some exceptions.
14330 Comments that start in column 1 are kept there.
14331 If possible, comments are not moved so far to the right that the maximum
14332 line length is exceeded.
14333 The @option{-c0} option
14334 turns off comment formatting.
14335 Special-form comments such as SPARK-style @code{--#...} are left alone.
14337 For an end-of-line comment, @command{gnatpp} tries to leave the same
14338 number of spaces between the end of the preceding Ada code and the
14339 beginning of the comment as appear in the original source.
14341 @noindent
14342 The @option{-c3} switch
14343 (GNAT style comment beginning) has the following
14344 effect:
14346 @itemize @bullet
14347 @item
14348 For each whole-line comment that does not end with two hyphens,
14349 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14350 to ensure that there are at least two spaces between these hyphens and the
14351 first non-blank character of the comment.
14352 @end itemize
14354 @noindent
14355 The @option{-c4} switch specifies that
14356 whole-line comments that form a paragraph will be filled in typical
14357 word processor style (that is, moving words between lines to make the
14358 lines other than the last similar in length ).
14360 @noindent
14361 The @option{--comments-only} switch specifies that only the comments
14362 are formatted; the rest of the program text is left alone. The
14363 comments are formatted according to the -c3 and -c4 switches; other
14364 formatting switches are ignored. For example, @option{--comments-only
14365 -c4} means to fill comment paragraphs, and do nothing else. Likewise,
14366 @option{--comments-only -c3} ensures comments start with at least two
14367 spaces after @code{--}, and @option{--comments-only -c3 -c4} does
14368 both. If @option{--comments-only} is given without @option{-c3} or
14369 @option{-c4}, then gnatpp doesn't format anything.
14371 @node Name Casing
14372 @subsection Name Casing
14374 @noindent
14375 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14376 the same casing as the corresponding defining identifier.
14378 You control the casing for defining occurrences via the
14379 @option{-n} switch.
14380 With @option{-nD} (``as declared'', which is the default),
14381 defining occurrences appear exactly as in the source file
14382 where they are declared.
14383 The other values for this switch ---
14384 @option{-nU},
14385 @option{-nL},
14386 @option{-nM} ---
14387 result in
14388 upper, lower, or mixed case, respectively.
14389 If @command{gnatpp} changes the casing of a defining
14390 occurrence, it analogously changes the casing of all the
14391 usage occurrences of this name.
14393 If the defining occurrence of a name is not in the source compilation unit
14394 currently being processed by @command{gnatpp}, the casing of each reference to
14395 this name is changed according to the value of the @option{-n}
14396 switch (subject to the dictionary file mechanism described below).
14397 Thus @command{gnatpp} acts as though the @option{-n} switch
14398 had affected the
14399 casing for the defining occurrence of the name.
14401 The options
14402 @option{-a@var{x}},
14403 @option{-k@var{x}},
14404 @option{-ne@var{x}},
14405 @option{-nt@var{x}},
14406 @option{-nn@var{x}}, and
14407 @option{-p@var{x}}
14408 allow finer-grained control over casing for
14409 attributes, keywords, enumeration literals,
14410 types, named numbers and pragmas, respectively.
14411 @option{-nt@var{x}} covers subtypes and
14412 task and protected bodies as well.
14414 Some names may need to be spelled with casing conventions that are not
14415 covered by the upper-, lower-, and mixed-case transformations.
14416 You can arrange correct casing by placing such names in a
14417 @emph{dictionary file},
14418 and then supplying a @option{-D} switch.
14419 The casing of names from dictionary files overrides
14420 any @option{-n} switch.
14422 To handle the casing of Ada predefined names and the names from GNAT libraries,
14423 @command{gnatpp} assumes a default dictionary file.
14424 The name of each predefined entity is spelled with the same casing as is used
14425 for the entity in the @cite{Ada Reference Manual} (usually mixed case).
14426 The name of each entity in the GNAT libraries is spelled with the same casing
14427 as is used in the declaration of that entity.
14429 The @w{@option{-D-}} switch suppresses the use of
14430 the default dictionary file. Instead, the casing for predefined and
14431 GNAT-defined names will be established by the
14432 @option{-n} switch or explicit dictionary files. For
14433 example, by default the names @code{Ada.Text_IO} and
14434 @code{GNAT.OS_Lib} will appear as just shown, even in the presence of
14435 a @option{-nU} switch.  To ensure that even
14436 such names are rendered in uppercase, additionally supply the
14437 @w{@option{-D-}} switch (or else place these names
14438 in upper case in a dictionary file).
14440 A dictionary file is a plain text file; each line in this file can be
14441 either a blank line (containing only space characters), an Ada comment
14442 line, or the specification of exactly one @emph{casing schema}.
14444 A casing schema is a string that has the following syntax:
14446 @smallexample
14447 @cartouche
14448   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14450   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14451 @end cartouche
14452 @end smallexample
14454 @noindent
14455 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14456 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14458 The casing schema string can be followed by white space and/or an Ada-style
14459 comment; any amount of white space is allowed before the string.
14461 If a dictionary file is passed as
14462 the value of a @option{-D@var{file}} switch
14463 then for every
14464 simple name and every identifier, @command{gnatpp} checks if the dictionary
14465 defines the casing for the name or for some of its parts (the term ``subword''
14466 is used below to denote the part of a name which is delimited by ``_'' or by
14467 the beginning or end of the word and which does not contain any ``_'' inside):
14469 @itemize @bullet
14470 @item
14471 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14472 the casing defined by the dictionary; no subwords are checked for this word
14474 @item
14475 for every subword @command{gnatpp} checks if the dictionary contains the
14476 corresponding string of the form @code{*@var{simple_identifier}*},
14477 and if it does, the casing of this @var{simple_identifier} is used
14478 for this subword
14480 @item
14481 if the whole name does not contain any ``_'' inside, and if for this name
14482 the dictionary contains two entries - one of the form @var{identifier},
14483 and another - of the form *@var{simple_identifier}*, then the first one
14484 is applied to define the casing of this name
14486 @item
14487 if more than one dictionary file is passed as @command{gnatpp} switches, each
14488 dictionary adds new casing exceptions and overrides all the existing casing
14489 exceptions set by the previous dictionaries
14491 @item
14492 when @command{gnatpp} checks if the word or subword is in the dictionary,
14493 this check is not case sensitive
14494 @end itemize
14496 @noindent
14497 For example, suppose we have the following source to reformat:
14499 @smallexample @c ada
14500 @cartouche
14501 @b{procedure} test @b{is}
14502    name1 : integer := 1;
14503    name4_name3_name2 : integer := 2;
14504    name2_name3_name4 : Boolean;
14505    name1_var : Float;
14506 @b{begin}
14507    name2_name3_name4 := name4_name3_name2 > name1;
14508 @b{end};
14509 @end cartouche
14510 @end smallexample
14512 @noindent
14513 And suppose we have two dictionaries:
14515 @smallexample
14516 @cartouche
14517 @i{dict1:}
14518    NAME1
14519    *NaMe3*
14520    *Name1*
14521 @end cartouche
14523 @cartouche
14524 @i{dict2:}
14525   *NAME3*
14526 @end cartouche
14527 @end smallexample
14529 @noindent
14530 If @command{gnatpp} is called with the following switches:
14532 @smallexample
14533 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14534 @end smallexample
14536 @noindent
14537 then we will get the following name casing in the @command{gnatpp} output:
14539 @smallexample @c ada
14540 @cartouche
14541 @b{procedure} Test @b{is}
14542    NAME1             : Integer := 1;
14543    Name4_NAME3_Name2 : Integer := 2;
14544    Name2_NAME3_Name4 : Boolean;
14545    Name1_Var         : Float;
14546 @b{begin}
14547    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14548 @b{end} Test;
14549 @end cartouche
14550 @end smallexample
14551 @end ifclear
14553 @ifclear FSFEDITION
14554 @c *********************************
14555 @node The Ada-to-XML converter gnat2xml
14556 @chapter The Ada-to-XML converter @command{gnat2xml}
14557 @findex gnat2xml
14558 @cindex XML generation
14560 @noindent
14561 The @command{gnat2xml} tool is an ASIS-based utility that converts
14562 Ada source code into XML.
14564 @menu
14565 * Switches for gnat2xml::
14566 * Other Programs::
14567 * Structure of the XML::
14568 * Generating Representation Clauses::
14569 @end menu
14571 @node Switches for gnat2xml
14572 @section Switches for @command{gnat2xml}
14574 @noindent
14575 @command{gnat2xml} takes Ada source code as input, and produces XML
14576 that conforms to the schema.
14578 Usage:
14580 @smallexample
14581 gnat2xml [options] filenames [-files filename] [-cargs gcc_switches]
14582 @end smallexample
14584 @noindent
14585 options:
14586 @smallexample
14588 --help -- generate usage information and quit, ignoring all other options
14589 --version -- print version and quit, ignoring all other options
14591 -P @file{file} -- indicates the name of the project file that describes
14592       the set of sources to be processed. The exact set of argument
14593       sources depends on other options specified, see below.
14595 -U -- if a project file is specified and no argument source is explicitly
14596       specified, process all the units of the closure of the argument project.
14597       Otherwise this option has no effect.
14599 -U @var{main_unit} -- if a project file is specified and no argument source
14600       is explicitly specified (either directly or by means of @option{-files}
14601       option), process the closure of units rooted at @var{main_unit}.
14602       Otherwise this option has no effect.
14604 -X@var{name}=@var{value} -- indicates that external variable @var{name} in
14605       the argument project has the value @var{value}. Has no effect if no
14606       project is specified as tool argument.
14608 --RTS=@var{rts-path}  -- Specifies the default location of the runtime
14609       library. Same meaning as the equivalent @command{gnatmake} flag
14610       (@pxref{Switches for gnatmake}).
14612 --incremental -- incremental processing on a per-file basis. Source files are
14613       only processed if they have been modified, or if files they depend
14614       on have been modified. This is similar to the way gnatmake/gprbuild
14615       only compiles files that need to be recompiled. A project file
14616       is required in this mode.
14618 -j@var{n} -- In @option{--incremental} mode, use @var{n} @command{gnat2xml}
14619       processes to perform XML generation in parallel. If @var{n} is 0, then
14620       the maximum number of parallel tree creations is the number of core
14621       processors on the platform.
14623 --output-dir=@var{dir} -- generate one .xml file for each Ada source file, in
14624       directory @file{dir}. (Default is to generate the XML to standard
14625       output.)
14627 -I <include-dir>
14628       directories to search for dependencies
14629       You can also set the ADA_INCLUDE_PATH environment variable for this.
14631 --compact -- debugging version, with interspersed source, and a more
14632       compact representation of "sloc". This version does not conform
14633       to any schema.
14635 --rep-clauses -- generate representation clauses (see ``Generating
14636       Representation Clauses'' below).
14638 -files=filename - the name of a text file containing a list
14639                   of Ada source files to process
14641 -q -- quiet
14642 -v -- verbose
14644 -cargs ... -- options to pass to gcc
14645 @end smallexample
14647 @noindent
14648 If a project file is specified and no argument source is explicitly
14649 specified, and no @option{-U} is specified, then the set of processed
14650 sources is all the immediate units of the argument project.
14652 Example:
14654 @smallexample
14655 gnat2xml -v -output-dir=xml-files *.ad[sb]
14656 @end smallexample
14658 @noindent
14659 The above will create *.xml files in the @file{xml-files} subdirectory.
14660 For example, if there is an Ada package Mumble.Dumble, whose spec and
14661 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
14662 the above will produce xml-files/mumble-dumble.ads.xml and
14663 xml-files/mumble-dumble.adb.xml.
14665 @node Other Programs
14666 @section Other Programs
14668 @noindent
14669 The distribution includes two other programs that are related to
14670 @command{gnat2xml}:
14672 @command{gnat2xsd} is the schema generator, which generates the schema
14673 to standard output, based on the structure of Ada as encoded by
14674 ASIS. You don't need to run @command{gnat2xsd} in order to use
14675 @command{gnat2xml}. To generate the schema, type:
14677 @smallexample
14678 gnat2xsd > ada-schema.xsd
14679 @end smallexample
14681 @noindent
14682 @command{gnat2xml} generates XML files that will validate against
14683 @file{ada-schema.xsd}.
14685 @command{xml2gnat} is a back-translator that translates the XML back
14686 into Ada source code. The Ada generated by @command{xml2gnat} has
14687 identical semantics to the original Ada code passed to
14688 @command{gnat2xml}. It is not textually identical, however --- for
14689 example, no attempt is made to preserve the original indentation.
14691 @node Structure of the XML
14692 @section Structure of the XML
14694 @noindent
14695 The primary documentation for the structure of the XML generated by
14696 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
14697 following documentation gives additional details needed to understand
14698 the schema and therefore the XML.
14700 The elements listed under Defining Occurrences, Usage Occurrences, and
14701 Other Elements represent the syntactic structure of the Ada program.
14702 Element names are given in lower case, with the corresponding element
14703 type Capitalized_Like_This. The element and element type names are
14704 derived directly from the ASIS enumeration type Flat_Element_Kinds,
14705 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
14706 removed. For example, the ASIS enumeration literal
14707 An_Assignment_Statement corresponds to the XML element
14708 assignment_statement of XML type Assignment_Statement.
14710 To understand the details of the schema and the corresponding XML, it is
14711 necessary to understand the ASIS standard, as well as the GNAT-specific
14712 extension to ASIS.
14714 A defining occurrence is an identifier (or character literal or operator
14715 symbol) declared by a declaration. A usage occurrence is an identifier
14716 (or ...) that references such a declared entity. For example, in:
14718 @smallexample
14719 type T is range 1..10;
14720 X, Y : constant T := 1;
14721 @end smallexample
14723 @noindent
14724 The first ``T'' is the defining occurrence of a type. The ``X'' is the
14725 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
14726 a usage occurrence referring to the defining occurrence of T.
14728 Each element has a 'sloc' (source location), and subelements for each
14729 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
14730 The types of subelements are as defined in the ASIS standard. For
14731 example, for the right-hand side of an assignment_statement we have
14732 the following comment in asis-statements.ads:
14734 @smallexample
14735 ------------------------------------------------------------------------------
14736 --  18.3  function Assignment_Expression
14737 ------------------------------------------------------------------------------
14739    function Assignment_Expression
14740      (Statement : Asis.Statement)
14741       return      Asis.Expression;
14743 ------------------------------------------------------------------------------
14745 --  Returns the expression from the right hand side of the assignment.
14747 --  Returns Element_Kinds:
14748 --       An_Expression
14749 @end smallexample
14751 @noindent
14752 The corresponding sub-element of type Assignment_Statement is:
14754 @smallexample
14755 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
14756 @end smallexample
14758 @noindent
14759 where Expression_Class is defined by an xsd:choice of all the
14760 various kinds of expression.
14762 The 'sloc' of each element indicates the starting and ending line and
14763 column numbers. Column numbers are character counts; that is, a tab
14764 counts as 1, not as however many spaces it might expand to.
14766 Subelements of type Element have names ending in ``_q'' (for ASIS
14767 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
14768 List'').
14770 Some subelements are ``Boolean''. For example, Private_Type_Definition
14771 has has_abstract_q and has_limited_q, to indicate whether those
14772 keywords are present, as in @code{type T is abstract limited
14773 private;}. False is represented by a Nil_Element. True is represented
14774 by an element type specific to that query (for example, Abstract and
14775 Limited).
14777 The root of the tree is a Compilation_Unit, with attributes:
14779 @itemize @bullet
14780 @item
14781 unit_kind, unit_class, and unit_origin. These are strings that match the
14782 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
14783 in package Asis.
14785 @item
14786 unit_full_name is the full expanded name of the unit, starting from a
14787 root library unit. So for @code{package P.Q.R is ...},
14788 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
14790 @item
14791 def_name is the same as unit_full_name for library units; for subunits,
14792 it is just the simple name.
14794 @item
14795 source_file is the name of the Ada source file. For example, for
14796 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
14797 interpret the source locations --- the ``sloc'' of all elements
14798 within this Compilation_Unit refers to line and column numbers
14799 within the named file.
14800 @end itemize
14802 @noindent
14803 Defining occurrences have these attributes:
14805 @itemize @bullet
14806 @item
14807 def_name is the simple name of the declared entity, as written in the Ada
14808 source code.
14810 @item
14811 def is a unique URI of the form:
14813  ada://kind/fully/qualified/name
14815 where:
14817  kind indicates the kind of Ada entity being declared (see below), and
14819  fully/qualified/name, is the fully qualified name of the Ada
14820  entity, with each of ``fully'', ``qualified'', and ``name'' being
14821  mangled for uniqueness. We do not document the mangling
14822  algorithm, which is subject to change; we just guarantee that the
14823  names are unique in the face of overloading.
14825 @item
14826 type is the type of the declared object, or @code{null} for
14827 declarations of things other than objects.
14828 @end itemize
14830 @noindent
14831 Usage occurrences have these attributes:
14833 @itemize @bullet
14834 @item
14835 ref_name is the same as the def_name of the corresponding defining
14836 occurrence. This attribute is not of much use, because of
14837 overloading; use ref for lookups, instead.
14839 @item
14840 ref is the same as the def of the corresponding defining
14841 occurrence.
14842 @end itemize
14844 @noindent
14845 In summary, @code{def_name} and @code{ref_name} are as in the source
14846 code of the declaration, possibly overloaded, whereas @code{def} and
14847 @code{ref} are unique-ified.
14849 Literal elements have this attribute:
14851 @itemize @bullet
14852 @item
14853 lit_val is the value of the literal as written in the source text,
14854 appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
14855 only to numeric and string literals. Enumeration literals in Ada are
14856 not really "literals" in the usual sense; they are usage occurrences,
14857 and have ref_name and ref as described above. Note also that string
14858 literals used as operator symbols are treated as defining or usage
14859 occurrences, not as literals.
14860 @end itemize
14862 @noindent
14863 Elements that can syntactically represent names and expressions (which
14864 includes usage occurrences, plus function calls and so forth) have this
14865 attribute:
14867 @itemize @bullet
14868 @item
14869 type. If the element represents an expression or the name of an object,
14870 'type' is the 'def' for the defining occurrence of the type of that
14871 expression or name. Names of other kinds of entities, such as package
14872 names and type names, do not have a type in Ada; these have type="null"
14873 in the XML.
14874 @end itemize
14876 @noindent
14877 Pragma elements have this attribute:
14879 @itemize @bullet
14880 @item
14881 pragma_name is the name of the pragma. For language-defined pragmas, the
14882 pragma name is redundant with the element kind (for example, an
14883 assert_pragma element necessarily has pragma_name="Assert"). However, all
14884 implementation-defined pragmas are lumped together in ASIS as a single
14885 element kind (for example, the GNAT-specific pragma Unreferenced is
14886 represented by an implementation_defined_pragma element with
14887 pragma_name="Unreferenced").
14888 @end itemize
14890 @noindent
14891 Defining occurrences of formal parameters and generic formal objects have this
14892 attribute:
14894 @itemize @bullet
14895 @item
14896 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
14897 @end itemize
14899 @noindent
14900 All elements other than Not_An_Element have this attribute:
14902 @itemize @bullet
14903 @item
14904 checks is a comma-separated list of run-time checks that are needed
14905 for that element. The possible checks are: do_accessibility_check,
14906 do_discriminant_check,do_division_check,do_length_check,
14907 do_overflow_check,do_range_check,do_storage_check,do_tag_check.
14908 @end itemize
14910 @noindent
14911 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
14912 enumeration type Flat_Declaration_Kinds, declared in
14913 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
14914 any trailing "_Declaration" or "_Specification" removed. Thus, the
14915 possible kinds are as follows:
14917 @smallexample
14918 ordinary_type
14919 task_type
14920 protected_type
14921 incomplete_type
14922 tagged_incomplete_type
14923 private_type
14924 private_extension
14925 subtype
14926 variable
14927 constant
14928 deferred_constant
14929 single_task
14930 single_protected
14931 integer_number
14932 real_number
14933 enumeration_literal
14934 discriminant
14935 component
14936 loop_parameter
14937 generalized_iterator
14938 element_iterator
14939 procedure
14940 function
14941 parameter
14942 procedure_body
14943 function_body
14944 return_variable
14945 return_constant
14946 null_procedure
14947 expression_function
14948 package
14949 package_body
14950 object_renaming
14951 exception_renaming
14952 package_renaming
14953 procedure_renaming
14954 function_renaming
14955 generic_package_renaming
14956 generic_procedure_renaming
14957 generic_function_renaming
14958 task_body
14959 protected_body
14960 entry
14961 entry_body
14962 entry_index
14963 procedure_body_stub
14964 function_body_stub
14965 package_body_stub
14966 task_body_stub
14967 protected_body_stub
14968 exception
14969 choice_parameter
14970 generic_procedure
14971 generic_function
14972 generic_package
14973 package_instantiation
14974 procedure_instantiation
14975 function_instantiation
14976 formal_object
14977 formal_type
14978 formal_incomplete_type
14979 formal_procedure
14980 formal_function
14981 formal_package
14982 formal_package_declaration_with_box
14983 @end smallexample
14985 @node Generating Representation Clauses
14986 @section Generating Representation Clauses
14988 @noindent
14989 If the @option{--rep-clauses} switch is given, @command{gnat2xml} will
14990 generate representation clauses for certain types showing the
14991 representation chosen by the compiler. The information is produced by
14992 the ASIS ``Data Decomposition'' facility --- see the
14993 @code{Asis.Data_Decomposition} package for details.
14995 Not all types are supported. For example, @code{Type_Model_Kind} must
14996 be @code{A_Simple_Static_Model}. Types declared within generic units
14997 have no representation. The clauses that are generated include
14998 @code{attribute_definition_clauses} for @code{Size} and
14999 @code{Component_Size}, as well as
15000 @code{record_representation_clauses}.
15002 There is no guarantee that the generated representation clauses could
15003 have actually come from legal Ada code; Ada has some restrictions that
15004 are not necessarily obeyed by the generated clauses.
15006 The representation clauses are surrounded by comment elements to
15007 indicate that they are automatically generated, something like this:
15009 @smallexample
15010 <comment text="--gen+">
15012 <attribute_definition_clause>
15014 <comment text="--gen-">
15016 @end smallexample
15018 @end ifclear
15020 @ifclear FSFEDITION
15021 @c *********************************
15022 @node The GNAT Metrics Tool gnatmetric
15023 @chapter The GNAT Metrics Tool @command{gnatmetric}
15024 @findex gnatmetric
15025 @cindex Metric tool
15027 @noindent
15028 The @command{gnatmetric} tool is an ASIS-based utility
15029 for computing various program metrics.
15030 It takes an Ada source file as input and generates a file containing the
15031 metrics data as output. Various switches control which
15032 metrics are computed and output.
15034 @menu
15035 * Switches for gnatmetric::
15036 @end menu
15038 To compute program metrics, @command{gnatmetric} invokes the Ada
15039 compiler and generates and uses the ASIS tree for the input source;
15040 thus the input must be legal Ada code, and the tool should have all the
15041 information needed to compile the input source. To provide this information,
15042 you may specify as a tool parameter the project file the input source belongs to
15043 (or you may call @command{gnatmetric}
15044 through the @command{gnat} driver (see @ref{The GNAT Driver and
15045 Project Files}). Another possibility is to specify the source search
15046 path and needed configuration files in @option{-cargs} section of @command{gnatmetric}
15047 call, see the description of the @command{gnatmetric} switches below.
15049 If the set of sources to be processed by @code{gnatmetric} contains sources with
15050 preprocessing directives
15051 then the needed options should be provided to run preprocessor as a part of
15052 the @command{gnatmetric} call, and the computed metrics
15053 will correspond to preprocessed sources.
15056 The @command{gnatmetric} command has the form
15058 @smallexample
15059 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15060 @c Expanding @ovar macro inline (explanation in macro def comments)
15061 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15062 @end smallexample
15064 @noindent
15065 where
15066 @itemize @bullet
15067 @item
15068 @var{switches} specify the metrics to compute and define the destination for
15069 the output
15071 @item
15072 Each @var{filename} is the name (including the extension) of a source
15073 file to process. ``Wildcards'' are allowed, and
15074 the file name may contain path information.
15075 If no @var{filename} is supplied, then the @var{switches} list must contain
15076 at least one
15077 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15078 Including both a @option{-files} switch and one or more
15079 @var{filename} arguments is permitted.
15081 @item
15082 @samp{@var{gcc_switches}} is a list of switches for
15083 @command{gcc}. They will be passed on to all compiler invocations made by
15084 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15085 @option{-I} switches to form the source search path,
15086 and use the @option{-gnatec} switch to set the configuration file,
15087 use the @option{-gnat05} switch if sources should be compiled in
15088 Ada 2005 mode etc.
15089 @end itemize
15091 @node Switches for gnatmetric
15092 @section Switches for @command{gnatmetric}
15094 @noindent
15095 The following subsections describe the various switches accepted by
15096 @command{gnatmetric}, organized by category.
15098 @menu
15099 * Output Files Control::
15100 * Disable Metrics For Local Units::
15101 * Specifying a set of metrics to compute::
15102 * Other gnatmetric Switches::
15103 @ignore
15104 * Generate project-wide metrics::
15105 @end ignore
15106 @end menu
15108 @node Output Files Control
15109 @subsection Output File Control
15110 @cindex Output file control in @command{gnatmetric}
15112 @noindent
15113 @command{gnatmetric} has two output formats. It can generate a
15114 textual (human-readable) form, and also XML. By default only textual
15115 output is generated.
15117 When generating the output in textual form, @command{gnatmetric} creates
15118 for each Ada source file a corresponding text file
15119 containing the computed metrics, except for the case when the set of metrics
15120 specified by gnatmetric parameters consists only of metrics that are computed
15121 for the whole set of analyzed sources, but not for each Ada source.
15122 By default, the name of the file containing metric information for a source
15123 is obtained by appending the @file{.metrix} suffix to the
15124 name of the input source file. If not otherwise specified and no project file
15125 is specified as @command{gnatmetric} option this file is placed in the same
15126 directory as where the source file is located. If @command{gnatmetric} has a
15127 project  file as its parameter, it places all the generated files in the
15128 object directory of the project (or in the project source directory if the
15129 project does not define an objects directory), if @option{--subdirs} option
15130 is specified, the files are placed in the subrirectory of this directory
15131 specified by this option.
15133 All the output information generated in XML format is placed in a single
15134 file. By default the name of this file is @file{metrix.xml}.
15135 If not otherwise specified and if no project file is specified
15136 as @command{gnatmetric} option  this file is placed in the
15137 current directory.
15139 Some of the computed metrics are summed over the units passed to
15140 @command{gnatmetric}; for example, the total number of lines of code.
15141 By default this information is sent to @file{stdout}, but a file
15142 can be specified with the @option{-og} switch.
15144 The following switches control the @command{gnatmetric} output:
15146 @table @option
15147 @cindex @option{-x} (@command{gnatmetric})
15148 @item -x
15149 Generate the XML output
15151 @cindex @option{-xs} (@command{gnatmetric})
15152 @item -xs
15153 Generate the XML output and the XML schema file that describes the structure
15154 of the XML metric report, this schema is assigned to the XML file. The schema
15155 file has the same name as the XML output file with @file{.xml} suffix replaced
15156 with @file{.xsd}
15158 @cindex @option{-nt} (@command{gnatmetric})
15159 @item -nt
15160 Do not generate the output in text form (implies @option{-x})
15162 @cindex @option{-d} (@command{gnatmetric})
15163 @item -d @var{output_dir}
15164 Put text files with detailed metrics into @var{output_dir}
15166 @cindex @option{-o} (@command{gnatmetric})
15167 @item -o @var{file_suffix}
15168 Use @var{file_suffix}, instead of @file{.metrix}
15169 in the name of the output file.
15171 @cindex @option{-og} (@command{gnatmetric})
15172 @item -og @var{file_name}
15173 Put global metrics into @var{file_name}
15175 @cindex @option{-ox} (@command{gnatmetric})
15176 @item -ox @var{file_name}
15177 Put the XML output into @var{file_name} (also implies @option{-x})
15179 @cindex @option{-sfn} (@command{gnatmetric})
15180 @item -sfn
15181 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15182 output includes the name(s) of the Ada source file(s) from which the metrics
15183 are computed.  By default each name includes the absolute path. The
15184 @option{-sfn} switch causes @command{gnatmetric}
15185 to exclude all directory information from the file names that are output.)
15187 @end table
15189 @node Disable Metrics For Local Units
15190 @subsection Disable Metrics For Local Units
15191 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15193 @noindent
15194 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15195 one compilation
15196 unit per one source file. It computes line metrics for the whole source
15197 file, and it also computes syntax
15198 and complexity metrics for the file's outermost unit.
15200 By default, @command{gnatmetric} will also compute all metrics for certain
15201 kinds of locally declared program units:
15203 @itemize @bullet
15204 @item
15205 subprogram (and generic subprogram) bodies;
15207 @item
15208 package (and generic package) specs and bodies;
15210 @item
15211 task object and type specifications and bodies;
15213 @item
15214 protected object and type specifications and bodies.
15215 @end itemize
15217 @noindent
15218 These kinds of entities will be referred to as
15219 @emph{eligible local program units}, or simply @emph{eligible local units},
15220 @cindex Eligible local unit (for @command{gnatmetric})
15221 in the discussion below.
15223 Note that a subprogram declaration, generic instantiation,
15224 or renaming declaration only receives metrics
15225 computation when it appear as the outermost entity
15226 in a source file.
15228 Suppression of metrics computation for eligible local units can be
15229 obtained via the following switch:
15231 @table @option
15232 @cindex @option{-nolocal} (@command{gnatmetric})
15233 @item -nolocal
15234 Do not compute detailed metrics for eligible local program units
15236 @end table
15238 @node Specifying a set of metrics to compute
15239 @subsection Specifying a set of metrics to compute
15241 @noindent
15242 By default all the metrics are computed and reported. The switches
15243 described in this subsection allow you to control, on an individual
15244 basis, whether metrics are computed and
15245 reported. If at least one positive metric
15246 switch is specified (that is, a switch that defines that a given
15247 metric or set of metrics is to be computed), then only
15248 explicitly specified metrics are reported.
15250 @menu
15251 * Line Metrics Control::
15252 * Syntax Metrics Control::
15253 * Complexity Metrics Control::
15254 * Coupling Metrics Control::
15255 @end menu
15257 @node Line Metrics Control
15258 @subsubsection Line Metrics Control
15259 @cindex Line metrics control in @command{gnatmetric}
15261 @noindent
15262 For any (legal) source file, and for each of its
15263 eligible local program units, @command{gnatmetric} computes the following
15264 metrics:
15266 @itemize @bullet
15267 @item
15268 the total number of lines;
15270 @item
15271 the total number of code lines (i.e., non-blank lines that are not comments)
15273 @item
15274 the number of comment lines
15276 @item
15277 the number of code lines containing end-of-line comments;
15279 @item
15280 the comment percentage: the ratio between the number of lines that contain
15281 comments and the number of all non-blank lines, expressed as a percentage;
15283 @item
15284 the number of empty lines and lines containing only space characters and/or
15285 format effectors (blank lines)
15287 @item
15288 the average number of code lines in subprogram bodies, task bodies, entry
15289 bodies and statement sequences in package bodies (this metric is only computed
15290 across the whole set of the analyzed units)
15292 @end itemize
15294 @noindent
15295 @command{gnatmetric} sums the values of the line metrics for all the
15296 files being processed and then generates the cumulative results. The tool
15297 also computes for all the files being processed the average number of code
15298 lines in bodies.
15300 You can use the following switches to select the specific line metrics
15301 to be computed and reported.
15303 @table @option
15304 @cindex @option{--lines@var{x}} (@command{gnatmetric})
15306 @cindex @option{--no-lines@var{x}}
15308 @item --lines-all
15309 Report all the line metrics
15311 @item --no-lines-all
15312 Do not report any of line metrics
15314 @item --lines
15315 Report the number of all lines
15317 @item --no-lines
15318 Do not report the number of all lines
15320 @item --lines-code
15321 Report the number of code lines
15323 @item --no-lines-code
15324 Do not report the number of code lines
15326 @item --lines-comment
15327 Report the number of comment lines
15329 @item --no-lines-comment
15330 Do not report the number of comment lines
15332 @item --lines-eol-comment
15333 Report the number of code lines containing
15334 end-of-line comments
15336 @item --no-lines-eol-comment
15337 Do not report the number of code lines containing
15338 end-of-line comments
15340 @item --lines-ratio
15341 Report the comment percentage in the program text
15343 @item --no-lines-ratio
15344 Do not report the comment percentage in the program text
15346 @item --lines-blank
15347 Report the number of blank lines
15349 @item --no-lines-blank
15350 Do not report the number of blank lines
15352 @item --lines-average
15353 Report the average number of code lines in subprogram bodies, task bodies,
15354 entry bodies and statement sequences in package bodies. The metric is computed
15355 and reported for the whole set of processed Ada sources only.
15357 @item --no-lines-average
15358 Do not report the average number of code lines in subprogram bodies,
15359 task bodies, entry bodies and statement sequences in package bodies.
15361 @end table
15363 @node Syntax Metrics Control
15364 @subsubsection Syntax Metrics Control
15365 @cindex Syntax metrics control in @command{gnatmetric}
15367 @noindent
15368 @command{gnatmetric} computes various syntactic metrics for the
15369 outermost unit and for each eligible local unit:
15371 @table @emph
15372 @item LSLOC (``Logical Source Lines Of Code'')
15373 The total number of declarations and the total number of statements. Note
15374 that the definition of declarations is the one given in the reference
15375 manual:
15377 @noindent
15378 ``Each of the following is defined to be a declaration: any basic_declaration;
15379 an enumeration_literal_specification; a discriminant_specification;
15380 a component_declaration; a loop_parameter_specification; a
15381 parameter_specification; a subprogram_body; an entry_declaration;
15382 an entry_index_specification; a choice_parameter_specification;
15383 a generic_formal_parameter_declaration.''
15385 This means for example that each enumeration literal adds one to the count,
15386 as well as each subprogram parameter.
15388 Thus the results from this metric will be significantly greater than might
15389 be expected from a naive view of counting semicolons.
15391 @item Maximal static nesting level of inner program units
15392 According to
15393 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15394 package, a task unit, a protected unit, a
15395 protected entry, a generic unit, or an explicitly declared subprogram other
15396 than an enumeration literal.''
15398 @item Maximal nesting level of composite syntactic constructs
15399 This corresponds to the notion of the
15400 maximum nesting level in the GNAT built-in style checks
15401 (@pxref{Style Checking})
15402 @end table
15404 @noindent
15405 For the outermost unit in the file, @command{gnatmetric} additionally computes
15406 the following metrics:
15408 @table @emph
15409 @item Public subprograms
15410 This metric is computed for package specs. It is the
15411 number of subprograms and generic subprograms declared in the visible
15412 part (including the visible part of nested packages, protected objects, and
15413 protected types).
15415 @item All subprograms
15416 This metric is computed for bodies and subunits. The
15417 metric is equal to a total number of subprogram bodies in the compilation
15418 unit.
15419 Neither generic instantiations nor renamings-as-a-body nor body stubs
15420 are counted. Any subprogram body is counted, independently of its nesting
15421 level and enclosing constructs. Generic bodies and bodies of protected
15422 subprograms are counted in the same way as ``usual'' subprogram bodies.
15424 @item Public types
15425 This metric is computed for package specs and
15426 generic package declarations. It is the total number of types
15427 that can be referenced from outside this compilation unit, plus the
15428 number of types from all the visible parts of all the visible generic
15429 packages. Generic formal types are not counted.  Only types, not subtypes,
15430 are included.
15432 @noindent
15433 Along with the total number of public types, the following
15434 types are counted and reported separately:
15436 @itemize @bullet
15437 @item
15438 Abstract types
15440 @item
15441 Root tagged types (abstract, non-abstract, private, non-private). Type
15442 extensions are @emph{not} counted
15444 @item
15445 Private types (including private extensions)
15447 @item
15448 Task types
15450 @item
15451 Protected types
15453 @end itemize
15455 @item All types
15456 This metric is computed for any compilation unit. It is equal to the total
15457 number of the declarations of different types given in the compilation unit.
15458 The private and the corresponding full type declaration are counted as one
15459 type declaration. Incomplete type declarations and generic formal types
15460 are not counted.
15461 No distinction is made among different kinds of types (abstract,
15462 private etc.); the total number of types is computed and reported.
15464 @end table
15466 @noindent
15467 By default, all the syntax metrics are computed and reported. You can use the
15468 following switches to select specific syntax metrics.
15470 @table @option
15472 @cindex @option{--syntax@var{x}} (@command{gnatmetric})
15474 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15476 @item --syntax-all
15477 Report all the syntax metrics
15479 @item --no-syntax-all
15480 Do not report any of syntax metrics
15482 @item --declarations
15483 Report the total number of declarations
15485 @item --no-declarations
15486 Do not report the total number of declarations
15488 @item --statements
15489 Report the total number of statements
15491 @item --no-statements
15492 Do not report the total number of statements
15494 @item --public-subprograms
15495 Report the number of public subprograms in a compilation unit
15497 @item --no-public-subprograms
15498 Do not report the number of public subprograms in a compilation unit
15500 @item --all-subprograms
15501 Report the number of all the subprograms in a compilation unit
15503 @item --no-all-subprograms
15504 Do not report the number of all the subprograms in a compilation unit
15506 @item --public-types
15507 Report the number of public types in a compilation unit
15509 @item --no-public-types
15510 Do not report the number of public types in a compilation unit
15512 @item --all-types
15513 Report the number of all the types in a compilation unit
15515 @item --no-all-types
15516 Do not report the number of all the types in a compilation unit
15518 @item --unit-nesting
15519 Report the maximal program unit nesting level
15521 @item --no-unit-nesting
15522 Do not report the maximal program unit nesting level
15524 @item --construct-nesting
15525 Report the maximal construct nesting level
15527 @item --no-construct-nesting
15528 Do not report the maximal construct nesting level
15530 @end table
15532 @node Complexity Metrics Control
15533 @subsubsection Complexity Metrics Control
15534 @cindex Complexity metrics control in @command{gnatmetric}
15536 @noindent
15537 For a program unit that is an executable body (a subprogram body (including
15538 generic bodies), task body, entry body or a package body containing
15539 its own statement sequence) @command{gnatmetric} computes the following
15540 complexity metrics:
15542 @itemize @bullet
15543 @item
15544 McCabe cyclomatic complexity;
15546 @item
15547 McCabe essential complexity;
15549 @item
15550 maximal loop nesting level;
15552 @item
15553 extra exit points (for subprograms);
15554 @end itemize
15556 @noindent
15557 The McCabe cyclomatic complexity metric is defined
15558 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15560 According to McCabe, both control statements and short-circuit control forms
15561 should be taken into account when computing cyclomatic complexity.
15562 For Ada 2012 we have also take into account conditional expressions
15563 and quantified expressions. For each body, we compute three metric values:
15565 @itemize @bullet
15566 @item
15567 the complexity introduced by control
15568 statements only, without taking into account short-circuit forms
15569 (referred as @code{statement complexity} in @command{gnatmetric} output),
15571 @item
15572 the complexity introduced by short-circuit control forms only
15573 (referred as @code{expression complexity} in @command{gnatmetric} output), and
15575 @item
15576 the total
15577 cyclomatic complexity, which is the sum of these two values
15578 (referred as @code{cyclomatic complexity} in @command{gnatmetric} output).
15579 @end itemize
15581 @noindent
15583 The cyclomatic complexity is also computed for Ada 2012 expression functions.
15584 An expression function cannot have statements as its components, so only one
15585 metric value is computed as a cyclomatic complexity of an expression function.
15587 The origin of cyclomatic complexity metric is the need to estimate the number
15588 of independent paths in the control flow graph that in turn gives the number
15589 of tests needed to satisfy paths coverage testing completeness criterion.
15590 Considered from the testing point of view, a static Ada @code{loop} (that is,
15591 the @code{loop} statement having static subtype in loop parameter
15592 specification) does not add to cyclomatic complexity. By providing
15593 @option{--no-static-loop} option a user
15594 may specify that such loops should not be counted when computing the
15595 cyclomatic complexity metric
15597 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
15598 counted for the code that is reduced by excluding all the pure structural Ada
15599 control statements. An compound statement is considered as a non-structural
15600 if it contains a @code{raise} or @code{return} statement as it subcomponent,
15601 or if it contains a @code{goto} statement that transfers the control outside
15602 the operator. A selective accept statement with @code{terminate} alternative
15603 is considered as non-structural statement. When computing this metric,
15604 @code{exit} statements are treated in the same way as @code{goto}
15605 statements unless @option{-ne} option is specified.
15607 The Ada essential complexity metric defined here is intended to quantify
15608 the extent to which the software is unstructured. It is adapted from
15609 the McCabe essential complexity metric defined in
15610 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
15611 suitable for typical Ada usage. For example, short circuit forms
15612 are not penalized as unstructured in the Ada essential complexity metric.
15614 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15615 the code in the exception handlers and in all the nested program units. The
15616 code of assertions and predicates (that is, subprogram preconditions and
15617 postconditions, subtype predicates and type invariants) is also skipped.
15619 By default, all the complexity metrics are computed and reported.
15620 For more fine-grained control you can use
15621 the following switches:
15623 @table @option
15624 @cindex @option{-complexity@var{x}} (@command{gnatmetric})
15626 @cindex @option{--no-complexity@var{x}}
15628 @item --complexity-all
15629 Report all the complexity metrics
15631 @item --no-complexity-all
15632 Do not report any of complexity metrics
15634 @item --complexity-cyclomatic
15635 Report the McCabe Cyclomatic Complexity
15637 @item --no-complexity-cyclomatic
15638 Do not report the McCabe Cyclomatic Complexity
15640 @item --complexity-essential
15641 Report the Essential Complexity
15643 @item --no-complexity-essential
15644 Do not report the Essential Complexity
15646 @item --loop-nesting
15647 Report maximal loop nesting level
15649 @item --no-loop-nesting
15650 Do not report maximal loop nesting level
15652 @item --complexity-average
15653 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15654 task bodies, entry bodies and statement sequences in package bodies.
15655 The metric is computed and reported for whole set of processed Ada sources
15656 only.
15658 @item --no-complexity-average
15659 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15660 bodies, task bodies, entry bodies and statement sequences in package bodies
15662 @cindex @option{-ne} (@command{gnatmetric})
15663 @item -ne
15664 Do not consider @code{exit} statements as @code{goto}s when
15665 computing Essential Complexity
15667 @cindex @option{--no-static-loop} (@command{gnatmetric})
15668 @item --no-static-loop
15669 Do not consider static loops when computing cyclomatic complexity
15671 @item --extra-exit-points
15672 Report the extra exit points for subprogram bodies. As an exit point, this
15673 metric counts @code{return} statements and raise statements in case when the
15674 raised exception is not handled in the same body. In case of a function this
15675 metric subtracts 1 from the number of exit points, because a function body
15676 must contain at least one @code{return} statement.
15678 @item --no-extra-exit-points
15679 Do not report the extra exit points for subprogram bodies
15680 @end table
15683 @node Coupling Metrics Control
15684 @subsubsection Coupling Metrics Control
15685 @cindex Coupling metrics control in @command{gnatmetric}
15687 @noindent
15688 @cindex Coupling metrics (in @command{gnatmetric})
15689 Coupling metrics measure the dependencies between a given entity and other
15690 entities in the program. This information is useful since high coupling
15691 may signal potential issues with maintainability as the program evolves.
15693 @command{gnatmetric} computes the following coupling metrics:
15695 @itemize @bullet
15697 @item
15698 @emph{object-oriented coupling}, for classes in traditional object-oriented
15699 sense;
15701 @item
15702 @emph{unit coupling}, for all the program units making up a program;
15704 @item
15705 @emph{control coupling}, reflecting dependencies between a unit and
15706 other units that contain subprograms.
15707 @end itemize
15709 @noindent
15710 Two kinds of coupling metrics are computed:
15712 @itemize @bullet
15713 @item fan-out coupling (``efferent coupling''):
15714 @cindex fan-out coupling
15715 @cindex efferent coupling
15716 the number of entities the given entity depends upon. This metric
15717 reflects how the given entity depends on the changes in the
15718 ``external world''.
15720 @item fan-in coupling (``afferent'' coupling):
15721 @cindex fan-in coupling
15722 @cindex afferent coupling
15723 the number of entities that depend on a given entity.
15724 This metric reflects how the ``external world'' depends on the changes in a
15725 given entity.
15726 @end itemize
15728 @noindent
15729 Object-oriented coupling metrics measure the dependencies
15730 between a given class (or a group of classes) and the other classes in the
15731 program. In this subsection the term ``class'' is used in its traditional
15732 object-oriented programming sense (an instantiable module that contains data
15733 and/or method members). A @emph{category} (of classes) is a group of closely
15734 related classes that are reused and/or modified together.
15736 A class @code{K}'s fan-out coupling is the number of classes
15737 that @code{K} depends upon.
15738 A category's fan-out coupling is the number of classes outside the
15739 category that the classes inside the category depend upon.
15741 A class @code{K}'s fan-in coupling is the number of classes
15742 that depend upon @code{K}.
15743 A category's fan-in coupling is the number of classes outside the
15744 category that depend on classes belonging to the category.
15746 Ada's object-oriented paradigm separates the instantiable entity
15747 (type) from the module (package), so the definition of the coupling
15748 metrics for Ada maps the class and class category notions
15749 onto Ada constructs.
15751 For the coupling metrics, several kinds of modules that define a tagged type
15752 or an interface type  -- library packages, library generic packages, and
15753 library generic package instantiations -- are considered to be classes.
15754 A category consists of a library package (or
15755 a library generic package) that defines a tagged or an interface type,
15756 together with all its descendant (generic) packages that define tagged
15757 or interface types. Thus a
15758 category is an Ada hierarchy of library-level program units. Class
15759 coupling in Ada is referred to as ``tagged coupling'', and category coupling
15760 is referred to as ``hierarchy coupling''.
15762 For any package serving as a class, its body and subunits (if any) are
15763 considered together with its spec when computing dependencies, and coupling
15764 metrics are reported for spec units only. Dependencies between classes
15765 mean Ada semantic dependencies. For object-oriented coupling
15766 metrics, only dependencies on units treated as classes are
15767 considered.
15769 Similarly, for unit and control coupling an entity is considered to be the
15770 conceptual construct consisting of the entity's specification, body, and
15771 any subunits (transitively).
15772 @command{gnatmetric} computes
15773 the dependencies of all these units as a whole, but
15774 metrics are only reported for spec
15775 units (or for a subprogram body unit in case if there is no
15776 separate spec for the given subprogram).
15778 For unit coupling, dependencies are computed between all kinds of program
15779 units. For control coupling, the dependencies of a given unit are limited to
15780 those units that define subprograms. Thus control fan-out coupling is reported
15781 for all units, but control fan-in coupling is only reported for units
15782 that define subprograms.
15784 The following simple example illustrates the difference between unit coupling
15785 and control coupling metrics:
15787 @smallexample @c ada
15788 @group
15789 @b{package} Lib_1 @b{is}
15790     @b{function} F_1 (I : Integer) @b{return} Integer;
15791 @b{end} Lib_1;
15792 @end group
15794 @group
15795 @b{package} Lib_2 @b{is}
15796     @b{type} T_2 @b{is} @b{new} Integer;
15797 @b{end} Lib_2;
15798 @end group
15800 @group
15801 @b{package} @b{body} Lib_1 @b{is}
15802     @b{function} F_1 (I : Integer) @b{return} Integer @b{is}
15803     @b{begin}
15804        @b{return} I + 1;
15805     @b{end} F_1;
15806 @b{end} Lib_1;
15807 @end group
15809 @group
15810 @b{with} Lib_2; @b{use} Lib_2;
15811 @b{package} Pack @b{is}
15812     Var : T_2;
15813     @b{function} Fun (I : Integer) @b{return} Integer;
15814 @b{end} Pack;
15815 @end group
15817 @group
15818 @b{with} Lib_1; @b{use} Lib_1;
15819 @b{package} @b{body} Pack @b{is}
15820     @b{function} Fun (I : Integer) @b{return} Integer @b{is}
15821     @b{begin}
15822        @b{return} F_1 (I);
15823     @b{end} Fun;
15824 @b{end} Pack;
15825 @end group
15826 @end smallexample
15828 @noindent
15829 If we apply @command{gnatmetric} with the @option{--coupling-all} option to
15830 these units, the result will be:
15832 @smallexample
15833 @group
15834 Coupling metrics:
15835 =================
15836     Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
15837        control fan-out coupling  : 0
15838        control fan-in coupling   : 1
15839        unit fan-out coupling     : 0
15840        unit fan-in coupling      : 1
15841 @end group
15843 @group
15844     Unit Pack (C:\customers\662\L406-007\pack.ads)
15845        control fan-out coupling  : 1
15846        control fan-in coupling   : 0
15847        unit fan-out coupling     : 2
15848        unit fan-in coupling      : 0
15849 @end group
15851 @group
15852     Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
15853        control fan-out coupling  : 0
15854        unit fan-out coupling     : 0
15855        unit fan-in coupling      : 1
15856 @end group
15857 @end smallexample
15859 @noindent
15860 The result does not contain values for object-oriented
15861 coupling because none of the argument units contains a tagged type and
15862 therefore none of these units can be treated as a class.
15864 The @code{Pack} package (spec and body) depends on two
15865 units -- @code{Lib_1} @code{and Lib_2} -- and so its unit fan-out coupling
15866 is 2. Since nothing depends on it, its unit fan-in coupling is 0, as
15867 is its control fan-in coupling. Only one of the units @code{Pack} depends
15868 upon defines a subprogram, so its control fan-out coupling is 1.
15870 @code{Lib_2} depends on nothing, so its fan-out metrics are 0. It does
15871 not define any subprograms, so it has no control fan-in metric.
15872 One unit (@code{Pack}) depends on it , so its unit fan-in coupling is 1.
15874 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
15875 Its control fan-in coupling is 1 (because there is one unit
15876 depending on it).
15878 When computing coupling metrics, @command{gnatmetric} counts only
15879 dependencies between units that are arguments of the @command{gnatmetric}
15880 invocation. Coupling metrics are program-wide (or project-wide) metrics, so
15881 you should invoke @command{gnatmetric} for
15882 the complete set of sources comprising your program. This can be done
15883 by invoking @command{gnatmetric} with the corresponding project file
15884 and with the @option{-U} option.
15886 By default, all the coupling metrics are disabled. You can use the following
15887 switches to specify the coupling metrics to be computed and reported:
15889 @table @option
15891 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
15892 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
15893 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
15894 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
15897 @item --coupling-all
15898 Report all the coupling metrics
15900 @item --tagged-coupling-out
15901 Report tagged (class) fan-out coupling
15903 @item --tagged-coupling-in
15904 Report tagged (class) fan-in coupling
15906 @item --hierarchy-coupling-out
15907 Report hierarchy (category) fan-out coupling
15909 @item --hierarchy-coupling-in
15910 Report hierarchy (category) fan-in coupling
15912 @item --unit-coupling-out
15913 Report unit fan-out coupling
15915 @item --unit-coupling-in
15916 Report unit fan-in coupling
15918 @item --control-coupling-out
15919 Report control fan-out coupling
15921 @item --control-coupling-in
15922 Report control fan-in coupling
15923 @end table
15925 @node Other gnatmetric Switches
15926 @subsection Other @code{gnatmetric} Switches
15928 @noindent
15929 Additional @command{gnatmetric} switches are as follows:
15931 @table @option
15932 @item --version
15933 @cindex @option{--version} @command{gnatmetric}
15934 Display Copyright and version, then exit disregarding all other options.
15936 @item --help
15937 @cindex @option{--help} @command{gnatmetric}
15938 Display usage, then exit disregarding all other options.
15940 @item -P @var{file}
15941 @cindex @option{-P} @command{gnatmetric}
15942 Indicates the name of the project file that describes the set of sources
15943 to be processed. The exact set of argument sources depends on other options
15944 specified, see below.
15946 @item -U
15947 @cindex @option{-U} @command{gnatmetric}
15948 If a project file is specified and no argument source is explicitly
15949 specified (either directly or by means of @option{-files} option), process
15950 all the units of the closure of the argument project. Otherwise this option
15951 has no effect.
15953 @item -U @var{main_unit}
15954 If a project file is specified and no argument source is explicitly
15955 specified (either directly or by means of @option{-files} option), process
15956 the closure of units rooted at @var{main_unit}. Otherwise this option
15957 has no effect.
15959 @item -X@var{name}=@var{value}
15960 @cindex @option{-X} @command{gnatmetric}
15961 Indicates that external variable @var{name} in the argument project
15962 has the value @var{value}. Has no effect if no project is specified as
15963 tool argument.
15965 @item --RTS=@var{rts-path}
15966 @cindex @option{--RTS} (@command{gnatmetric})
15967 Specifies the default location of the runtime library. Same meaning as the
15968 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15970 @item --subdirs=@var{dir}
15971 @cindex @option{--subdirs=@var{dir}} @command{gnatmetric}
15972 Use the specified subdirectory of the project objects file (or of the
15973 project file directory if the project does not specify an object directory)
15974 for tool output files. Has no effect if no project is specified as
15975 tool argument r if @option{--no_objects_dir} is specified.
15977 @item --no_objects_dir
15978 @cindex @option{--no_objects_dir} @command{gnatmetric}
15979 Place all the result files into the current directory instead of
15980 project objects directory. This corresponds to the @command{gnatcheck}
15981 behavior when it is called with the project file from the
15982 GNAT driver. Has no effect if no project is specified.
15984 @item -files @var{filename}
15985 @cindex @option{-files} (@code{gnatmetric})
15986 Take the argument source files from the specified file. This file should be an
15987 ordinary text file containing file names separated by spaces or
15988 line breaks. You can use this switch more than once in the same call to
15989 @command{gnatmetric}. You also can combine this switch with
15990 an explicit list of files.
15992 @item -j@var{n}
15993 @cindex @option{-j} (@command{gnatmetric})
15994 Use @var{n} processes to carry out the tree creations (internal representations
15995 of the argument sources). On a multiprocessor machine this speeds up processing
15996 of big sets of argument sources. If @var{n} is 0, then the maximum number of
15997 parallel tree creations is the number of core processors on the platform.
15999 @cindex @option{-t} (@command{gnatmetric})
16000 @item -t
16001 Print out execution time.
16003 @item -v
16004 @cindex @option{-v} (@command{gnatmetric})
16005 Verbose mode;
16006 @command{gnatmetric} generates version information and then
16007 a trace of sources being processed.
16009 @item -q
16010 @cindex @option{-q} (@command{gnatmetric})
16011 Quiet mode.
16012 @end table
16014 @noindent
16015 If a project file is specified and no argument source is explicitly
16016 specified (either directly or by means of @option{-files} option), and no
16017 @option{-U} is specified, then the set of processed sources is
16018 all the immediate units of the argument project.
16021 @ignore
16022 @node Generate project-wide metrics
16023 @subsection Generate project-wide metrics
16025 In order to compute metrics on all units of a given project, you can use
16026 the @command{gnat} driver along with the @option{-P} option:
16027 @smallexample
16028    gnat metric -Pproj
16029 @end smallexample
16031 @noindent
16032 If the project @code{proj} depends upon other projects, you can compute
16033 the metrics on the project closure using the @option{-U} option:
16034 @smallexample
16035    gnat metric -Pproj -U
16036 @end smallexample
16038 @noindent
16039 Finally, if not all the units are relevant to a particular main
16040 program in the project closure, you can generate metrics for the set
16041 of units needed to create a given main program (unit closure) using
16042 the @option{-U} option followed by the name of the main unit:
16043 @smallexample
16044    gnat metric -Pproj -U main
16045 @end smallexample
16046 @end ignore
16047 @end ifclear
16050 @c ***********************************
16051 @node File Name Krunching with gnatkr
16052 @chapter File Name Krunching with @code{gnatkr}
16053 @findex gnatkr
16055 @noindent
16056 This chapter discusses the method used by the compiler to shorten
16057 the default file names chosen for Ada units so that they do not
16058 exceed the maximum length permitted. It also describes the
16059 @code{gnatkr} utility that can be used to determine the result of
16060 applying this shortening.
16061 @menu
16062 * About gnatkr::
16063 * Using gnatkr::
16064 * Krunching Method::
16065 * Examples of gnatkr Usage::
16066 @end menu
16068 @node About gnatkr
16069 @section About @code{gnatkr}
16071 @noindent
16072 The default file naming rule in GNAT
16073 is that the file name must be derived from
16074 the unit name. The exact default rule is as follows:
16075 @itemize @bullet
16076 @item
16077 Take the unit name and replace all dots by hyphens.
16078 @item
16079 If such a replacement occurs in the
16080 second character position of a name, and the first character is
16081 @samp{a}, @samp{g}, @samp{s}, or @samp{i},
16082 then replace the dot by the character
16083 @samp{~} (tilde)
16084 instead of a minus.
16085 @end itemize
16086 The reason for this exception is to avoid clashes
16087 with the standard names for children of System, Ada, Interfaces,
16088 and GNAT, which use the prefixes
16089 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
16090 respectively.
16092 The @option{-gnatk@var{nn}}
16093 switch of the compiler activates a ``krunching''
16094 circuit that limits file names to nn characters (where nn is a decimal
16095 integer). For example, using OpenVMS,
16096 where the maximum file name length is
16097 39, the value of nn is usually set to 39, but if you want to generate
16098 a set of files that would be usable if ported to a system with some
16099 different maximum file length, then a different value can be specified.
16100 The default value of 39 for OpenVMS need not be specified.
16102 The @code{gnatkr} utility can be used to determine the krunched name for
16103 a given file, when krunched to a specified maximum length.
16105 @node Using gnatkr
16106 @section Using @code{gnatkr}
16108 @noindent
16109 The @code{gnatkr} command has the form
16111 @smallexample
16112 @c $ gnatkr @var{name} @ovar{length}
16113 @c Expanding @ovar macro inline (explanation in macro def comments)
16114 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16115 @end smallexample
16118 @noindent
16119 @var{name} is the uncrunched file name, derived from the name of the unit
16120 in the standard manner described in the previous section (i.e., in particular
16121 all dots are replaced by hyphens). The file name may or may not have an
16122 extension (defined as a suffix of the form period followed by arbitrary
16123 characters other than period). If an extension is present then it will
16124 be preserved in the output. For example, when krunching @file{hellofile.ads}
16125 to eight characters, the result will be hellofil.ads.
16127 Note: for compatibility with previous versions of @code{gnatkr} dots may
16128 appear in the name instead of hyphens, but the last dot will always be
16129 taken as the start of an extension. So if @code{gnatkr} is given an argument
16130 such as @file{Hello.World.adb} it will be treated exactly as if the first
16131 period had been a hyphen, and for example krunching to eight characters
16132 gives the result @file{hellworl.adb}.
16134 Note that the result is always all lower case (except on OpenVMS where it is
16135 all upper case). Characters of the other case are folded as required.
16137 @var{length} represents the length of the krunched name. The default
16138 when no argument is given is 8 characters. A length of zero stands for
16139 unlimited, in other words do not chop except for system files where the
16140 implied crunching length is always eight characters.
16142 @noindent
16143 The output is the krunched name. The output has an extension only if the
16144 original argument was a file name with an extension.
16146 @node Krunching Method
16147 @section Krunching Method
16149 @noindent
16150 The initial file name is determined by the name of the unit that the file
16151 contains. The name is formed by taking the full expanded name of the
16152 unit and replacing the separating dots with hyphens and
16153 using lowercase
16154 for all letters, except that a hyphen in the second character position is
16155 replaced by a tilde if the first character is
16156 @samp{a}, @samp{i}, @samp{g}, or @samp{s}.
16157 The extension is @code{.ads} for a
16158 spec and @code{.adb} for a body.
16159 Krunching does not affect the extension, but the file name is shortened to
16160 the specified length by following these rules:
16162 @itemize @bullet
16163 @item
16164 The name is divided into segments separated by hyphens, tildes or
16165 underscores and all hyphens, tildes, and underscores are
16166 eliminated. If this leaves the name short enough, we are done.
16168 @item
16169 If the name is too long, the longest segment is located (left-most
16170 if there are two of equal length), and shortened by dropping
16171 its last character. This is repeated until the name is short enough.
16173 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16174 to fit the name into 8 characters as required by some operating systems.
16176 @smallexample
16177 our-strings-wide_fixed 22
16178 our strings wide fixed 19
16179 our string  wide fixed 18
16180 our strin   wide fixed 17
16181 our stri    wide fixed 16
16182 our stri    wide fixe  15
16183 our str     wide fixe  14
16184 our str     wid  fixe  13
16185 our str     wid  fix   12
16186 ou  str     wid  fix   11
16187 ou  st      wid  fix   10
16188 ou  st      wi   fix   9
16189 ou  st      wi   fi    8
16190 Final file name: oustwifi.adb
16191 @end smallexample
16193 @item
16194 The file names for all predefined units are always krunched to eight
16195 characters. The krunching of these predefined units uses the following
16196 special prefix replacements:
16198 @table @file
16199 @item ada-
16200 replaced by @file{a-}
16202 @item gnat-
16203 replaced by @file{g-}
16205 @item interfaces-
16206 replaced by @file{i-}
16208 @item system-
16209 replaced by @file{s-}
16210 @end table
16212 These system files have a hyphen in the second character position. That
16213 is why normal user files replace such a character with a
16214 tilde, to
16215 avoid confusion with system file names.
16217 As an example of this special rule, consider
16218 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16220 @smallexample
16221 ada-strings-wide_fixed 22
16222 a-  strings wide fixed 18
16223 a-  string  wide fixed 17
16224 a-  strin   wide fixed 16
16225 a-  stri    wide fixed 15
16226 a-  stri    wide fixe  14
16227 a-  str     wide fixe  13
16228 a-  str     wid  fixe  12
16229 a-  str     wid  fix   11
16230 a-  st      wid  fix   10
16231 a-  st      wi   fix   9
16232 a-  st      wi   fi    8
16233 Final file name: a-stwifi.adb
16234 @end smallexample
16235 @end itemize
16237 Of course no file shortening algorithm can guarantee uniqueness over all
16238 possible unit names, and if file name krunching is used then it is your
16239 responsibility to ensure that no name clashes occur. The utility
16240 program @code{gnatkr} is supplied for conveniently determining the
16241 krunched name of a file.
16243 @node Examples of gnatkr Usage
16244 @section Examples of @code{gnatkr} Usage
16246 @smallexample
16247 @iftex
16248 @leftskip=0cm
16249 @end iftex
16250 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16251 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16252 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16253 $ gnatkr grandparent-parent-child     --> grparchi
16254 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16255 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16256 @end smallexample
16258 @node Preprocessing with gnatprep
16259 @chapter Preprocessing with @code{gnatprep}
16260 @findex gnatprep
16262 @noindent
16263 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16264 preprocessing.
16265 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16266 special GNAT features.
16267 For further discussion of conditional compilation in general, see
16268 @ref{Conditional Compilation}.
16270 @menu
16271 * Preprocessing Symbols::
16272 * Using gnatprep::
16273 * Switches for gnatprep::
16274 * Form of Definitions File::
16275 * Form of Input Text for gnatprep::
16276 @end menu
16278 @node Preprocessing Symbols
16279 @section Preprocessing Symbols
16281 @noindent
16282 Preprocessing symbols are defined in definition files and referred to in
16283 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16284 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16285 all characters need to be in the ASCII set (no accented letters).
16287 @node Using gnatprep
16288 @section Using @code{gnatprep}
16290 @noindent
16291 To call @code{gnatprep} use
16293 @smallexample
16294 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16295 @c Expanding @ovar macro inline (explanation in macro def comments)
16296 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16297 @end smallexample
16299 @noindent
16300 where
16301 @table @var
16302 @item switches
16303 is an optional sequence of switches as described in the next section.
16305 @item infile
16306 is the full name of the input file, which is an Ada source
16307 file containing preprocessor directives.
16309 @item outfile
16310 is the full name of the output file, which is an Ada source
16311 in standard Ada form. When used with GNAT, this file name will
16312 normally have an ads or adb suffix.
16314 @item deffile
16315 is the full name of a text file containing definitions of
16316 preprocessing symbols to be referenced by the preprocessor. This argument is
16317 optional, and can be replaced by the use of the @option{-D} switch.
16319 @end table
16321 @node Switches for gnatprep
16322 @section Switches for @code{gnatprep}
16324 @table @option
16325 @c !sort!
16327 @item -b
16328 @cindex @option{-b} (@command{gnatprep})
16329 Causes both preprocessor lines and the lines deleted by
16330 preprocessing to be replaced by blank lines in the output source file,
16331 preserving line numbers in the output file.
16333 @item -c
16334 @cindex @option{-c} (@command{gnatprep})
16335 Causes both preprocessor lines and the lines deleted
16336 by preprocessing to be retained in the output source as comments marked
16337 with the special string @code{"--! "}. This option will result in line numbers
16338 being preserved in the output file.
16340 @item -C
16341 @cindex @option{-C} (@command{gnatprep})
16342 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16343 If this option is specified, then comments are scanned and any $symbol
16344 substitutions performed as in program text. This is particularly useful
16345 when structured comments are used (e.g., when writing programs in the
16346 SPARK dialect of Ada). Note that this switch is not available when
16347 doing integrated preprocessing (it would be useless in this context
16348 since comments are ignored by the compiler in any case).
16350 @item -Dsymbol=value
16351 @cindex @option{-D} (@command{gnatprep})
16352 Defines a new preprocessing symbol, associated with value. If no value is given
16353 on the command line, then symbol is considered to be @code{True}. This switch
16354 can be used in place of a definition file.
16357 @item -r
16358 @cindex @option{-r} (@command{gnatprep})
16359 Causes a @code{Source_Reference} pragma to be generated that
16360 references the original input file, so that error messages will use
16361 the file name of this original file. The use of this switch implies
16362 that preprocessor lines are not to be removed from the file, so its
16363 use will force @option{-b} mode if
16364 @option{-c}
16365 has not been specified explicitly.
16367 Note that if the file to be preprocessed contains multiple units, then
16368 it will be necessary to @code{gnatchop} the output file from
16369 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16370 in the preprocessed file, it will be respected by
16371 @code{gnatchop -r}
16372 so that the final chopped files will correctly refer to the original
16373 input source file for @code{gnatprep}.
16375 @item -s
16376 @cindex @option{-s} (@command{gnatprep})
16377 Causes a sorted list of symbol names and values to be
16378 listed on the standard output file.
16380 @item -u
16381 @cindex @option{-u} (@command{gnatprep})
16382 Causes undefined symbols to be treated as having the value FALSE in the context
16383 of a preprocessor test. In the absence of this option, an undefined symbol in
16384 a @code{#if} or @code{#elsif} test will be treated as an error.
16386 @end table
16388 @noindent
16389 Note: if neither @option{-b} nor @option{-c} is present,
16390 then preprocessor lines and
16391 deleted lines are completely removed from the output, unless -r is
16392 specified, in which case -b is assumed.
16394 @node Form of Definitions File
16395 @section Form of Definitions File
16397 @noindent
16398 The definitions file contains lines of the form
16400 @smallexample
16401 symbol := value
16402 @end smallexample
16404 @noindent
16405 where symbol is a preprocessing symbol, and value is one of the following:
16407 @itemize @bullet
16408 @item
16409 Empty, corresponding to a null substitution
16410 @item
16411 A string literal using normal Ada syntax
16412 @item
16413 Any sequence of characters from the set
16414 (letters, digits, period, underline).
16415 @end itemize
16417 @noindent
16418 Comment lines may also appear in the definitions file, starting with
16419 the usual @code{--},
16420 and comments may be added to the definitions lines.
16422 @node Form of Input Text for gnatprep
16423 @section Form of Input Text for @code{gnatprep}
16425 @noindent
16426 The input text may contain preprocessor conditional inclusion lines,
16427 as well as general symbol substitution sequences.
16429 The preprocessor conditional inclusion commands have the form
16431 @smallexample
16432 @group
16433 @cartouche
16434 #if @i{expression} @r{[}then@r{]}
16435    lines
16436 #elsif @i{expression} @r{[}then@r{]}
16437    lines
16438 #elsif @i{expression} @r{[}then@r{]}
16439    lines
16440 @dots{}
16441 #else
16442    lines
16443 #end if;
16444 @end cartouche
16445 @end group
16446 @end smallexample
16448 @noindent
16449 In this example, @i{expression} is defined by the following grammar:
16450 @smallexample
16451 @i{expression} ::=  <symbol>
16452 @i{expression} ::=  <symbol> = "<value>"
16453 @i{expression} ::=  <symbol> = <symbol>
16454 @i{expression} ::=  <symbol> = <integer>
16455 @i{expression} ::=  <symbol> > <integer>
16456 @i{expression} ::=  <symbol> >= <integer>
16457 @i{expression} ::=  <symbol> < <integer>
16458 @i{expression} ::=  <symbol> <= <integer>
16459 @i{expression} ::=  <symbol> 'Defined
16460 @i{expression} ::=  not @i{expression}
16461 @i{expression} ::=  @i{expression} and @i{expression}
16462 @i{expression} ::=  @i{expression} or @i{expression}
16463 @i{expression} ::=  @i{expression} and then @i{expression}
16464 @i{expression} ::=  @i{expression} or else @i{expression}
16465 @i{expression} ::=  ( @i{expression} )
16466 @end smallexample
16468 The following restriction exists: it is not allowed to have "and" or "or"
16469 following "not" in the same expression without parentheses. For example, this
16470 is not allowed:
16472 @smallexample
16473    not X or Y
16474 @end smallexample
16476 This should be one of the following:
16478 @smallexample
16479    (not X) or Y
16480    not (X or Y)
16481 @end smallexample
16483 @noindent
16484 For the first test (@i{expression} ::= <symbol>) the symbol must have
16485 either the value true or false, that is to say the right-hand of the
16486 symbol definition must be one of the (case-insensitive) literals
16487 @code{True} or @code{False}. If the value is true, then the
16488 corresponding lines are included, and if the value is false, they are
16489 excluded.
16491 When comparing a symbol to an integer, the integer is any non negative
16492 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
16493 2#11#. The symbol value must also be a non negative integer. Integer values
16494 in the range 0 .. 2**31-1 are supported.
16496 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16497 the symbol has been defined in the definition file or by a @option{-D}
16498 switch on the command line. Otherwise, the test is false.
16500 The equality tests are case insensitive, as are all the preprocessor lines.
16502 If the symbol referenced is not defined in the symbol definitions file,
16503 then the effect depends on whether or not switch @option{-u}
16504 is specified. If so, then the symbol is treated as if it had the value
16505 false and the test fails. If this switch is not specified, then
16506 it is an error to reference an undefined symbol. It is also an error to
16507 reference a symbol that is defined with a value other than @code{True}
16508 or @code{False}.
16510 The use of the @code{not} operator inverts the sense of this logical test.
16511 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16512 operators, without parentheses. For example, "if not X or Y then" is not
16513 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16515 The @code{then} keyword is optional as shown
16517 The @code{#} must be the first non-blank character on a line, but
16518 otherwise the format is free form. Spaces or tabs may appear between
16519 the @code{#} and the keyword. The keywords and the symbols are case
16520 insensitive as in normal Ada code. Comments may be used on a
16521 preprocessor line, but other than that, no other tokens may appear on a
16522 preprocessor line. Any number of @code{elsif} clauses can be present,
16523 including none at all. The @code{else} is optional, as in Ada.
16525 The @code{#} marking the start of a preprocessor line must be the first
16526 non-blank character on the line, i.e., it must be preceded only by
16527 spaces or horizontal tabs.
16529 Symbol substitution outside of preprocessor lines is obtained by using
16530 the sequence
16532 @smallexample
16533 $symbol
16534 @end smallexample
16536 @noindent
16537 anywhere within a source line, except in a comment or within a
16538 string literal. The identifier
16539 following the @code{$} must match one of the symbols defined in the symbol
16540 definition file, and the result is to substitute the value of the
16541 symbol in place of @code{$symbol} in the output file.
16543 Note that although the substitution of strings within a string literal
16544 is not possible, it is possible to have a symbol whose defined value is
16545 a string literal. So instead of setting XYZ to @code{hello} and writing:
16547 @smallexample
16548 Header : String := "$XYZ";
16549 @end smallexample
16551 @noindent
16552 you should set XYZ to @code{"hello"} and write:
16554 @smallexample
16555 Header : String := $XYZ;
16556 @end smallexample
16558 @noindent
16559 and then the substitution will occur as desired.
16561 @node The GNAT Library Browser gnatls
16562 @chapter The GNAT Library Browser @code{gnatls}
16563 @findex gnatls
16564 @cindex Library browser
16566 @noindent
16567 @code{gnatls} is a tool that outputs information about compiled
16568 units. It gives the relationship between objects, unit names and source
16569 files. It can also be used to check the source dependencies of a unit
16570 as well as various characteristics.
16572 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16573 driver (see @ref{The GNAT Driver and Project Files}).
16575 @menu
16576 * Running gnatls::
16577 * Switches for gnatls::
16578 * Examples of gnatls Usage::
16579 @end menu
16581 @node Running gnatls
16582 @section Running @code{gnatls}
16584 @noindent
16585 The @code{gnatls} command has the form
16587 @smallexample
16588 $ gnatls switches @var{object_or_ali_file}
16589 @end smallexample
16591 @noindent
16592 The main argument is the list of object or @file{ali} files
16593 (@pxref{The Ada Library Information Files})
16594 for which information is requested.
16596 In normal mode, without additional option, @code{gnatls} produces a
16597 four-column listing. Each line represents information for a specific
16598 object. The first column gives the full path of the object, the second
16599 column gives the name of the principal unit in this object, the third
16600 column gives the status of the source and the fourth column gives the
16601 full path of the source representing this unit.
16602 Here is a simple example of use:
16604 @smallexample
16605 $ gnatls *.o
16606 ./demo1.o            demo1            DIF demo1.adb
16607 ./demo2.o            demo2             OK demo2.adb
16608 ./hello.o            h1                OK hello.adb
16609 ./instr-child.o      instr.child      MOK instr-child.adb
16610 ./instr.o            instr             OK instr.adb
16611 ./tef.o              tef              DIF tef.adb
16612 ./text_io_example.o  text_io_example   OK text_io_example.adb
16613 ./tgef.o             tgef             DIF tgef.adb
16614 @end smallexample
16616 @noindent
16617 The first line can be interpreted as follows: the main unit which is
16618 contained in
16619 object file @file{demo1.o} is demo1, whose main source is in
16620 @file{demo1.adb}. Furthermore, the version of the source used for the
16621 compilation of demo1 has been modified (DIF). Each source file has a status
16622 qualifier which can be:
16624 @table @code
16625 @item OK (unchanged)
16626 The version of the source file used for the compilation of the
16627 specified unit corresponds exactly to the actual source file.
16629 @item MOK (slightly modified)
16630 The version of the source file used for the compilation of the
16631 specified unit differs from the actual source file but not enough to
16632 require recompilation. If you use gnatmake with the qualifier
16633 @option{-m (minimal recompilation)}, a file marked
16634 MOK will not be recompiled.
16636 @item DIF (modified)
16637 No version of the source found on the path corresponds to the source
16638 used to build this object.
16640 @item ??? (file not found)
16641 No source file was found for this unit.
16643 @item HID (hidden,  unchanged version not first on PATH)
16644 The version of the source that corresponds exactly to the source used
16645 for compilation has been found on the path but it is hidden by another
16646 version of the same source that has been modified.
16648 @end table
16650 @node Switches for gnatls
16651 @section Switches for @code{gnatls}
16653 @noindent
16654 @code{gnatls} recognizes the following switches:
16656 @table @option
16657 @c !sort!
16658 @cindex @option{--version} @command{gnatls}
16659 Display Copyright and version, then exit disregarding all other options.
16661 @item --help
16662 @cindex @option{--help} @command{gnatls}
16663 If @option{--version} was not used, display usage, then exit disregarding
16664 all other options.
16666 @item -a
16667 @cindex @option{-a} (@code{gnatls})
16668 Consider all units, including those of the predefined Ada library.
16669 Especially useful with @option{-d}.
16671 @item -d
16672 @cindex @option{-d} (@code{gnatls})
16673 List sources from which specified units depend on.
16675 @item -h
16676 @cindex @option{-h} (@code{gnatls})
16677 Output the list of options.
16679 @item -o
16680 @cindex @option{-o} (@code{gnatls})
16681 Only output information about object files.
16683 @item -s
16684 @cindex @option{-s} (@code{gnatls})
16685 Only output information about source files.
16687 @item -u
16688 @cindex @option{-u} (@code{gnatls})
16689 Only output information about compilation units.
16691 @item -files=@var{file}
16692 @cindex @option{-files} (@code{gnatls})
16693 Take as arguments the files listed in text file @var{file}.
16694 Text file @var{file} may contain empty lines that are ignored.
16695 Each nonempty line should contain the name of an existing file.
16696 Several such switches may be specified simultaneously.
16698 @item -aO@var{dir}
16699 @itemx -aI@var{dir}
16700 @itemx -I@var{dir}
16701 @itemx  -I-
16702 @itemx -nostdinc
16703 @cindex @option{-aO} (@code{gnatls})
16704 @cindex @option{-aI} (@code{gnatls})
16705 @cindex @option{-I} (@code{gnatls})
16706 @cindex @option{-I-} (@code{gnatls})
16707 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16708 flags (@pxref{Switches for gnatmake}).
16710 @item -aP@var{dir}
16711 @cindex @option{-aP} (@code{gnatls})
16712 Add @var{dir} at the beginning of the project search dir.
16714 @item --RTS=@var{rts-path}
16715 @cindex @option{--RTS} (@code{gnatls})
16716 Specifies the default location of the runtime library. Same meaning as the
16717 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16719 @item -v
16720 @cindex @option{-v} (@code{gnatls})
16721 Verbose mode. Output the complete source, object and project paths. Do not use
16722 the default column layout but instead use long format giving as much as
16723 information possible on each requested units, including special
16724 characteristics such as:
16726 @table @code
16727 @item  Preelaborable
16728 The unit is preelaborable in the Ada sense.
16730 @item No_Elab_Code
16731 No elaboration code has been produced by the compiler for this unit.
16733 @item Pure
16734 The unit is pure in the Ada sense.
16736 @item Elaborate_Body
16737 The unit contains a pragma Elaborate_Body.
16739 @item Remote_Types
16740 The unit contains a pragma Remote_Types.
16742 @item Shared_Passive
16743 The unit contains a pragma Shared_Passive.
16745 @item Predefined
16746 This unit is part of the predefined environment and cannot be modified
16747 by the user.
16749 @item Remote_Call_Interface
16750 The unit contains a pragma Remote_Call_Interface.
16752 @end table
16754 @end table
16756 @node Examples of gnatls Usage
16757 @section Example of @code{gnatls} Usage
16759 @noindent
16760 Example of using the verbose switch. Note how the source and
16761 object paths are affected by the -I switch.
16763 @smallexample
16764 $ gnatls -v -I.. demo1.o
16766 GNATLS 5.03w (20041123-34)
16767 Copyright 1997-2004 Free Software Foundation, Inc.
16769 Source Search Path:
16770    <Current_Directory>
16771    ../
16772    /home/comar/local/adainclude/
16774 Object Search Path:
16775    <Current_Directory>
16776    ../
16777    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16779 Project Search Path:
16780    <Current_Directory>
16781    /home/comar/local/lib/gnat/
16783 ./demo1.o
16784    Unit =>
16785      Name   => demo1
16786      Kind   => subprogram body
16787      Flags  => No_Elab_Code
16788      Source => demo1.adb    modified
16789 @end smallexample
16791 @noindent
16792 The following is an example of use of the dependency list.
16793 Note the use of the -s switch
16794 which gives a straight list of source files. This can be useful for
16795 building specialized scripts.
16797 @smallexample
16798 $ gnatls -d demo2.o
16799 ./demo2.o   demo2        OK demo2.adb
16800                          OK gen_list.ads
16801                          OK gen_list.adb
16802                          OK instr.ads
16803                          OK instr-child.ads
16805 $ gnatls -d -s -a demo1.o
16806 demo1.adb
16807 /home/comar/local/adainclude/ada.ads
16808 /home/comar/local/adainclude/a-finali.ads
16809 /home/comar/local/adainclude/a-filico.ads
16810 /home/comar/local/adainclude/a-stream.ads
16811 /home/comar/local/adainclude/a-tags.ads
16812 gen_list.ads
16813 gen_list.adb
16814 /home/comar/local/adainclude/gnat.ads
16815 /home/comar/local/adainclude/g-io.ads
16816 instr.ads
16817 /home/comar/local/adainclude/system.ads
16818 /home/comar/local/adainclude/s-exctab.ads
16819 /home/comar/local/adainclude/s-finimp.ads
16820 /home/comar/local/adainclude/s-finroo.ads
16821 /home/comar/local/adainclude/s-secsta.ads
16822 /home/comar/local/adainclude/s-stalib.ads
16823 /home/comar/local/adainclude/s-stoele.ads
16824 /home/comar/local/adainclude/s-stratt.ads
16825 /home/comar/local/adainclude/s-tasoli.ads
16826 /home/comar/local/adainclude/s-unstyp.ads
16827 /home/comar/local/adainclude/unchconv.ads
16828 @end smallexample
16831 @node Cleaning Up with gnatclean
16832 @chapter Cleaning Up with @code{gnatclean}
16833 @findex gnatclean
16834 @cindex Cleaning tool
16836 @noindent
16837 @code{gnatclean} is a tool that allows the deletion of files produced by the
16838 compiler, binder and linker, including ALI files, object files, tree files,
16839 expanded source files, library files, interface copy source files, binder
16840 generated files and executable files.
16842 @menu
16843 * Running gnatclean::
16844 * Switches for gnatclean::
16845 @c * Examples of gnatclean Usage::
16846 @end menu
16848 @node Running gnatclean
16849 @section Running @code{gnatclean}
16851 @noindent
16852 The @code{gnatclean} command has the form:
16854 @smallexample
16855 $ gnatclean switches @var{names}
16856 @end smallexample
16858 @noindent
16859 @var{names} is a list of source file names. Suffixes @code{.ads} and
16860 @code{adb} may be omitted. If a project file is specified using switch
16861 @code{-P}, then @var{names} may be completely omitted.
16863 @noindent
16864 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16865 if switch @code{-c} is not specified, by the binder and
16866 the linker. In informative-only mode, specified by switch
16867 @code{-n}, the list of files that would have been deleted in
16868 normal mode is listed, but no file is actually deleted.
16870 @node Switches for gnatclean
16871 @section Switches for @code{gnatclean}
16873 @noindent
16874 @code{gnatclean} recognizes the following switches:
16876 @table @option
16877 @c !sort!
16878 @cindex @option{--version} @command{gnatclean}
16879 Display Copyright and version, then exit disregarding all other options.
16881 @item --help
16882 @cindex @option{--help} @command{gnatclean}
16883 If @option{--version} was not used, display usage, then exit disregarding
16884 all other options.
16886 @item --subdirs=subdir
16887 Actual object directory of each project file is the subdirectory subdir of the
16888 object directory specified or defaulted in the project file.
16890 @item --unchecked-shared-lib-imports
16891 By default, shared library projects are not allowed to import static library
16892 projects. When this switch is used on the command line, this restriction is
16893 relaxed.
16895 @item -c
16896 @cindex @option{-c} (@code{gnatclean})
16897 Only attempt to delete the files produced by the compiler, not those produced
16898 by the binder or the linker. The files that are not to be deleted are library
16899 files, interface copy files, binder generated files and executable files.
16901 @item -D @var{dir}
16902 @cindex @option{-D} (@code{gnatclean})
16903 Indicate that ALI and object files should normally be found in directory
16904 @var{dir}.
16906 @item -F
16907 @cindex @option{-F} (@code{gnatclean})
16908 When using project files, if some errors or warnings are detected during
16909 parsing and verbose mode is not in effect (no use of switch
16910 -v), then error lines start with the full path name of the project
16911 file, rather than its simple file name.
16913 @item -h
16914 @cindex @option{-h} (@code{gnatclean})
16915 Output a message explaining the usage of @code{gnatclean}.
16917 @item -n
16918 @cindex @option{-n} (@code{gnatclean})
16919 Informative-only mode. Do not delete any files. Output the list of the files
16920 that would have been deleted if this switch was not specified.
16922 @item -P@var{project}
16923 @cindex @option{-P} (@code{gnatclean})
16924 Use project file @var{project}. Only one such switch can be used.
16925 When cleaning a project file, the files produced by the compilation of the
16926 immediate sources or inherited sources of the project files are to be
16927 deleted. This is not depending on the presence or not of executable names
16928 on the command line.
16930 @item -q
16931 @cindex @option{-q} (@code{gnatclean})
16932 Quiet output. If there are no errors, do not output anything, except in
16933 verbose mode (switch -v) or in informative-only mode
16934 (switch -n).
16936 @item -r
16937 @cindex @option{-r} (@code{gnatclean})
16938 When a project file is specified (using switch -P),
16939 clean all imported and extended project files, recursively. If this switch
16940 is not specified, only the files related to the main project file are to be
16941 deleted. This switch has no effect if no project file is specified.
16943 @item -v
16944 @cindex @option{-v} (@code{gnatclean})
16945 Verbose mode.
16947 @item -vP@emph{x}
16948 @cindex @option{-vP} (@code{gnatclean})
16949 Indicates the verbosity of the parsing of GNAT project files.
16950 @xref{Switches Related to Project Files}.
16952 @item -X@var{name=value}
16953 @cindex @option{-X} (@code{gnatclean})
16954 Indicates that external variable @var{name} has the value @var{value}.
16955 The Project Manager will use this value for occurrences of
16956 @code{external(name)} when parsing the project file.
16957 @xref{Switches Related to Project Files}.
16959 @item -aO@var{dir}
16960 @cindex @option{-aO} (@code{gnatclean})
16961 When searching for ALI and object files, look in directory
16962 @var{dir}.
16964 @item -I@var{dir}
16965 @cindex @option{-I} (@code{gnatclean})
16966 Equivalent to @option{-aO@var{dir}}.
16968 @item -I-
16969 @cindex @option{-I-} (@code{gnatclean})
16970 @cindex Source files, suppressing search
16971 Do not look for ALI or object files in the directory
16972 where @code{gnatclean} was invoked.
16974 @end table
16976 @c @node Examples of gnatclean Usage
16977 @c @section Examples of @code{gnatclean} Usage
16979 @node GNAT and Libraries
16980 @chapter GNAT and Libraries
16981 @cindex Library, building, installing, using
16983 @noindent
16984 This chapter describes how to build and use libraries with GNAT, and also shows
16985 how to recompile the GNAT run-time library. You should be familiar with the
16986 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16987 chapter.
16989 @menu
16990 * Introduction to Libraries in GNAT::
16991 * General Ada Libraries::
16992 * Stand-alone Ada Libraries::
16993 * Rebuilding the GNAT Run-Time Library::
16994 @end menu
16996 @node Introduction to Libraries in GNAT
16997 @section Introduction to Libraries in GNAT
16999 @noindent
17000 A library is, conceptually, a collection of objects which does not have its
17001 own main thread of execution, but rather provides certain services to the
17002 applications that use it. A library can be either statically linked with the
17003 application, in which case its code is directly included in the application,
17004 or, on platforms that support it, be dynamically linked, in which case
17005 its code is shared by all applications making use of this library.
17007 GNAT supports both types of libraries.
17008 In the static case, the compiled code can be provided in different ways. The
17009 simplest approach is to provide directly the set of objects resulting from
17010 compilation of the library source files. Alternatively, you can group the
17011 objects into an archive using whatever commands are provided by the operating
17012 system. For the latter case, the objects are grouped into a shared library.
17014 In the GNAT environment, a library has three types of components:
17015 @itemize @bullet
17016 @item
17017 Source files.
17018 @item
17019 @file{ALI} files.
17020 @xref{The Ada Library Information Files}.
17021 @item
17022 Object files, an archive or a shared library.
17023 @end itemize
17025 @noindent
17026 A GNAT library may expose all its source files, which is useful for
17027 documentation purposes. Alternatively, it may expose only the units needed by
17028 an external user to make use of the library. That is to say, the specs
17029 reflecting the library services along with all the units needed to compile
17030 those specs, which can include generic bodies or any body implementing an
17031 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17032 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17034 All compilation units comprising an application, including those in a library,
17035 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17036 computes the elaboration order from the @file{ALI} files and this is why they
17037 constitute a mandatory part of GNAT libraries.
17038 @emph{Stand-alone libraries} are the exception to this rule because a specific
17039 library elaboration routine is produced independently of the application(s)
17040 using the library.
17042 @node General Ada Libraries
17043 @section General Ada Libraries
17045 @menu
17046 * Building a library::
17047 * Installing a library::
17048 * Using a library::
17049 @end menu
17051 @node Building a library
17052 @subsection Building a library
17054 @noindent
17055 The easiest way to build a library is to use the Project Manager,
17056 which supports a special type of project called a @emph{Library Project}
17057 (@pxref{Library Projects}).
17059 A project is considered a library project, when two project-level attributes
17060 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17061 control different aspects of library configuration, additional optional
17062 project-level attributes can be specified:
17063 @table @code
17064 @item Library_Kind
17065 This attribute controls whether the library is to be static or dynamic
17067 @item Library_Version
17068 This attribute specifies the library version; this value is used
17069 during dynamic linking of shared libraries to determine if the currently
17070 installed versions of the binaries are compatible.
17072 @item Library_Options
17073 @item Library_GCC
17074 These attributes specify additional low-level options to be used during
17075 library generation, and redefine the actual application used to generate
17076 library.
17077 @end table
17079 @noindent
17080 The GNAT Project Manager takes full care of the library maintenance task,
17081 including recompilation of the source files for which objects do not exist
17082 or are not up to date, assembly of the library archive, and installation of
17083 the library (i.e., copying associated source, object and @file{ALI} files
17084 to the specified location).
17086 Here is a simple library project file:
17087 @smallexample @c ada
17088 project My_Lib @b{is}
17089    @b{for} Source_Dirs @b{use} ("src1", "src2");
17090    @b{for} Object_Dir @b{use} "obj";
17091    @b{for} Library_Name @b{use} "mylib";
17092    @b{for} Library_Dir @b{use} "lib";
17093    @b{for} Library_Kind @b{use} "dynamic";
17094 @b{end} My_lib;
17095 @end smallexample
17097 @noindent
17098 and the compilation command to build and install the library:
17100 @smallexample @c ada
17101   $ gnatmake -Pmy_lib
17102 @end smallexample
17104 @noindent
17105 It is not entirely trivial to perform manually all the steps required to
17106 produce a library. We recommend that you use the GNAT Project Manager
17107 for this task. In special cases where this is not desired, the necessary
17108 steps are discussed below.
17110 There are various possibilities for compiling the units that make up the
17111 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17112 with a conventional script. For simple libraries, it is also possible to create
17113 a dummy main program which depends upon all the packages that comprise the
17114 interface of the library. This dummy main program can then be given to
17115 @command{gnatmake}, which will ensure that all necessary objects are built.
17117 After this task is accomplished, you should follow the standard procedure
17118 of the underlying operating system to produce the static or shared library.
17120 Here is an example of such a dummy program:
17121 @smallexample @c ada
17122 @group
17123 @b{with} My_Lib.Service1;
17124 @b{with} My_Lib.Service2;
17125 @b{with} My_Lib.Service3;
17126 @b{procedure} My_Lib_Dummy @b{is}
17127 @b{begin}
17128    @b{null};
17129 @b{end};
17130 @end group
17131 @end smallexample
17133 @noindent
17134 Here are the generic commands that will build an archive or a shared library.
17136 @smallexample
17137 # compiling the library
17138 $ gnatmake -c my_lib_dummy.adb
17140 # we don't need the dummy object itself
17141 $ rm my_lib_dummy.o my_lib_dummy.ali
17143 # create an archive with the remaining objects
17144 $ ar rc libmy_lib.a *.o
17145 # some systems may require "ranlib" to be run as well
17147 # or create a shared library
17148 $ gcc -shared -o libmy_lib.so *.o
17149 # some systems may require the code to have been compiled with -fPIC
17151 # remove the object files that are now in the library
17152 $ rm *.o
17154 # Make the ALI files read-only so that gnatmake will not try to
17155 # regenerate the objects that are in the library
17156 $ chmod -w *.ali
17157 @end smallexample
17159 @noindent
17160 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17161 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17162 be accessed by the directive @option{-l@var{xxx}} at link time.
17164 @node Installing a library
17165 @subsection Installing a library
17166 @cindex @code{ADA_PROJECT_PATH}
17167 @cindex @code{GPR_PROJECT_PATH}
17169 @noindent
17170 If you use project files, library installation is part of the library build
17171 process (@pxref{Installing a library with project files}).
17173 When project files are not an option, it is also possible, but not recommended,
17174 to install the library so that the sources needed to use the library are on the
17175 Ada source path and the ALI files & libraries be on the Ada Object path (see
17176 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17177 administrator can place general-purpose libraries in the default compiler
17178 paths, by specifying the libraries' location in the configuration files
17179 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17180 must be located in the GNAT installation tree at the same place as the gcc spec
17181 file. The location of the gcc spec file can be determined as follows:
17182 @smallexample
17183 $ gcc -v
17184 @end smallexample
17186 @noindent
17187 The configuration files mentioned above have a simple format: each line
17188 must contain one unique directory name.
17189 Those names are added to the corresponding path
17190 in their order of appearance in the file. The names can be either absolute
17191 or relative; in the latter case, they are relative to where theses files
17192 are located.
17194 The files @file{ada_source_path} and @file{ada_object_path} might not be
17195 present in a
17196 GNAT installation, in which case, GNAT will look for its run-time library in
17197 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17198 objects and @file{ALI} files). When the files exist, the compiler does not
17199 look in @file{adainclude} and @file{adalib}, and thus the
17200 @file{ada_source_path} file
17201 must contain the location for the GNAT run-time sources (which can simply
17202 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17203 contain the location for the GNAT run-time objects (which can simply
17204 be @file{adalib}).
17206 You can also specify a new default path to the run-time library at compilation
17207 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17208 the run-time library you want your program to be compiled with. This switch is
17209 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17210 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17212 It is possible to install a library before or after the standard GNAT
17213 library, by reordering the lines in the configuration files. In general, a
17214 library must be installed before the GNAT library if it redefines
17215 any part of it.
17217 @node Using a library
17218 @subsection Using a library
17220 @noindent Once again, the project facility greatly simplifies the use of
17221 libraries. In this context, using a library is just a matter of adding a
17222 @code{with} clause in the user project. For instance, to make use of the
17223 library @code{My_Lib} shown in examples in earlier sections, you can
17224 write:
17226 @smallexample @c projectfile
17227 @b{with} "my_lib";
17228 @b{project} My_Proj @b{is}
17229   @dots{}
17230 @b{end} My_Proj;
17231 @end smallexample
17233 Even if you have a third-party, non-Ada library, you can still use GNAT's
17234 Project Manager facility to provide a wrapper for it. For example, the
17235 following project, when @code{with}ed by your main project, will link with the
17236 third-party library @file{liba.a}:
17238 @smallexample @c projectfile
17239 @group
17240 @b{project} Liba @b{is}
17241    @b{for} Externally_Built @b{use} "true";
17242    @b{for} Source_Files @b{use} ();
17243    @b{for} Library_Dir @b{use} "lib";
17244    @b{for} Library_Name @b{use} "a";
17245    @b{for} Library_Kind @b{use} "static";
17246 @b{end} Liba;
17247 @end group
17248 @end smallexample
17249 This is an alternative to the use of @code{pragma Linker_Options}. It is
17250 especially interesting in the context of systems with several interdependent
17251 static libraries where finding a proper linker order is not easy and best be
17252 left to the tools having visibility over project dependence information.
17254 @noindent
17255 In order to use an Ada library manually, you need to make sure that this
17256 library is on both your source and object path
17257 (see @ref{Search Paths and the Run-Time Library (RTL)}
17258 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17259 in an archive or a shared library, you need to specify the desired
17260 library at link time.
17262 For example, you can use the library @file{mylib} installed in
17263 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17265 @smallexample
17266 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17267   -largs -lmy_lib
17268 @end smallexample
17270 @noindent
17271 This can be expressed more simply:
17272 @smallexample
17273 $ gnatmake my_appl
17274 @end smallexample
17275 @noindent
17276 when the following conditions are met:
17277 @itemize @bullet
17278 @item
17279 @file{/dir/my_lib_src} has been added by the user to the environment
17280 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17281 @file{ada_source_path}
17282 @item
17283 @file{/dir/my_lib_obj} has been added by the user to the environment
17284 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17285 @file{ada_object_path}
17286 @item
17287 a pragma @code{Linker_Options} has been added to one of the sources.
17288 For example:
17290 @smallexample @c ada
17291 @b{pragma} Linker_Options ("-lmy_lib");
17292 @end smallexample
17293 @end itemize
17295 Note that you may also load a library dynamically at
17296 run time given its filename, as illustrated in the GNAT @file{plugins} example
17297 in the directory @file{share/examples/gnat/plugins} within the GNAT
17298 install area.
17300 @node Stand-alone Ada Libraries
17301 @section Stand-alone Ada Libraries
17302 @cindex Stand-alone library, building, using
17304 @menu
17305 * Introduction to Stand-alone Libraries::
17306 * Building a Stand-alone Library::
17307 * Creating a Stand-alone Library to be used in a non-Ada context::
17308 * Restrictions in Stand-alone Libraries::
17309 @end menu
17311 @node Introduction to Stand-alone Libraries
17312 @subsection Introduction to Stand-alone Libraries
17314 @noindent
17315 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17316 necessary code to
17317 elaborate the Ada units that are included in the library. In contrast with
17318 an ordinary library, which consists of all sources, objects and @file{ALI}
17319 files of the
17320 library, a SAL may specify a restricted subset of compilation units
17321 to serve as a library interface. In this case, the fully
17322 self-sufficient set of files will normally consist of an objects
17323 archive, the sources of interface units' specs, and the @file{ALI}
17324 files of interface units.
17325 If an interface spec contains a generic unit or an inlined subprogram,
17326 the body's
17327 source must also be provided; if the units that must be provided in the source
17328 form depend on other units, the source and @file{ALI} files of those must
17329 also be provided.
17331 The main purpose of a SAL is to minimize the recompilation overhead of client
17332 applications when a new version of the library is installed. Specifically,
17333 if the interface sources have not changed, client applications do not need to
17334 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17335 version, controlled by @code{Library_Version} attribute, is not changed,
17336 then the clients do not need to be relinked.
17338 SALs also allow the library providers to minimize the amount of library source
17339 text exposed to the clients.  Such ``information hiding'' might be useful or
17340 necessary for various reasons.
17342 Stand-alone libraries are also well suited to be used in an executable whose
17343 main routine is not written in Ada.
17345 @node Building a Stand-alone Library
17346 @subsection Building a Stand-alone Library
17348 @noindent
17349 GNAT's Project facility provides a simple way of building and installing
17350 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17351 To be a Stand-alone Library Project, in addition to the two attributes
17352 that make a project a Library Project (@code{Library_Name} and
17353 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17354 @code{Library_Interface} must be defined.  For example:
17356 @smallexample @c projectfile
17357 @group
17358    @b{for} Library_Dir @b{use} "lib_dir";
17359    @b{for} Library_Name @b{use} "dummy";
17360    @b{for} Library_Interface @b{use} ("int1", "int1.child");
17361 @end group
17362 @end smallexample
17364 @noindent
17365 Attribute @code{Library_Interface} has a non-empty string list value,
17366 each string in the list designating a unit contained in an immediate source
17367 of the project file.
17369 When a Stand-alone Library is built, first the binder is invoked to build
17370 a package whose name depends on the library name
17371 (@file{b~dummy.ads/b} in the example above).
17372 This binder-generated package includes initialization and
17373 finalization procedures whose
17374 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17375 in the example
17376 above). The object corresponding to this package is included in the library.
17378 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17379 calling of these procedures if a static SAL is built, or if a shared SAL
17380 is built
17381 with the project-level attribute @code{Library_Auto_Init} set to
17382 @code{"false"}.
17384 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17385 (those that are listed in attribute @code{Library_Interface}) are copied to
17386 the Library Directory. As a consequence, only the Interface Units may be
17387 imported from Ada units outside of the library. If other units are imported,
17388 the binding phase will fail.
17390 @noindent
17391 It is also possible to build an encapsulated library where not only
17392 the code to elaborate and finalize the library is embedded but also
17393 ensuring that the library is linked only against static
17394 libraries. So an encapsulated library only depends on system
17395 libraries, all other code, including the GNAT runtime, is embedded. To
17396 build an encapsulated library the attribute
17397 @code{Library_Standalone} must be set to @code{encapsulated}:
17399 @smallexample @c projectfile
17400 @group
17401    @b{for} Library_Dir @b{use} "lib_dir";
17402    @b{for} Library_Name @b{use} "dummy";
17403    @b{for} Library_Kind @b{use} "dynamic";
17404    @b{for} Library_Interface @b{use} ("int1", "int1.child");
17405    @b{for} Library_Standalone @b{use} "encapsulated";
17406 @end group
17407 @end smallexample
17409 @noindent
17410 The default value for this attribute is @code{standard} in which case
17411 a stand-alone library is built.
17413 The attribute @code{Library_Src_Dir} may be specified for a
17414 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17415 single string value. Its value must be the path (absolute or relative to the
17416 project directory) of an existing directory. This directory cannot be the
17417 object directory or one of the source directories, but it can be the same as
17418 the library directory. The sources of the Interface
17419 Units of the library that are needed by an Ada client of the library will be
17420 copied to the designated directory, called the Interface Copy directory.
17421 These sources include the specs of the Interface Units, but they may also
17422 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17423 are used, or when there is a generic unit in the spec. Before the sources
17424 are copied to the Interface Copy directory, an attempt is made to delete all
17425 files in the Interface Copy directory.
17427 Building stand-alone libraries by hand is somewhat tedious, but for those
17428 occasions when it is necessary here are the steps that you need to perform:
17429 @itemize @bullet
17430 @item
17431 Compile all library sources.
17433 @item
17434 Invoke the binder with the switch @option{-n} (No Ada main program),
17435 with all the @file{ALI} files of the interfaces, and
17436 with the switch @option{-L} to give specific names to the @code{init}
17437 and @code{final} procedures.  For example:
17438 @smallexample
17439   gnatbind -n int1.ali int2.ali -Lsal1
17440 @end smallexample
17442 @item
17443 Compile the binder generated file:
17444 @smallexample
17445   gcc -c b~int2.adb
17446 @end smallexample
17448 @item
17449 Link the dynamic library with all the necessary object files,
17450 indicating to the linker the names of the @code{init} (and possibly
17451 @code{final}) procedures for automatic initialization (and finalization).
17452 The built library should be placed in a directory different from
17453 the object directory.
17455 @item
17456 Copy the @code{ALI} files of the interface to the library directory,
17457 add in this copy an indication that it is an interface to a SAL
17458 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17459 with letter ``P'') and make the modified copy of the @file{ALI} file
17460 read-only.
17461 @end itemize
17463 @noindent
17464 Using SALs is not different from using other libraries
17465 (see @ref{Using a library}).
17467 @node Creating a Stand-alone Library to be used in a non-Ada context
17468 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17470 @noindent
17471 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17472 a non-Ada context.
17474 The only extra step required is to ensure that library interface subprograms
17475 are compatible with the main program, by means of @code{pragma Export}
17476 or @code{pragma Convention}.
17478 Here is an example of simple library interface for use with C main program:
17480 @smallexample @c ada
17481 @b{package} My_Package @b{is}
17483    @b{procedure} Do_Something;
17484    @b{pragma} Export (C, Do_Something, "do_something");
17486    @b{procedure} Do_Something_Else;
17487    @b{pragma} Export (C, Do_Something_Else, "do_something_else");
17489 @b{end} My_Package;
17490 @end smallexample
17492 @noindent
17493 On the foreign language side, you must provide a ``foreign'' view of the
17494 library interface; remember that it should contain elaboration routines in
17495 addition to interface subprograms.
17497 The example below shows the content of @code{mylib_interface.h} (note
17498 that there is no rule for the naming of this file, any name can be used)
17499 @smallexample
17500 /* the library elaboration procedure */
17501 extern void mylibinit (void);
17503 /* the library finalization procedure */
17504 extern void mylibfinal (void);
17506 /* the interface exported by the library */
17507 extern void do_something (void);
17508 extern void do_something_else (void);
17509 @end smallexample
17511 @noindent
17512 Libraries built as explained above can be used from any program, provided
17513 that the elaboration procedures (named @code{mylibinit} in the previous
17514 example) are called before the library services are used. Any number of
17515 libraries can be used simultaneously, as long as the elaboration
17516 procedure of each library is called.
17518 Below is an example of a C program that uses the @code{mylib} library.
17520 @smallexample
17521 #include "mylib_interface.h"
17524 main (void)
17526    /* First, elaborate the library before using it */
17527    mylibinit ();
17529    /* Main program, using the library exported entities */
17530    do_something ();
17531    do_something_else ();
17533    /* Library finalization at the end of the program */
17534    mylibfinal ();
17535    return 0;
17537 @end smallexample
17539 @noindent
17540 Note that invoking any library finalization procedure generated by
17541 @code{gnatbind} shuts down the Ada run-time environment.
17542 Consequently, the
17543 finalization of all Ada libraries must be performed at the end of the program.
17544 No call to these libraries or to the Ada run-time library should be made
17545 after the finalization phase.
17547 @node Restrictions in Stand-alone Libraries
17548 @subsection Restrictions in Stand-alone Libraries
17550 @noindent
17551 The pragmas listed below should be used with caution inside libraries,
17552 as they can create incompatibilities with other Ada libraries:
17553 @itemize @bullet
17554 @item pragma @code{Locking_Policy}
17555 @item pragma @code{Partition_Elaboration_Policy}
17556 @item pragma @code{Queuing_Policy}
17557 @item pragma @code{Task_Dispatching_Policy}
17558 @item pragma @code{Unreserve_All_Interrupts}
17559 @end itemize
17561 @noindent
17562 When using a library that contains such pragmas, the user must make sure
17563 that all libraries use the same pragmas with the same values. Otherwise,
17564 @code{Program_Error} will
17565 be raised during the elaboration of the conflicting
17566 libraries. The usage of these pragmas and its consequences for the user
17567 should therefore be well documented.
17569 Similarly, the traceback in the exception occurrence mechanism should be
17570 enabled or disabled in a consistent manner across all libraries.
17571 Otherwise, Program_Error will be raised during the elaboration of the
17572 conflicting libraries.
17574 If the @code{Version} or @code{Body_Version}
17575 attributes are used inside a library, then you need to
17576 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17577 libraries, so that version identifiers can be properly computed.
17578 In practice these attributes are rarely used, so this is unlikely
17579 to be a consideration.
17581 @node  Rebuilding the GNAT Run-Time Library
17582 @section Rebuilding the GNAT Run-Time Library
17583 @cindex GNAT Run-Time Library, rebuilding
17584 @cindex Building the GNAT Run-Time Library
17585 @cindex Rebuilding the GNAT Run-Time Library
17586 @cindex Run-Time Library, rebuilding
17588 @noindent
17589 It may be useful to recompile the GNAT library in various contexts, the
17590 most important one being the use of partition-wide configuration pragmas
17591 such as @code{Normalize_Scalars}. A special Makefile called
17592 @code{Makefile.adalib} is provided to that effect and can be found in
17593 the directory containing the GNAT library. The location of this
17594 directory depends on the way the GNAT environment has been installed and can
17595 be determined by means of the command:
17597 @smallexample
17598 $ gnatls -v
17599 @end smallexample
17601 @noindent
17602 The last entry in the object search path usually contains the
17603 gnat library. This Makefile contains its own documentation and in
17604 particular the set of instructions needed to rebuild a new library and
17605 to use it.
17607 @node Using the GNU make Utility
17608 @chapter Using the GNU @code{make} Utility
17609 @findex make
17611 @noindent
17612 This chapter offers some examples of makefiles that solve specific
17613 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
17614 make, make, GNU @code{make}}), nor does it try to replace the
17615 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
17617 All the examples in this section are specific to the GNU version of
17618 make. Although @command{make} is a standard utility, and the basic language
17619 is the same, these examples use some advanced features found only in
17620 @code{GNU make}.
17622 @menu
17623 * Using gnatmake in a Makefile::
17624 * Automatically Creating a List of Directories::
17625 * Generating the Command Line Switches::
17626 * Overcoming Command Line Length Limits::
17627 @end menu
17629 @node Using gnatmake in a Makefile
17630 @section Using gnatmake in a Makefile
17631 @findex makefile
17632 @cindex GNU make
17634 @noindent
17635 Complex project organizations can be handled in a very powerful way by
17636 using GNU make combined with gnatmake. For instance, here is a Makefile
17637 which allows you to build each subsystem of a big project into a separate
17638 shared library. Such a makefile allows you to significantly reduce the link
17639 time of very big applications while maintaining full coherence at
17640 each step of the build process.
17642 The list of dependencies are handled automatically by
17643 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17644 the appropriate directories.
17646 Note that you should also read the example on how to automatically
17647 create the list of directories
17648 (@pxref{Automatically Creating a List of Directories})
17649 which might help you in case your project has a lot of subdirectories.
17651 @smallexample
17652 @iftex
17653 @leftskip=0cm
17654 @font@heightrm=cmr8
17655 @heightrm
17656 @end iftex
17657 ## This Makefile is intended to be used with the following directory
17658 ## configuration:
17659 ##  - The sources are split into a series of csc (computer software components)
17660 ##    Each of these csc is put in its own directory.
17661 ##    Their name are referenced by the directory names.
17662 ##    They will be compiled into shared library (although this would also work
17663 ##    with static libraries
17664 ##  - The main program (and possibly other packages that do not belong to any
17665 ##    csc is put in the top level directory (where the Makefile is).
17666 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17667 ##                    \_ second_csc (sources) __ lib (will contain the library)
17668 ##                    \_ @dots{}
17669 ## Although this Makefile is build for shared library, it is easy to modify
17670 ## to build partial link objects instead (modify the lines with -shared and
17671 ## gnatlink below)
17673 ## With this makefile, you can change any file in the system or add any new
17674 ## file, and everything will be recompiled correctly (only the relevant shared
17675 ## objects will be recompiled, and the main program will be re-linked).
17677 # The list of computer software component for your project. This might be
17678 # generated automatically.
17679 CSC_LIST=aa bb cc
17681 # Name of the main program (no extension)
17682 MAIN=main
17684 # If we need to build objects with -fPIC, uncomment the following line
17685 #NEED_FPIC=-fPIC
17687 # The following variable should give the directory containing libgnat.so
17688 # You can get this directory through 'gnatls -v'. This is usually the last
17689 # directory in the Object_Path.
17690 GLIB=@dots{}
17692 # The directories for the libraries
17693 # (This macro expands the list of CSC to the list of shared libraries, you
17694 # could simply use the expanded form:
17695 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17696 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17698 $@{MAIN@}: objects $@{LIB_DIR@}
17699     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17700     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17702 objects::
17703     # recompile the sources
17704     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17706 # Note: In a future version of GNAT, the following commands will be simplified
17707 # by a new tool, gnatmlib
17708 $@{LIB_DIR@}:
17709     mkdir -p $@{dir $@@ @}
17710     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17711     cd $@{dir $@@ @} && cp -f ../*.ali .
17713 # The dependencies for the modules
17714 # Note that we have to force the expansion of *.o, since in some cases
17715 # make won't be able to do it itself.
17716 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17717 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17718 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17720 # Make sure all of the shared libraries are in the path before starting the
17721 # program
17722 run::
17723     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17725 clean::
17726     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17727     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17728     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17729     $@{RM@} *.o *.ali $@{MAIN@}
17730 @end smallexample
17732 @node Automatically Creating a List of Directories
17733 @section Automatically Creating a List of Directories
17735 @noindent
17736 In most makefiles, you will have to specify a list of directories, and
17737 store it in a variable. For small projects, it is often easier to
17738 specify each of them by hand, since you then have full control over what
17739 is the proper order for these directories, which ones should be
17740 included.
17742 However, in larger projects, which might involve hundreds of
17743 subdirectories, it might be more convenient to generate this list
17744 automatically.
17746 The example below presents two methods. The first one, although less
17747 general, gives you more control over the list. It involves wildcard
17748 characters, that are automatically expanded by @command{make}. Its
17749 shortcoming is that you need to explicitly specify some of the
17750 organization of your project, such as for instance the directory tree
17751 depth, whether some directories are found in a separate tree, @enddots{}
17753 The second method is the most general one. It requires an external
17754 program, called @command{find}, which is standard on all Unix systems. All
17755 the directories found under a given root directory will be added to the
17756 list.
17758 @smallexample
17759 @iftex
17760 @leftskip=0cm
17761 @font@heightrm=cmr8
17762 @heightrm
17763 @end iftex
17764 # The examples below are based on the following directory hierarchy:
17765 # All the directories can contain any number of files
17766 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17767 #                       ->  ab
17768 #                       ->  ac
17769 #                ->  b  ->  ba  ->  baa
17770 #                       ->  bb
17771 #                       ->  bc
17772 # This Makefile creates a variable called DIRS, that can be reused any time
17773 # you need this list (see the other examples in this section)
17775 # The root of your project's directory hierarchy
17776 ROOT_DIRECTORY=.
17778 ####
17779 # First method: specify explicitly the list of directories
17780 # This allows you to specify any subset of all the directories you need.
17781 ####
17783 DIRS := a/aa/ a/ab/ b/ba/
17785 ####
17786 # Second method: use wildcards
17787 # Note that the argument(s) to wildcard below should end with a '/'.
17788 # Since wildcards also return file names, we have to filter them out
17789 # to avoid duplicate directory names.
17790 # We thus use make's @code{dir} and @code{sort} functions.
17791 # It sets DIRs to the following value (note that the directories aaa and baa
17792 # are not given, unless you change the arguments to wildcard).
17793 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17794 ####
17796 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17797                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17799 ####
17800 # Third method: use an external program
17801 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17802 # This is the most complete command: it sets DIRs to the following value:
17803 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17804 ####
17806 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17808 @end smallexample
17810 @node Generating the Command Line Switches
17811 @section Generating the Command Line Switches
17813 @noindent
17814 Once you have created the list of directories as explained in the
17815 previous section (@pxref{Automatically Creating a List of Directories}),
17816 you can easily generate the command line arguments to pass to gnatmake.
17818 For the sake of completeness, this example assumes that the source path
17819 is not the same as the object path, and that you have two separate lists
17820 of directories.
17822 @smallexample
17823 # see "Automatically creating a list of directories" to create
17824 # these variables
17825 SOURCE_DIRS=
17826 OBJECT_DIRS=
17828 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17829 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17831 all:
17832         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17833 @end smallexample
17835 @node Overcoming Command Line Length Limits
17836 @section Overcoming Command Line Length Limits
17838 @noindent
17839 One problem that might be encountered on big projects is that many
17840 operating systems limit the length of the command line. It is thus hard to give
17841 gnatmake the list of source and object directories.
17843 This example shows how you can set up environment variables, which will
17844 make @command{gnatmake} behave exactly as if the directories had been
17845 specified on the command line, but have a much higher length limit (or
17846 even none on most systems).
17848 It assumes that you have created a list of directories in your Makefile,
17849 using one of the methods presented in
17850 @ref{Automatically Creating a List of Directories}.
17851 For the sake of completeness, we assume that the object
17852 path (where the ALI files are found) is different from the sources patch.
17854 Note a small trick in the Makefile below: for efficiency reasons, we
17855 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17856 expanded immediately by @code{make}. This way we overcome the standard
17857 make behavior which is to expand the variables only when they are
17858 actually used.
17860 On Windows, if you are using the standard Windows command shell, you must
17861 replace colons with semicolons in the assignments to these variables.
17863 @smallexample
17864 @iftex
17865 @leftskip=0cm
17866 @font@heightrm=cmr8
17867 @heightrm
17868 @end iftex
17869 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17870 # This is the same thing as putting the -I arguments on the command line.
17871 # (the equivalent of using -aI on the command line would be to define
17872 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17873 # You can of course have different values for these variables.
17875 # Note also that we need to keep the previous values of these variables, since
17876 # they might have been set before running 'make' to specify where the GNAT
17877 # library is installed.
17879 # see "Automatically creating a list of directories" to create these
17880 # variables
17881 SOURCE_DIRS=
17882 OBJECT_DIRS=
17884 empty:=
17885 space:=$@{empty@} $@{empty@}
17886 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17887 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17888 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17889 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17890 export ADA_INCLUDE_PATH
17891 export ADA_OBJECTS_PATH
17893 all:
17894         gnatmake main_unit
17895 @end smallexample
17897 @node Memory Management Issues
17898 @chapter Memory Management Issues
17900 @noindent
17901 This chapter describes some useful memory pools provided in the GNAT library
17902 and in particular the GNAT Debug Pool facility, which can be used to detect
17903 incorrect uses of access values (including ``dangling references'').
17904 @ifclear FSFEDITION
17905 It also describes the @command{gnatmem} tool, which can be used to track down
17906 ``memory leaks''.
17907 @end ifclear
17909 @menu
17910 * Some Useful Memory Pools::
17911 * The GNAT Debug Pool Facility::
17912 @ifclear FSFEDITION
17913 * The gnatmem Tool::
17914 @end ifclear
17915 @end menu
17917 @node Some Useful Memory Pools
17918 @section Some Useful Memory Pools
17919 @findex Memory Pool
17920 @cindex storage, pool
17922 @noindent
17923 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17924 storage pool. Allocations use the standard system call @code{malloc} while
17925 deallocations use the standard system call @code{free}. No reclamation is
17926 performed when the pool goes out of scope. For performance reasons, the
17927 standard default Ada allocators/deallocators do not use any explicit storage
17928 pools but if they did, they could use this storage pool without any change in
17929 behavior. That is why this storage pool is used  when the user
17930 manages to make the default implicit allocator explicit as in this example:
17931 @smallexample @c ada
17932    @b{type} T1 @b{is} @b{access} Something;
17933     --@i{ no Storage pool is defined for T2}
17934    @b{type} T2 @b{is} @b{access} Something_Else;
17935    @b{for} T2'Storage_Pool @b{use} T1'Storage_Pool;
17936    --@i{ the above is equivalent to}
17937    @b{for} T2'Storage_Pool @b{use} System.Pool_Global.Global_Pool_Object;
17938 @end smallexample
17940 @noindent
17941 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17942 pool. The allocation strategy is similar to @code{Pool_Local}'s
17943 except that the all
17944 storage allocated with this pool is reclaimed when the pool object goes out of
17945 scope. This pool provides a explicit mechanism similar to the implicit one
17946 provided by several Ada 83 compilers for allocations performed through a local
17947 access type and whose purpose was to reclaim memory when exiting the
17948 scope of a given local access. As an example, the following program does not
17949 leak memory even though it does not perform explicit deallocation:
17951 @smallexample @c ada
17952 @b{with} System.Pool_Local;
17953 @b{procedure} Pooloc1 @b{is}
17954    @b{procedure} Internal @b{is}
17955       @b{type} A @b{is} @b{access} Integer;
17956       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17957       @b{for} A'Storage_Pool @b{use} X;
17958       v : A;
17959    @b{begin}
17960       @b{for} I @b{in}  1 .. 50 @b{loop}
17961          v := @b{new} Integer;
17962       @b{end} @b{loop};
17963    @b{end} Internal;
17964 @b{begin}
17965    @b{for} I @b{in}  1 .. 100 @b{loop}
17966       Internal;
17967    @b{end} @b{loop};
17968 @b{end} Pooloc1;
17969 @end smallexample
17971 @noindent
17972 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17973 @code{Storage_Size} is specified for an access type.
17974 The whole storage for the pool is
17975 allocated at once, usually on the stack at the point where the access type is
17976 elaborated. It is automatically reclaimed when exiting the scope where the
17977 access type is defined. This package is not intended to be used directly by the
17978 user and it is implicitly used for each such declaration:
17980 @smallexample @c ada
17981    @b{type} T1 @b{is} @b{access} Something;
17982    @b{for} T1'Storage_Size @b{use} 10_000;
17983 @end smallexample
17985 @node The GNAT Debug Pool Facility
17986 @section The GNAT Debug Pool Facility
17987 @findex Debug Pool
17988 @cindex storage, pool, memory corruption
17990 @noindent
17991 The use of unchecked deallocation and unchecked conversion can easily
17992 lead to incorrect memory references. The problems generated by such
17993 references are usually difficult to tackle because the symptoms can be
17994 very remote from the origin of the problem. In such cases, it is
17995 very helpful to detect the problem as early as possible. This is the
17996 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17998 In order to use the GNAT specific debugging pool, the user must
17999 associate a debug pool object with each of the access types that may be
18000 related to suspected memory problems. See Ada Reference Manual 13.11.
18001 @smallexample @c ada
18002 @b{type} Ptr @b{is} @b{access} Some_Type;
18003 Pool : GNAT.Debug_Pools.Debug_Pool;
18004 @b{for} Ptr'Storage_Pool @b{use} Pool;
18005 @end smallexample
18007 @noindent
18008 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18009 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18010 allow the user to redefine allocation and deallocation strategies. They
18011 also provide a checkpoint for each dereference, through the use of
18012 the primitive operation @code{Dereference} which is implicitly called at
18013 each dereference of an access value.
18015 Once an access type has been associated with a debug pool, operations on
18016 values of the type may raise four distinct exceptions,
18017 which correspond to four potential kinds of memory corruption:
18018 @itemize @bullet
18019 @item
18020 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18021 @item
18022 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18023 @item
18024 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18025 @item
18026 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18027 @end itemize
18029 @noindent
18030 For types associated with a Debug_Pool, dynamic allocation is performed using
18031 the standard GNAT allocation routine. References to all allocated chunks of
18032 memory are kept in an internal dictionary. Several deallocation strategies are
18033 provided, whereupon the user can choose to release the memory to the system,
18034 keep it allocated for further invalid access checks, or fill it with an easily
18035 recognizable pattern for debug sessions. The memory pattern is the old IBM
18036 hexadecimal convention: @code{16#DEADBEEF#}.
18038 See the documentation in the file g-debpoo.ads for more information on the
18039 various strategies.
18041 Upon each dereference, a check is made that the access value denotes a
18042 properly allocated memory location. Here is a complete example of use of
18043 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18044 @smallexample @c ada
18045 @iftex
18046 @leftskip=0cm
18047 @end iftex
18048 @b{with} Gnat.Io; @b{use} Gnat.Io;
18049 @b{with} Unchecked_Deallocation;
18050 @b{with} Unchecked_Conversion;
18051 @b{with} GNAT.Debug_Pools;
18052 @b{with} System.Storage_Elements;
18053 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
18054 @b{procedure} Debug_Pool_Test @b{is}
18056    @b{type} T @b{is} @b{access} Integer;
18057    @b{type} U @b{is} @b{access} @b{all} T;
18059    P : GNAT.Debug_Pools.Debug_Pool;
18060    @b{for} T'Storage_Pool @b{use} P;
18062    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
18063    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
18064    A, B : @b{aliased} T;
18066    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
18068 @b{begin}
18069    Info (P);
18070    A := @b{new} Integer;
18071    B := @b{new} Integer;
18072    B := A;
18073    Info (P);
18074    Free (A);
18075    @b{begin}
18076       Put_Line (Integer'Image(B.@b{all}));
18077    @b{exception}
18078       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18079    @b{end};
18080    @b{begin}
18081       Free (B);
18082    @b{exception}
18083       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18084    @b{end};
18085    B := UC(A'Access);
18086    @b{begin}
18087       Put_Line (Integer'Image(B.@b{all}));
18088    @b{exception}
18089       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18090    @b{end};
18091    @b{begin}
18092       Free (B);
18093    @b{exception}
18094       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18095    @b{end};
18096    Info (P);
18097 @b{end} Debug_Pool_Test;
18098 @end smallexample
18100 @noindent
18101 The debug pool mechanism provides the following precise diagnostics on the
18102 execution of this erroneous program:
18103 @smallexample
18104 Debug Pool info:
18105   Total allocated bytes :  0
18106   Total deallocated bytes :  0
18107   Current Water Mark:  0
18108   High Water Mark:  0
18110 Debug Pool info:
18111   Total allocated bytes :  8
18112   Total deallocated bytes :  0
18113   Current Water Mark:  8
18114   High Water Mark:  8
18116 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18117 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18118 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18119 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18120 Debug Pool info:
18121   Total allocated bytes :  8
18122   Total deallocated bytes :  4
18123   Current Water Mark:  4
18124   High Water Mark:  8
18125 @end smallexample
18127 @ifclear FSFEDITION
18128 @node The gnatmem Tool
18129 @section The @command{gnatmem} Tool
18130 @findex gnatmem
18132 @noindent
18133 The @code{gnatmem} utility monitors dynamic allocation and
18134 deallocation activity in a program, and displays information about
18135 incorrect deallocations and possible sources of memory leaks.
18136 It is designed to work in association with a static runtime library
18137 only and in this context provides three types of information:
18138 @itemize @bullet
18139 @item
18140 General information concerning memory management, such as the total
18141 number of allocations and deallocations, the amount of allocated
18142 memory and the high water mark, i.e.@: the largest amount of allocated
18143 memory in the course of program execution.
18145 @item
18146 Backtraces for all incorrect deallocations, that is to say deallocations
18147 which do not correspond to a valid allocation.
18149 @item
18150 Information on each allocation that is potentially the origin of a memory
18151 leak.
18152 @end itemize
18154 @menu
18155 * Running gnatmem::
18156 * Switches for gnatmem::
18157 * Example of gnatmem Usage::
18158 @end menu
18160 @node Running gnatmem
18161 @subsection Running @code{gnatmem}
18163 @noindent
18164 @code{gnatmem} makes use of the output created by the special version of
18165 allocation and deallocation routines that record call information. This allows
18166 it to obtain accurate dynamic memory usage history at a minimal cost to the
18167 execution speed. Note however, that @code{gnatmem} is not supported on all
18168 platforms (currently, it is supported on AIX, HP-UX, GNU/Linux, Solaris and
18169 Windows NT/2000/XP (x86).
18171 @noindent
18172 The @code{gnatmem} command has the form
18174 @smallexample
18175 @c    $ gnatmem @ovar{switches} user_program
18176 @c Expanding @ovar macro inline (explanation in macro def comments)
18177       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18178 @end smallexample
18180 @noindent
18181 The program must have been linked with the instrumented version of the
18182 allocation and deallocation routines. This is done by linking with the
18183 @file{libgmem.a} library. For correct symbolic backtrace information,
18184 the user program should be compiled with debugging options
18185 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18187 @smallexample
18188 $ gnatmake -g my_program -largs -lgmem
18189 @end smallexample
18191 @noindent
18192 As library @file{libgmem.a} contains an alternate body for package
18193 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18194 when an executable is linked with library @file{libgmem.a}. It is then not
18195 recommended to use @command{gnatmake} with switch @option{-a}.
18197 @noindent
18198 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18199 This file contains information about all allocations and deallocations
18200 performed by the program. It is produced by the instrumented allocations and
18201 deallocations routines and will be used by @code{gnatmem}.
18203 In order to produce symbolic backtrace information for allocations and
18204 deallocations performed by the GNAT run-time library, you need to use a
18205 version of that library that has been compiled with the @option{-g} switch
18206 (see @ref{Rebuilding the GNAT Run-Time Library}).
18208 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18209 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18210 @option{-i} switch, gnatmem will assume that this file can be found in the
18211 current directory. For example, after you have executed @file{my_program},
18212 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18214 @smallexample
18215 $ gnatmem my_program
18216 @end smallexample
18218 @noindent
18219 This will produce the output with the following format:
18221 *************** debut cc
18222 @smallexample
18223 $ gnatmem my_program
18225 Global information
18226 ------------------
18227    Total number of allocations        :  45
18228    Total number of deallocations      :   6
18229    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18230    High Water Mark                    :  11.40 Kilobytes
18235 Allocation Root # 2
18236 -------------------
18237  Number of non freed allocations    :  11
18238  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18239  High Water Mark                    :   1.27 Kilobytes
18240  Backtrace                          :
18241    my_program.adb:23 my_program.alloc
18245 @end smallexample
18247 The first block of output gives general information. In this case, the
18248 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18249 Unchecked_Deallocation routine occurred.
18251 @noindent
18252 Subsequent paragraphs display  information on all allocation roots.
18253 An allocation root is a specific point in the execution of the program
18254 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18255 construct. This root is represented by an execution backtrace (or subprogram
18256 call stack). By default the backtrace depth for allocations roots is 1, so
18257 that a root corresponds exactly to a source location. The backtrace can
18258 be made deeper, to make the root more specific.
18260 @node Switches for gnatmem
18261 @subsection Switches for @code{gnatmem}
18263 @noindent
18264 @code{gnatmem} recognizes the following switches:
18266 @table @option
18268 @item -q
18269 @cindex @option{-q} (@code{gnatmem})
18270 Quiet. Gives the minimum output needed to identify the origin of the
18271 memory leaks. Omits statistical information.
18273 @item @var{N}
18274 @cindex @var{N} (@code{gnatmem})
18275 N is an integer literal (usually between 1 and 10) which controls the
18276 depth of the backtraces defining allocation root. The default value for
18277 N is 1. The deeper the backtrace, the more precise the localization of
18278 the root. Note that the total number of roots can depend on this
18279 parameter. This parameter must be specified @emph{before} the name of the
18280 executable to be analyzed, to avoid ambiguity.
18282 @item -b n
18283 @cindex @option{-b} (@code{gnatmem})
18284 This switch has the same effect as just depth parameter.
18286 @item -i @var{file}
18287 @cindex @option{-i} (@code{gnatmem})
18288 Do the @code{gnatmem} processing starting from @file{file}, rather than
18289 @file{gmem.out} in the current directory.
18291 @item -m n
18292 @cindex @option{-m} (@code{gnatmem})
18293 This switch causes @code{gnatmem} to mask the allocation roots that have less
18294 than n leaks.  The default value is 1. Specifying the value of 0 will allow
18295 examination of even the roots that did not result in leaks.
18297 @item -s order
18298 @cindex @option{-s} (@code{gnatmem})
18299 This switch causes @code{gnatmem} to sort the allocation roots according to the
18300 specified order of sort criteria, each identified by a single letter. The
18301 currently supported criteria are @code{n, h, w} standing respectively for
18302 number of unfreed allocations, high watermark, and final watermark
18303 corresponding to a specific root. The default order is @code{nwh}.
18305 @item -t
18306 @cindex @option{-t} (@code{gnatmem})
18307 This switch causes memory allocated size to be always output in bytes.
18308 Default @code{gnatmem} behavior is to show memory sizes less then 1 kilobyte
18309 in bytes, from 1 kilobyte till 1 megabyte in kilobytes and the rest in
18310 megabytes.
18312 @end table
18314 @node Example of gnatmem Usage
18315 @subsection Example of @code{gnatmem} Usage
18317 @noindent
18318 The following example shows the use of @code{gnatmem}
18319 on a simple memory-leaking program.
18320 Suppose that we have the following Ada program:
18322 @smallexample @c ada
18323 @group
18324 @cartouche
18325 @b{with} Unchecked_Deallocation;
18326 @b{procedure} Test_Gm @b{is}
18328    @b{type} T @b{is} @b{array} (1..1000) @b{of} Integer;
18329    @b{type} Ptr @b{is} @b{access} T;
18330    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (T, Ptr);
18331    A : Ptr;
18333    @b{procedure} My_Alloc @b{is}
18334    @b{begin}
18335       A := @b{new} T;
18336    @b{end} My_Alloc;
18338    @b{procedure} My_DeAlloc @b{is}
18339       B : Ptr := A;
18340    @b{begin}
18341       Free (B);
18342    @b{end} My_DeAlloc;
18344 @b{begin}
18345    My_Alloc;
18346    @b{for} I @b{in} 1 .. 5 @b{loop}
18347       @b{for} J @b{in} I .. 5 @b{loop}
18348          My_Alloc;
18349       @b{end} @b{loop};
18350       My_Dealloc;
18351    @b{end} @b{loop};
18352 @b{end};
18353 @end cartouche
18354 @end group
18355 @end smallexample
18357 @noindent
18358 The program needs to be compiled with debugging option and linked with
18359 @code{gmem} library:
18361 @smallexample
18362 $ gnatmake -g test_gm -largs -lgmem
18363 @end smallexample
18365 @noindent
18366 Then we execute the program as usual:
18368 @smallexample
18369 $ test_gm
18370 @end smallexample
18372 @noindent
18373 Then @code{gnatmem} is invoked simply with
18374 @smallexample
18375 $ gnatmem test_gm
18376 @end smallexample
18378 @noindent
18379 which produces the following output (result may vary on different platforms):
18381 @smallexample
18382 Global information
18383 ------------------
18384    Total number of allocations        :  18
18385    Total number of deallocations      :   5
18386    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18387    High Water Mark                    :  56.90 Kilobytes
18389 Allocation Root # 1
18390 -------------------
18391  Number of non freed allocations    :  11
18392  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18393  High Water Mark                    :  46.88 Kilobytes
18394  Backtrace                          :
18395    test_gm.adb:11 test_gm.my_alloc
18397 Allocation Root # 2
18398 -------------------
18399  Number of non freed allocations    :   1
18400  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18401  High Water Mark                    :  10.02 Kilobytes
18402  Backtrace                          :
18403    s-secsta.adb:81 system.secondary_stack.ss_init
18405 Allocation Root # 3
18406 -------------------
18407  Number of non freed allocations    :   1
18408  Final Water Mark (non freed mem)   :  12 Bytes
18409  High Water Mark                    :  12 Bytes
18410  Backtrace                          :
18411    s-secsta.adb:181 system.secondary_stack.ss_init
18412 @end smallexample
18414 @noindent
18415 Note that the GNAT run time contains itself a certain number of
18416 allocations that have no  corresponding deallocation,
18417 as shown here for root #2 and root
18418 #3. This is a normal behavior when the number of non-freed allocations
18419 is one, it allocates dynamic data structures that the run time needs for
18420 the complete lifetime of the program. Note also that there is only one
18421 allocation root in the user program with a single line back trace:
18422 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18423 program shows that 'My_Alloc' is called at 2 different points in the
18424 source (line 21 and line 24). If those two allocation roots need to be
18425 distinguished, the backtrace depth parameter can be used:
18427 @smallexample
18428 $ gnatmem 3 test_gm
18429 @end smallexample
18431 @noindent
18432 which will give the following output:
18434 @smallexample
18435 Global information
18436 ------------------
18437    Total number of allocations        :  18
18438    Total number of deallocations      :   5
18439    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18440    High Water Mark                    :  56.90 Kilobytes
18442 Allocation Root # 1
18443 -------------------
18444  Number of non freed allocations    :  10
18445  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18446  High Water Mark                    :  42.97 Kilobytes
18447  Backtrace                          :
18448    test_gm.adb:11 test_gm.my_alloc
18449    test_gm.adb:24 test_gm
18450    b_test_gm.c:52 main
18452 Allocation Root # 2
18453 -------------------
18454  Number of non freed allocations    :   1
18455  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18456  High Water Mark                    :  10.02 Kilobytes
18457  Backtrace                          :
18458    s-secsta.adb:81  system.secondary_stack.ss_init
18459    s-secsta.adb:283 <system__secondary_stack___elabb>
18460    b_test_gm.c:33   adainit
18462 Allocation Root # 3
18463 -------------------
18464  Number of non freed allocations    :   1
18465  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18466  High Water Mark                    :   3.91 Kilobytes
18467  Backtrace                          :
18468    test_gm.adb:11 test_gm.my_alloc
18469    test_gm.adb:21 test_gm
18470    b_test_gm.c:52 main
18472 Allocation Root # 4
18473 -------------------
18474  Number of non freed allocations    :   1
18475  Final Water Mark (non freed mem)   :  12 Bytes
18476  High Water Mark                    :  12 Bytes
18477  Backtrace                          :
18478    s-secsta.adb:181 system.secondary_stack.ss_init
18479    s-secsta.adb:283 <system__secondary_stack___elabb>
18480    b_test_gm.c:33   adainit
18481 @end smallexample
18483 @noindent
18484 The allocation root #1 of the first example has been split in 2 roots #1
18485 and #3 thanks to the more precise associated backtrace.
18486 @end ifclear
18488 @node Stack Related Facilities
18489 @chapter Stack Related Facilities
18491 @noindent
18492 This chapter describes some useful tools associated with stack
18493 checking and analysis. In
18494 particular, it deals with dynamic and static stack usage measurements.
18496 @menu
18497 * Stack Overflow Checking::
18498 * Static Stack Usage Analysis::
18499 * Dynamic Stack Usage Analysis::
18500 @end menu
18502 @node Stack Overflow Checking
18503 @section Stack Overflow Checking
18504 @cindex Stack Overflow Checking
18505 @cindex -fstack-check
18507 @noindent
18508 For most operating systems, @command{gcc} does not perform stack overflow
18509 checking by default. This means that if the main environment task or
18510 some other task exceeds the available stack space, then unpredictable
18511 behavior will occur. Most native systems offer some level of protection by
18512 adding a guard page at the end of each task stack. This mechanism is usually
18513 not enough for dealing properly with stack overflow situations because
18514 a large local variable could ``jump'' above the guard page.
18515 Furthermore, when the
18516 guard page is hit, there may not be any space left on the stack for executing
18517 the exception propagation code. Enabling stack checking avoids
18518 such situations.
18520 To activate stack checking, compile all units with the gcc option
18521 @option{-fstack-check}. For example:
18523 @smallexample
18524 gcc -c -fstack-check package1.adb
18525 @end smallexample
18527 @noindent
18528 Units compiled with this option will generate extra instructions to check
18529 that any use of the stack (for procedure calls or for declaring local
18530 variables in declare blocks) does not exceed the available stack space.
18531 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18533 For declared tasks, the stack size is controlled by the size
18534 given in an applicable @code{Storage_Size} pragma or by the value specified
18535 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18536 the default size as defined in the GNAT runtime otherwise.
18538 For the environment task, the stack size depends on
18539 system defaults and is unknown to the compiler. Stack checking
18540 may still work correctly if a fixed
18541 size stack is allocated, but this cannot be guaranteed.
18542 To ensure that a clean exception is signalled for stack
18543 overflow, set the environment variable
18544 @env{GNAT_STACK_LIMIT} to indicate the maximum
18545 stack area that can be used, as in:
18546 @cindex GNAT_STACK_LIMIT
18548 @smallexample
18549 SET GNAT_STACK_LIMIT 1600
18550 @end smallexample
18552 @noindent
18553 The limit is given in kilobytes, so the above declaration would
18554 set the stack limit of the environment task to 1.6 megabytes.
18555 Note that the only purpose of this usage is to limit the amount
18556 of stack used by the environment task. If it is necessary to
18557 increase the amount of stack for the environment task, then this
18558 is an operating systems issue, and must be addressed with the
18559 appropriate operating systems commands.
18561 @node Static Stack Usage Analysis
18562 @section Static Stack Usage Analysis
18563 @cindex Static Stack Usage Analysis
18564 @cindex -fstack-usage
18566 @noindent
18567 A unit compiled with @option{-fstack-usage} will generate an extra file
18568 that specifies
18569 the maximum amount of stack used, on a per-function basis.
18570 The file has the same
18571 basename as the target object file with a @file{.su} extension.
18572 Each line of this file is made up of three fields:
18574 @itemize
18575 @item
18576 The name of the function.
18577 @item
18578 A number of bytes.
18579 @item
18580 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18581 @end itemize
18583 The second field corresponds to the size of the known part of the function
18584 frame.
18586 The qualifier @code{static} means that the function frame size
18587 is purely static.
18588 It usually means that all local variables have a static size.
18589 In this case, the second field is a reliable measure of the function stack
18590 utilization.
18592 The qualifier @code{dynamic} means that the function frame size is not static.
18593 It happens mainly when some local variables have a dynamic size. When this
18594 qualifier appears alone, the second field is not a reliable measure
18595 of the function stack analysis. When it is qualified with  @code{bounded}, it
18596 means that the second field is a reliable maximum of the function stack
18597 utilization.
18599 A unit compiled with @option{-Wstack-usage} will issue a warning for each
18600 subprogram whose stack usage might be larger than the specified amount of
18601 bytes.  The wording is in keeping with the qualifier documented above.
18603 @node Dynamic Stack Usage Analysis
18604 @section Dynamic Stack Usage Analysis
18606 @noindent
18607 It is possible to measure the maximum amount of stack used by a task, by
18608 adding a switch to @command{gnatbind}, as:
18610 @smallexample
18611 $ gnatbind -u0 file
18612 @end smallexample
18614 @noindent
18615 With this option, at each task termination, its stack usage is  output on
18616 @file{stderr}.
18617 It is not always convenient to output the stack usage when the program
18618 is still running. Hence, it is possible to delay this output until program
18619 termination. for a given number of tasks specified as the argument of the
18620 @option{-u} option. For instance:
18622 @smallexample
18623 $ gnatbind -u100 file
18624 @end smallexample
18626 @noindent
18627 will buffer the stack usage information of the first 100 tasks to terminate and
18628 output this info at program termination. Results are displayed in four
18629 columns:
18631 @noindent
18632 Index | Task Name | Stack Size | Stack Usage
18634 @noindent
18635 where:
18637 @table @emph
18638 @item Index
18639 is a number associated with each task.
18641 @item Task Name
18642 is the name of the task analyzed.
18644 @item Stack Size
18645 is the maximum size for the stack.
18647 @item Stack Usage
18648 is the measure done by the stack analyzer. In order to prevent overflow, the stack
18649 is not entirely analyzed, and it's not possible to know exactly how
18650 much has actually been used.
18652 @end table
18654 @noindent
18655 The environment task stack, e.g., the stack that contains the main unit, is
18656 only processed when the environment variable GNAT_STACK_LIMIT is set.
18658 @noindent
18659 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
18660 stack usage reports at run-time. See its body for the details.
18662 @ifclear FSFEDITION
18663 @c *********************************
18664 @c *            GNATCHECK          *
18665 @c *********************************
18666 @node Verifying Properties with gnatcheck
18667 @chapter Verifying Properties with @command{gnatcheck}
18668 @findex gnatcheck
18669 @cindex @command{gnatcheck}
18671 @noindent
18672 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18673 of Ada source files according to a given set of semantic rules.
18674 @cindex ASIS
18676 In order to check compliance with a given rule, @command{gnatcheck} has to
18677 semantically analyze the Ada sources.
18678 Therefore, checks can only be performed on
18679 legal Ada units. Moreover, when a unit depends semantically upon units located
18680 outside the current directory, the source search path has to be provided when
18681 calling @command{gnatcheck}, either through a specified project file or
18682 through @command{gnatcheck} switches.
18684 For full details, refer to @cite{GNATcheck Reference Manual} document.
18685 @end ifclear
18687 @ifclear FSFEDITION
18688 @c *********************************
18689 @node Creating Sample Bodies with gnatstub
18690 @chapter Creating Sample Bodies with @command{gnatstub}
18691 @findex gnatstub
18693 @noindent
18694 @command{gnatstub} creates empty but compilable bodies
18695 for library unit declarations and empty but compilable
18696 subunit for body stubs.
18698 To create a body or a subunit, @command{gnatstub} invokes the Ada
18699 compiler and generates and uses the ASIS tree for the input source;
18700 thus the input must be legal Ada code, and the tool should have all the
18701 information needed to compile the input source. To provide this information,
18702 you may specify as a tool parameter the project file the input source belongs to
18703 (or you may call @command{gnatstub}
18704 through the @command{gnat} driver (see @ref{The GNAT Driver and
18705 Project Files}). Another possibility is to specify the source search
18706 path and needed configuration files in @option{-cargs} section of @command{gnatstub}
18707 call, see the description of the @command{gnatstub} switches below.
18709 If the @command{gnatstub} argument source contains preprocessing directives
18710 then the needed options should be provided to run preprocessor as a part of
18711 the @command{gnatstub} call, and the generated body stub will correspond to
18712 the preprocessed source.
18714 By default, all the program unit bodies generated by @code{gnatstub}
18715 raise the predefined @code{Program_Error} exception, which will catch
18716 accidental calls of generated stubs. This behavior can be changed with
18717 option @option{--no-exception} (see below).
18719 @menu
18720 * Running gnatstub::
18721 * Switches for gnatstub::
18722 @end menu
18724 @node Running gnatstub
18725 @section Running @command{gnatstub}
18727 @noindent
18728 @command{gnatstub} has a command-line interface of the form:
18730 @smallexample
18731 @c $ gnatstub @ovar{switches} @var{filename}
18732 @c Expanding @ovar macro inline (explanation in macro def comments)
18733 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
18734 @end smallexample
18736 @noindent
18737 where
18738 @table @var
18739 @item filename
18740 is the name of the source file that contains a library unit declaration
18741 for which a body must be created or a library unit body for which subunits
18742 must be created for the body stubs declared in this body.
18743 The file name may contain the path information.
18744 If the name does not follow GNAT file naming conventions and a set
18745 of seitches does not contain a project file that defines naming
18746 conventions, the name of the body file must
18747 be provided
18748 explicitly as the value of the @option{-o@var{body-name}} option.
18749 If the file name follows the GNAT file naming
18750 conventions and the name of the body file is not provided,
18751 @command{gnatstub}
18752 takes the naming conventions for the generated source from the
18753 project file provided as a parameter of @option{-P} switch if any,
18754 or creates the name file to generate using the standard GNAT
18755 naming conventions.
18757 @item @samp{@var{gcc_switches}} is a list of switches for
18758 @command{gcc}. They will be passed on to all compiler invocations made by
18759 @command{gnatstub} to generate the ASIS trees. Here you can provide
18760 @option{-I} switches to form the source search path,
18761 use the @option{-gnatec} switch to set the configuration file,
18762 use the @option{-gnat05} switch if sources should be compiled in
18763 Ada 2005 mode etc.
18765 @item switches
18766 is an optional sequence of switches as described in the next section
18767 @end table
18769 @node Switches for gnatstub
18770 @section Switches for @command{gnatstub}
18772 @table @option
18773 @c !sort!
18775 @item --version
18776 @cindex @option{--version} @command{gnatstub}
18777 Display Copyright and version, then exit disregarding all other options.
18779 @item --help
18780 @cindex @option{--help} @command{gnatstub}
18781 Display usage, then exit disregarding all other options.
18783 @item -P @var{file}
18784 @cindex @option{-P} @command{gnatstub}
18785 Indicates the name of the project file that describes the set of sources
18786 to be processed.
18788 @item -X@var{name}=@var{value}
18789 @cindex @option{-X} @command{gnatstub}
18790 Indicates that external variable @var{name} in the argument project
18791 has the value @var{value}. Has no effect if no project is specified as
18792 tool argument.
18794 @item --RTS=@var{rts-path}
18795 @cindex @option{--RTS} (@command{gnatstub})
18796 Specifies the default location of the runtime library. Same meaning as the
18797 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18799 @item --subunits
18800 @cindex @option{--subunits} (@command{gnatstub})
18801 Generate subunits for body stubs. If this switch is specified,
18802 @command{gnatstub} expects a library unit body as an agrument file,
18803 otherwise a library unit declaration is expected. If a body stub
18804 already has a corresponding subunit, @command{gnatstub} does not
18805 generate anything for it.
18807 @item -f
18808 @cindex @option{-f} (@command{gnatstub})
18809 If the destination directory already contains a file with the name of the
18810 body file
18811 for the argument spec file, replace it with the generated body stub.
18812 This switch cannot be used together with @option{--subunits}.
18814 @item -hs
18815 @cindex @option{-hs} (@command{gnatstub})
18816 Put the comment header (i.e., all the comments preceding the
18817 compilation unit) from the source of the library unit declaration
18818 into the body stub.
18820 @item -hg
18821 @cindex @option{-hg} (@command{gnatstub})
18822 Put a sample comment header into the body stub.
18824 @item --header-file=@var{filename}
18825 @cindex @option{--header-file} (@command{gnatstub})
18826 Use the content of the file as the comment header for a generated body stub.
18828 @item -IDIR
18829 @cindex @option{-IDIR} (@command{gnatstub})
18830 @itemx -I-
18831 @cindex @option{-I-} (@command{gnatstub})
18832 These switches have  the same meaning as in calls to
18833 @command{gcc}.
18834 They define  the source search path in the call to
18835 @command{gcc} issued
18836 by @command{gnatstub} to compile an argument source file.
18838 @item -gnatec@var{PATH}
18839 @cindex @option{-gnatec} (@command{gnatstub})
18840 This switch has the same meaning as in calls to @command{gcc}.
18841 It defines the additional configuration file to be passed to the call to
18842 @command{gcc} issued
18843 by @command{gnatstub} to compile an argument source file.
18845 @item -gnatyM@var{n}
18846 @cindex @option{-gnatyM} (@command{gnatstub})
18847 (@var{n} is a non-negative integer). Set the maximum line length that is
18848 allowed in a source file. The default is 79. The maximum value that can be
18849 specified is 32767. Note that in the special case of configuration
18850 pragma files, the maximum is always 32767 regardless of whether or
18851 not this switch appears.
18853 @item -gnaty@var{n}
18854 @cindex @option{-gnaty} (@command{gnatstub})
18855 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18856 the generated body sample to @var{n}.
18857 The default indentation is 3.
18859 @item -gnatyo
18860 @cindex @option{-gnatyo} (@command{gnatstub})
18861 Order local bodies alphabetically. (By default local bodies are ordered
18862 in the same way as the corresponding local specs in the argument spec file.)
18864 @item -i@var{n}
18865 @cindex @option{-i} (@command{gnatstub})
18866 Same as @option{-gnaty@var{n}}
18868 @item -k
18869 @cindex @option{-k} (@command{gnatstub})
18870 Do not remove the tree file (i.e., the snapshot of the compiler internal
18871 structures used by @command{gnatstub}) after creating the body stub.
18873 @item -l@var{n}
18874 @cindex @option{-l} (@command{gnatstub})
18875 Same as @option{-gnatyM@var{n}}
18877 @item --no-exception
18878 @cindex @option{--no-exception} (@command{gnatstub})
18879 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18880 This is not always possible for function stubs.
18882 @item --no-local-header
18883 @cindex @option{--no-local-header} (@command{gnatstub})
18884 Do not place local comment header with unit name before body stub for a
18885 unit.
18887 @item -o @var{body-name}
18888 @cindex @option{-o} (@command{gnatstub})
18889 Body file name.  This should be set if the argument file name does not
18890 follow
18891 the GNAT file naming
18892 conventions. If this switch is omitted the default name for the body will be
18893 obtained
18894 from the argument file name according to the GNAT file naming conventions.
18896 @item --dir=@var{dir-name}
18897 @cindex @option{--dir} (@command{gnatstub})
18898 The path to the directory to place the generated files into.
18899 If this switch is not set, the generated library unit body is
18900 placed in the current directory, and generated sununits -
18901 in the directory where the argument body is located.
18903 @item -W@var{e}
18904 @cindex @option{-W} (@command{gnatstub})
18905 Specify the wide character encoding method for the output body file.
18906 @var{e} is one of the following:
18908 @itemize @bullet
18910 @item h
18911 Hex encoding
18913 @item u
18914 Upper half encoding
18916 @item s
18917 Shift/JIS encoding
18919 @item e
18920 EUC encoding
18922 @item 8
18923 UTF-8 encoding
18925 @item b
18926 Brackets encoding (default value)
18927 @end itemize
18929 @item -q
18930 @cindex @option{-q} (@command{gnatstub})
18931 Quiet mode: do not generate a confirmation when a body is
18932 successfully created, and do not generate a message when a body is not
18933 required for an
18934 argument unit.
18936 @item -r
18937 @cindex @option{-r} (@command{gnatstub})
18938 Reuse the tree file (if it exists) instead of creating it.  Instead of
18939 creating the tree file for the library unit declaration, @command{gnatstub}
18940 tries to find it in the current directory and use it for creating
18941 a body. If the tree file is not found, no body is created. This option
18942 also implies @option{-k}, whether or not
18943 the latter is set explicitly.
18945 @item -t
18946 @cindex @option{-t} (@command{gnatstub})
18947 Overwrite the existing tree file.  If the current directory already
18948 contains the file which, according to the GNAT file naming rules should
18949 be considered as a tree file for the argument source file,
18950 @command{gnatstub}
18951 will refuse to create the tree file needed to create a sample body
18952 unless this option is set.
18954 @item -v
18955 @cindex @option{-v} (@command{gnatstub})
18956 Verbose mode: generate version information.
18958 @end table
18959 @end ifclear
18961 @ifclear FSFEDITION
18962 @c *********************************
18963 @node Creating Unit Tests with gnattest
18964 @chapter Creating Unit Tests with @command{gnattest}
18965 @findex gnattest
18967 @noindent
18968 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
18969 as well as a test driver infrastructure (harness). @command{gnattest} creates
18970 a skeleton for each visible subprogram in the packages under consideration when
18971 they do not exist already.
18973 The user can choose to generate a single test driver
18974 that will run all individual tests, or separate test drivers for each test. The
18975 second option allows much greater flexibility in test execution environment,
18976 allows to benefit from parallel tests execution to increase performance, and
18977 provides stubbing support.
18979 @command{gnattest} also has a mode of operation where it acts as the test
18980 aggregator when multiple test executables must be run, in particular when
18981 the separate test drivers were generated. In this mode it handles individual
18982 tests execution and upon completion reports the summary results of the test
18983 run.
18985 In order to process source files from a project, @command{gnattest} has to
18986 semantically analyze the sources. Therefore, test skeletons can only be
18987 generated for legal Ada units. If a unit is dependent on other units,
18988 those units should be among the source files of the project or of other projects
18989 imported by this one.
18991 Generated skeletons and harnesses are based on the AUnit testing framework.
18992 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
18993 for Java or CppUnit for C++. While it is advised that gnattest users read
18994 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
18995 For correct operation of @command{gnattest}, AUnit should be installed and
18996 aunit.gpr must be on the project path. This happens automatically when Aunit
18997 is installed at its default location.
18999 @menu
19000 * Running gnattest::
19001 * Switches for gnattest in framework generation mode::
19002 * Switches for gnattest in tests execution mode::
19003 * Project Attributes for gnattest::
19004 * Simple Example::
19005 * Setting Up and Tearing Down the Testing Environment::
19006 * Regenerating Tests::
19007 * Default Test Behavior::
19008 * Testing Primitive Operations of Tagged Types::
19009 * Testing Inheritance::
19010 * Tagged Types Substitutability Testing::
19011 * Testing with Contracts::
19012 * Additional Tests::
19013 * Individual Test Drivers::
19014 * Stubbing::
19015 * Putting Tests under Version Control::
19016 * Support for other platforms/run-times::
19017 * Current Limitations::
19018 @end menu
19020 @node Running gnattest
19021 @section Running @command{gnattest}
19023 @noindent
19024 @b{In the framework generation mode}, @command{gnattest} has a command-line
19025 interface of the form
19027 @smallexample
19028 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19029 @c Expanding @ovar macro inline (explanation in macro def comments)
19030 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19031 @end smallexample
19033 @noindent
19034 where
19035 @table @var
19037 @item -Pprojname
19038 specifies the project defining the location of source files. When no
19039 file names are provided on the command line, all sources in the project
19040 are used as input. This switch is required.
19042 @item filename
19043 is the name of the source file containing the library unit package declaration
19044 for which a test package will be created. The file name may be given with a
19045 path.
19047 @item @samp{@var{gcc_switches}}
19048 is a list of switches for
19049 @command{gcc}. These switches will be passed on to all compiler invocations
19050 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19051 @option{-I} switches to form the source search path,
19052 use the @option{-gnatec} switch to set the configuration file,
19053 use the @option{-gnat05} switch if sources should be compiled in
19054 Ada 2005 mode, etc.
19056 @item switches
19057 is an optional sequence of switches as described in the next section.
19059 @end table
19061 @command{gnattest} results can be found in two different places.
19063 @itemize @bullet
19064 @item automatic harness:
19065 the harness code, which is located by default in "gnattest/harness" directory
19066 that is created in the object directory of corresponding project file. All of
19067 this code is generated completely automatically and can be destroyed and
19068 regenerated at will. It is not recommended to modify this code manually, since
19069 it could easily be overridden by mistake. The entry point in the harness code is
19070 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19071 using a command such as:
19073 @smallexample
19074 gnatmake -P<harness-dir>/test_driver
19075 test_runner
19076 @end smallexample
19078 Note that you might need to specify the necessary values of scenario variables
19079 when you are not using the AUnit defaults.
19081 @item actual unit test skeletons:
19082 a test skeleton for each visible subprogram is created in a separate file, if it
19083 doesn't exist already. By default, those separate test files are located in a
19084 "gnattest/tests" directory that is created in the object directory of
19085 corresponding project file. For example, if a source file my_unit.ads in
19086 directory src contains a visible subprogram Proc, then the corresponding unit
19087 test will be found in file src/tests/my_unit-test_data-tests.adb and will be
19088 called Test_Proc_<code>. <code> is a signature encoding used to differentiate
19089 test names in case of overloading.
19091 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19092 this will cause a name conflict with the generated test package.
19093 @end itemize
19096 @noindent
19097 @b{In the tests execution mode mode}, @command{gnattest} has a command-line
19098 interface of the form
19100 @smallexample
19101 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19102 @c Expanding @ovar macro inline (explanation in macro def comments)
19103 $ gnattest @var{test_drivers.list} @r{[}@var{switches}@r{]}
19104 @end smallexample
19106 @noindent
19107 where
19108 @table @var
19110 @item test_drivers.list
19111 is the name of the text file containing the list of executables to treat as
19112 test drivers. This file is automatically generated by gnattest, but can be
19113 hand-edited to add or remove tests. This switch is required.
19115 @item switches
19116 is an optional sequence of switches as described below.
19118 @end table
19121 @node Switches for gnattest in framework generation mode
19122 @section Switches for @command{gnattest} in framework generation mode
19124 @table @option
19125 @c !sort!
19127 @item -q
19128 @cindex @option{-q} (@command{gnattest})
19129 Quiet mode: suppresses noncritical output messages.
19131 @item -v
19132 @cindex @option{-v} (@command{gnattest})
19133 Verbose mode: generates version information if specified by itself on the
19134 command line.  If specified via GNATtest_Switches, produces output
19135 about the execution of the tool.
19137 @item -r
19138 @cindex @option{-r} (@command{gnattest})
19139 Recursively considers all sources from all projects.
19142 @item -X@var{name=value}
19143 @cindex @option{-X} (@command{gnattest})
19144 Indicate that external variable @var{name} has the value @var{value}.
19146 @item --RTS=@var{rts-path}
19147 @cindex @option{--RTS} (@command{gnattest})
19148 Specifies the default location of the runtime library. Same meaning as the
19149 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
19152 @item --additional-tests=@var{projname}
19153 @cindex @option{--additional-tests} (@command{gnattest})
19154 Sources described in @var{projname} are considered potential additional
19155 manual tests to be added to the test suite.
19157 @item --harness-only
19158 @cindex @option{--harness-only} (@command{gnattest})
19159 When this option is given, @command{gnattest} creates a harness for all
19160 sources, treating them as test packages.
19162 @item --separate-drivers
19163 @cindex @option{--separate-drivers} (@command{gnattest})
19164 Generates a separate test driver for each test, rather than a single
19165 executable incorporating all tests.
19167 @item --stub
19168 @cindex @option{--stub} (@command{gnattest})
19169 Generates the testing framework that uses subsystem stubbing to isolate the
19170 code under test.
19173 @item --harness-dir=@var{dirname}
19174 @cindex @option{--harness-dir} (@command{gnattest})
19175 Specifies the directory that will hold the harness packages and project file
19176 for the test driver. If the @var{dirname} is a relative path, it is considered
19177 relative to the object directory of the project file.
19179 @item --tests-dir=@var{dirname}
19180 @cindex @option{--tests-dir} (@command{gnattest})
19181 All test packages are placed in the @var{dirname} directory.
19182 If the @var{dirname} is a relative path, it is considered relative to the object
19183 directory of the project file. When all sources from all projects are taken
19184 recursively from all projects, @var{dirname} directories are created for each
19185 project in their object directories and test packages are placed accordingly.
19187 @item --subdir=@var{dirname}
19188 @cindex @option{--subdir} (@command{gnattest})
19189 Test packages are placed in a subdirectory of the corresponding source
19190 directory, with the name @var{dirname}. Thus, each set of unit tests is located
19191 in a subdirectory of the code under test.  If the sources are in separate
19192 directories, each source directory has a test subdirectory named @var{dirname}.
19194 @item --tests-root=@var{dirname}
19195 @cindex @option{--tests-root} (@command{gnattest})
19196 The hierarchy of source directories, if any, is recreated in the @var{dirname}
19197 directory, with test packages placed in directories corresponding to those
19198 of the sources.
19199 If the @var{dirname} is a relative path, it is considered relative to the object
19200 directory of the project file. When projects are considered recursively,
19201 directory hierarchies of tested sources are
19202 recreated for each project in their object directories and test packages are
19203 placed accordingly.
19205 @item --stubs-dir=@var{dirname}
19206 @cindex @option{--stubs-dir} (@command{gnattest})
19207 The hierarchy of directories containing stubbed units is recreated in
19208 the @var{dirname} directory, with stubs placed in directories corresponding to
19209 projects they are derived from.
19210 If the @var{dirname} is a relative path, it is considered relative to the object
19211 directory of the project file. When projects are considered recursively,
19212 directory hierarchies of stubs are
19213 recreated for each project in their object directories and test packages are
19214 placed accordingly.
19217 @item --validate-type-extensions
19218 @cindex @option{--validate-type-extensions} (@command{gnattest})
19219 Enables substitution check: run all tests from all parents in order
19220 to check substitutability in accordance with LSP.
19222 @item --skeleton-default=@var{val}
19223 @cindex @option{--skeleton-default} (@command{gnattest})
19224 Specifies the default behavior of generated skeletons. @var{val} can be either
19225 "fail" or "pass", "fail" being the default.
19227 @item --passed-tests=@var{val}
19228 @cindex @option{--passed-tests} (@command{gnattest})
19229 Specifies whether or not passed tests should be shown. @var{val} can be either
19230 "show" or "hide", "show" being the default.
19232 @item --exit-status=@var{val}
19233 @cindex @option{--exit-status} (@command{gnattest})
19234 Specifies whether or not generated test driver should return failure exit
19235 status if at least one test fails or crashes. @var{val} can be either
19236 "on" or "off", "off" being the default.
19238 @item --omit-sloc
19239 @cindex @option{--omit-sloc} (@command{gnattest})
19240 Suppresses comment line containing file name and line number of corresponding
19241 subprograms in test skeletons.
19244 @item --separates
19245 @cindex @option{--separates} (@command{gnattest})
19246 Bodies of all test routines are generated as separates. Note that this mode is
19247 kept for compatibility reasons only and it is not advised to use it due to
19248 possible problems with hash in names of test skeletons when using an
19249 inconsistent casing. Separate test skeletons can be incorporated to monolith
19250 test package with improved hash being used by using @option{--transition}
19251 switch.
19254 @item --transition
19255 @cindex @option{--transition} (@command{gnattest})
19256 This allows transition from separate test routines to monolith test packages.
19257 All matching test routines are overwritten with contents of corresponding
19258 separates. Note that if separate test routines had any manually added with
19259 clauses they will be moved to the test package body as is and have to be moved
19260 by hand.
19262 @item --test-duration
19263 @cindex @option{--test-duration} (@command{gnattest})
19264 Adds time measurements for each test in generated test driver.
19266 @end table
19268 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19269 mutually exclusive.
19272 @node Switches for gnattest in tests execution mode
19273 @section Switches for @command{gnattest} in tests execution mode
19275 @table @option
19276 @c !sort!
19278 @item --passed-tests=@var{val}
19279 @cindex @option{--passed-tests} (@command{gnattest})
19280 Specifies whether or not passed tests should be shown. @var{val} can be either
19281 "show" or "hide", "show" being the default.
19283 @item --queues=@var{n}, -j@var{n}
19284 @cindex @option{--queues} (@command{gnattest})
19285 @cindex @option{-j} (@command{gnattest})
19286 Runs @var{n} tests in parallel (default is 1).
19288 @end table
19291 @node Project Attributes for gnattest
19292 @section Project Attributes for @command{gnattest}
19294 @noindent
19296 Most of the command-line options can also be passed to the tool by adding
19297 special attributes to the project file. Those attributes should be put in
19298 package gnattest. Here is the list of attributes:
19300 @itemize @bullet
19302 @item Tests_Root
19303 is used to select the same output mode as with the --tests-root option.
19304 This attribute cannot be used together with Subdir or Tests_Dir.
19306 @item Subdir
19307 is used to select the same output mode as with the --subdir option.
19308 This attribute cannot be used together with Tests_Root or Tests_Dir.
19310 @item Tests_Dir
19311 is used to select the same output mode as with the --tests-dir option.
19312 This attribute cannot be used together with Subdir or Tests_Root.
19314 @item Harness_Dir
19315 is used to specify the directory in which to place harness packages and project
19316 file for the test driver, otherwise specified by --harness-dir.
19318 @item Additional_Tests
19319 is used to specify the project file, otherwise given by
19320 --additional-tests switch.
19322 @item Skeletons_Default
19323 is used to specify the default behaviour of test skeletons, otherwise
19324 specified by --skeleton-default option. The value of this attribute
19325 should be either "pass" or "fail".
19327 @end itemize
19329 Each of those attributes can be overridden from the command line if needed.
19330 Other @command{gnattest} switches can also be passed via the project
19331 file as an attribute list called GNATtest_Switches.
19333 @node Simple Example
19334 @section Simple Example
19336 @noindent
19338 Let's take a very simple example using the first @command{gnattest} example
19339 located in:
19341 @smallexample
19342 <install_prefix>/share/examples/gnattest/simple
19343 @end smallexample
19345 This project contains a simple package containing one subprogram. By running gnattest:
19347 @smallexample
19348 $ gnattest --harness-dir=driver -Psimple.gpr
19349 @end smallexample
19351 a test driver is created in directory "driver". It can be compiled and run:
19353 @smallexample
19354 $ cd obj/driver
19355 $ gnatmake -Ptest_driver
19356 $ test_runner
19357 @end smallexample
19359 One failed test with diagnosis "test not implemented" is reported.
19360 Since no special output option was specified, the test package Simple.Tests
19361 is located in:
19363 @smallexample
19364 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19365 @end smallexample
19367 For each package containing visible subprograms, a child test package is
19368 generated. It contains one test routine per tested subprogram. Each
19369 declaration of a test subprogram has a comment specifying which tested
19370 subprogram it corresponds to. Bodies of test routines are placed in test package
19371 bodies and are surrounded by special comment sections. Those comment sections
19372 should not be removed or modified in order for gnattest to be able to regenerate
19373 test packages and keep already written tests in place.
19374 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19375 a single statement: a call to procedure Assert. It has two arguments:
19376 the Boolean expression we want to check and the diagnosis message to display if
19377 the condition is false.
19379 That is where actual testing code should be written after a proper setup.
19380 An actual check can be performed by replacing the Assert call with:
19382 @smallexample @c ada
19383 Assert (Inc (1) = 2, "wrong incrementation");
19384 @end smallexample
19386 After recompiling and running the test driver, one successfully passed test
19387 is reported.
19389 @node Setting Up and Tearing Down the Testing Environment
19390 @section Setting Up and Tearing Down the Testing Environment
19392 @noindent
19394 Besides test routines themselves, each test package has a parent package
19395 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19396 overwritten by the tool. Set_Up is called before each test routine of the
19397 package and Tear_Down is called after each test routine. Those two procedures
19398 can be used to perform necessary initialization and finalization,
19399 memory allocation, etc. Test type declared in Test_Data package is parent type
19400 for the test type of test package and can have user-defined components whose
19401 values can be set by Set_Up routine and used in test routines afterwards.
19403 @node Regenerating Tests
19404 @section Regenerating Tests
19406 @noindent
19408 Bodies of test routines and test_data packages are never overridden after they
19409 have been created once. As long as the name of the subprogram, full expanded Ada
19410 names, and the order of its parameters is the same, and comment sections are
19411 intact the old test routine will fit in its place and no test skeleton will be
19412 generated for the subprogram.
19414 This can be demonstrated with the previous example. By uncommenting declaration
19415 and body of function Dec in simple.ads and simple.adb, running
19416 @command{gnattest} on the project, and then running the test driver:
19418 @smallexample
19419 gnattest --harness-dir=driver -Psimple.gpr
19420 cd obj/driver
19421 gnatmake -Ptest_driver
19422 test_runner
19423 @end smallexample
19425 the old test is not replaced with a stub, nor is it lost, but a new test
19426 skeleton is created for function Dec.
19428 The only way of regenerating tests skeletons is to remove the previously created
19429 tests together with corresponding comment sections.
19431 @node Default Test Behavior
19432 @section Default Test Behavior
19434 @noindent
19436 The generated test driver can treat unimplemented tests in two ways:
19437 either count them all as failed (this is useful to see which tests are still
19438 left to implement) or as passed (to sort out unimplemented ones from those
19439 actually failing).
19441 The test driver accepts a switch to specify this behavior:
19442 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19443 @command{gnattest}).
19445 The default behavior of the test driver is set with the same switch
19446 as passed to gnattest when generating the test driver.
19448 Passing it to the driver generated on the first example:
19450 @smallexample
19451 test_runner --skeleton-default=pass
19452 @end smallexample
19454 makes both tests pass, even the unimplemented one.
19456 @node Testing Primitive Operations of Tagged Types
19457 @section Testing Primitive Operations of Tagged Types
19459 @noindent
19461 Creation of test skeletons for primitive operations of tagged types entails
19462 a number of features. Test routines for all primitives of a given tagged type
19463 are placed in a separate child package named according to the tagged type. For
19464 example, if you have tagged type T in package P, all tests for primitives
19465 of T will be in P.T_Test_Data.T_Tests.
19467 Consider running gnattest on the second example (note: actual tests for this
19468 example already exist, so there's no need to worry if the tool reports that
19469 no new stubs were generated):
19471 @smallexample
19472 cd <install_prefix>/share/examples/gnattest/tagged_rec
19473 gnattest --harness-dir=driver -Ptagged_rec.gpr
19474 @end smallexample
19476 Taking a closer look at the test type declared in the test package
19477 Speed1.Controller_Test_Data is necessary. It is declared in:
19479 @smallexample
19480 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19481 @end smallexample
19483 Test types are direct or indirect descendants of
19484 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19485 subprograms, the user doesn't need to be concerned with them. However,
19486 when generating test packages for primitive operations, there are some things
19487 the user needs to know.
19489 Type Test_Controller has components that allow assignment of various
19490 derivations of type Controller. And if you look at the specification of
19491 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19492 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19493 Thus, test types mirror the hierarchy of tested types.
19495 The Set_Up procedure of Test_Data package corresponding to a test package
19496 of primitive operations of type T assigns to Fixture a reference to an
19497 object of that exact type T. Notice, however, that if the tagged type has
19498 discriminants, the Set_Up only has a commented template for setting
19499 up the fixture, since filling the discriminant with actual value is up
19500 to the user.
19502 The knowledge of the structure of test types allows additional testing
19503 without additional effort. Those possibilities are described below.
19505 @node Testing Inheritance
19506 @section Testing Inheritance
19508 @noindent
19510 Since the test type hierarchy mimics the hierarchy of tested types, the
19511 inheritance of tests takes place. An example of such inheritance can be
19512 seen by running the test driver generated for the second example. As previously
19513 mentioned, actual tests are already written for this example.
19515 @smallexample
19516 cd obj/driver
19517 gnatmake -Ptest_driver
19518 test_runner
19519 @end smallexample
19521 There are 6 passed tests while there are only 5 testable subprograms. The test
19522 routine for function Speed has been inherited and run against objects of the
19523 derived type.
19525 @node Tagged Types Substitutability Testing
19526 @section Tagged Types Substitutability Testing
19528 @noindent
19530 Tagged Types Substitutability Testing is a way of verifying the global type
19531 consistency by testing. Global type consistency is a principle stating that if
19532 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19533 then objects of type T may be replaced with objects of type S (that is,
19534 objects of type S may be substituted for objects of type T), without
19535 altering any of the desirable properties of the program. When the properties
19536 of the program are expressed in the form of subprogram preconditions and
19537 postconditions (let's call them pre and post), the principle is formulated as
19538 relations between the pre and post of primitive operations and the pre and post
19539 of their derived operations. The pre of a derived operation should not be
19540 stronger than the original pre, and the post of the derived operation should
19541 not be weaker than the original post. Those relations ensure that verifying if
19542 a dispatching call is safe can be done just by using the pre and post of the
19543 root operation.
19545 Verifying global type consistency by testing consists of running all the unit
19546 tests associated with the primitives of a given tagged type with objects of its
19547 derived types.
19549 In the example used in the previous section, there was clearly a violation of
19550 type consistency. The overriding primitive Adjust_Speed in package Speed2
19551 removes the functionality of the overridden primitive and thus doesn't respect
19552 the consistency principle.
19553 Gnattest has a special option to run overridden parent tests against objects
19554 of the type which have overriding primitives:
19556 @smallexample
19557 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19558 cd obj/driver
19559 gnatmake -Ptest_driver
19560 test_runner
19561 @end smallexample
19563 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19564 against objects of the derived type.
19566 Non-overridden tests are already inherited for derived test types, so the
19567 --validate-type-extensions enables the application of overriden tests to objects
19568 of derived types.
19570 @node Testing with Contracts
19571 @section Testing with Contracts
19573 @noindent
19575 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19576 as well as corresponding aspects.
19577 Test routines are generated, one per each Test_Case associated with a tested
19578 subprogram. Those test routines have special wrappers for tested functions
19579 that have composition of pre- and postcondition of the subprogram with
19580 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19581 either count for Nominal mode or do not count for Robustness mode).
19583 The third example demonstrates how this works:
19585 @smallexample
19586 cd <install_prefix>/share/examples/gnattest/contracts
19587 gnattest --harness-dir=driver -Pcontracts.gpr
19588 @end smallexample
19590 Putting actual checks within the range of the contract does not cause any
19591 error reports. For example, for the test routine which corresponds to
19592 test case 1:
19594 @smallexample @c ada
19595 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19596 @end smallexample
19598 and for the test routine corresponding to test case 2:
19600 @smallexample @c ada
19601 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19602 @end smallexample
19604 are acceptable:
19606 @smallexample
19607 cd obj/driver
19608 gnatmake -Ptest_driver
19609 test_runner
19610 @end smallexample
19612 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19613 a precondition violation for test case one. Also, by using any otherwise
19614 correct but positive pair of numbers in the second test routine, you can also
19615 get a precondition violation. Postconditions are checked and reported
19616 the same way.
19618 @node Additional Tests
19619 @section Additional Tests
19621 @noindent
19622 @command{gnattest} can add user-written tests to the main suite of the test
19623 driver. @command{gnattest} traverses the given packages and searches for test
19624 routines. All procedures with a single in out parameter of a type which is
19625 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19626 specifications are added to the suites and are then executed by the test driver.
19627 (Set_Up and Tear_Down are filtered out.)
19629 An example illustrates two ways of creating test harnesses for user-written
19630 tests. Directory additional_tests contains an AUnit-based test driver written
19631 by hand.
19633 @smallexample
19634 <install_prefix>/share/examples/gnattest/additional_tests/
19635 @end smallexample
19637 To create a test driver for already-written tests, use the --harness-only
19638 option:
19640 @smallexample
19641 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19642   --harness-only
19643 gnatmake -Pharness_only/test_driver.gpr
19644 harness_only/test_runner
19645 @end smallexample
19647 Additional tests can also be executed together with generated tests:
19649 @smallexample
19650 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19651   --harness-dir=mixing
19652 gnatmake -Pmixing/test_driver.gpr
19653 mixing/test_runner
19654 @end smallexample
19657 @node Individual Test Drivers
19658 @section Individual Test Drivers
19660 @noindent
19661 By default, @command{gnattest} generates a monolithic test driver that
19662 aggregates the individual tests into a single executable. It is also possible
19663 to generate separate executables for each test, by passing the switch
19664 @option{--separate-drivers}. This approach scales better for large testing
19665 campaigns, especially involving target architectures with limited resources
19666 typical for embedded development. It can also provide a major performance
19667 benefit on multi-core systems by allowing simultaneous execution of multiple
19668 tests.
19670 @command{gnattest} can take charge of executing the individual tests; for this,
19671 instead of passing a project file, a text file containing the list of
19672 executables can be passed. Such a file is automatically generated by gnattest
19673 under the name @option{test_drivers.list}, but it can be
19674 hand-edited to add or remove tests, or replaced. The individual tests can
19675 also be executed standalone, or from any user-defined scripted framework.
19678 @node Stubbing
19679 @section Stubbing
19681 @noindent
19682 Depending on the testing campaign, it is sometimes necessary to isolate the
19683 part of the algorithm under test from its dependencies. This is accomplished
19684 via @emph{stubbing}, i.e. replacing the subprograms that are called from the
19685 subprogram under test by stand-in subprograms that match the profiles of the
19686 original ones, but simply return predetermined values required by the test
19687 scenario.
19689 This mode of test harness generation is activated by the switch @option{--stub}.
19691 The implementation approach chosen by @command{gnattest} is as follows.
19692 For each package under consideration all the packages it is directly depending
19693 on are stubbed, excluding the generic packages and package instantiations.
19694 The stubs are shared for each package under test. The specs of packages to stub
19695 remain intact, while their bodies are replaced, and hide the original bodies by
19696 means of extending projects. Also, for each stubbed
19697 package, a child package with setter routines for each subprogram declaration
19698 is created. These setters are meant to be used to set the behaviour of
19699 stubbed subprograms from within test cases.
19701 Note that subprograms belonging to the same package as the subprogram under
19702 test are not stubbed. This guarantees that the sources being tested are
19703 exactly the sources used for production, which is an important property for
19704 establishing the traceability between the testing campaign and production code.
19706 Due to the nature of stubbing process, this mode implies the switch
19707 @option{--separate-drivers}, i.e. an individual test driver (with the
19708 corresponding hierarchy of extending projects) is generated for each test.
19710 @quotation Note
19711 Developing a stubs-based testing campaign requires
19712 good understanding of the infrastructure created by @command{gnattest} for
19713 this purpose. We recommend following the stubbing tutorials provided
19714 under @file{<install_prefix>/share/examples/gnattest/stubbing*} before
19715 attempting to use this powerful feature.
19716 @end quotation
19718 @node Putting Tests under Version Control
19719 @section Putting Tests under Version Control
19721 @noindent
19722 As has been stated earlier, @command{gnattest} generates two different types
19723 of code, test skeletons and harness. The harness is generated completely
19724 automatically each time, does not require manual changes and therefore should
19725 not be put under version control.
19726 It makes sense to put under version control files containing test data packages,
19727 both specs and bodies, and files containing bodies of test packages. Note that
19728 test package specs are also generated automatically each time and should not be
19729 put under version control.
19730 Option @option{--omit-sloc} may be usefull when putting test packages under VCS.
19732 @node Support for other platforms/run-times
19733 @section Support for other platforms/run-times
19735 @noindent
19736 @command{gnattest} can be used to generate the test harness for platforms
19737 and run-time libraries others than the default native target with the
19738 default full run-time. For example, when using a limited run-time library
19739 such as Zero FootPrint (ZFP), a simplified harness is generated.
19741 Two variables are used to tell the underlying AUnit framework how to generate
19742 the test harness: @code{PLATFORM}, which identifies the target, and
19743 @code{RUNTIME}, used to determine the run-time library for which the harness
19744 is generated. Corresponding prefix should also be used when calling
19745 @command{gnattest} for non-native targets. For example, the following options
19746 are used to generate the AUnit test harness for a PowerPC ELF target using
19747 the ZFP run-time library:
19749 @smallexample
19750 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19751 @end smallexample
19753 @node Current Limitations
19754 @section Current Limitations
19756 @noindent
19758 The tool currently does not support following features:
19760 @itemize @bullet
19761 @item generic tests for nested generic packages and their instantiations
19762 @item tests for protected subprograms and entries
19764 @end itemize
19765 @end ifclear
19768 @c *********************************
19769 @node Performing Dimensionality Analysis in GNAT
19770 @chapter Performing Dimensionality Analysis in GNAT
19771 @cindex Dimensionality analysis
19773 @noindent
19774 The GNAT compiler now supports dimensionality checking. The user can
19775 specify physical units for objects, and the compiler will verify that uses
19776 of these objects are compatible with their dimensions, in a fashion that is
19777 familiar to engineering practice. The dimensions of algebraic expressions
19778 (including powers with static exponents) are computed from their constituents.
19780 This feature depends on Ada 2012 aspect specifications, and is available from
19781 version 7.0.1 of GNAT onwards.
19782 The GNAT-specific aspect @code{Dimension_System}
19783 @cindex @code{Dimension_System} aspect
19784 allows you to define a system of units; the aspect @code{Dimension}
19785 @cindex @code{Dimension} aspect
19786 then allows the user to declare dimensioned quantities within a given system.
19787 (These aspects are described in the @i{Implementation Defined Aspects}
19788 chapter of the @i{GNAT Reference Manual}).
19790 The major advantage of this model is that it does not require the declaration of
19791 multiple operators for all possible combinations of types: it is only necessary
19792 to use the proper subtypes in object declarations.
19794 The simplest way to impose dimensionality checking on a computation is to make
19795 use of the package @code{System.Dim.Mks},
19796 @cindex @code{System.Dim.Mks} package (GNAT library)
19797 which is part of the GNAT library. This
19798 package defines a floating-point type @code{MKS_Type},
19799 @cindex @code{MKS_Type} type
19800 for which a sequence of
19801 dimension names are specified, together with their conventional abbreviations.
19802 The following should be read together with the full specification of the
19803 package, in file @file{s-dimmks.ads}.
19804 @cindex @file{s-dimmks.ads} file
19806 @smallexample @c ada
19807 @group
19808    @b{type} Mks_Type @b{is} @b{new} Long_Long_Float
19809      @b{with}
19810       Dimension_System => (
19811         (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
19812         (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
19813         (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
19814         (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
19815         (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
19816         (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
19817         (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
19818 @end group
19819 @end smallexample
19821 @noindent
19822 The package then defines a series of subtypes that correspond to these
19823 conventional units. For example:
19825 @smallexample @c ada
19826 @group
19827    @b{subtype} Length @b{is} Mks_Type
19828      @b{with}
19829       Dimension => (Symbol => 'm', Meter  => 1, @b{others} => 0);
19830 @end group
19831 @end smallexample
19833 @noindent
19834 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
19835 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
19836 @code{Luminous_Intensity} (the standard set of units of the SI system).
19838 The package also defines conventional names for values of each unit, for
19839 example:
19841 @smallexample @c ada
19842 @group
19843    m   : @b{constant} Length           := 1.0;
19844    kg  : @b{constant} Mass             := 1.0;
19845    s   : @b{constant} Time             := 1.0;
19846    A   : @b{constant} Electric_Current := 1.0;
19847 @end group
19848 @end smallexample
19850 @noindent
19851 as well as useful multiples of these units:
19853 @smallexample @c ada
19854 @group
19855    cm  : @b{constant} Length := 1.0E-02;
19856    g   : @b{constant} Mass   := 1.0E-03;
19857    min : @b{constant} Time   := 60.0;
19858    day : @b{constant} Time   := 60.0 * 24.0 * min;
19859   ...
19860 @end group
19861 @end smallexample
19863 @noindent
19864 Using this package, you can then define a derived unit by
19865 providing the aspect that
19866 specifies its dimensions within the MKS system, as well as the string to
19867 be used for output of a value of that unit:
19869 @smallexample @c ada
19870 @group
19871   @b{subtype} Acceleration @b{is} Mks_Type
19872     @b{with} Dimension => ("m/sec^2",
19873                        Meter => 1,
19874                        Second => -2,
19875                        @b{others} => 0);
19876 @end group
19877 @end smallexample
19879 @noindent
19880 Here is a complete example of use:
19882 @smallexample @c ada
19883 @group
19884 @b{with} System.Dim.MKS; @b{use} System.Dim.Mks;
19885 @b{with} System.Dim.Mks_IO; @b{use} System.Dim.Mks_IO;
19886 @b{with} Text_IO; @b{use} Text_IO;
19887 @b{procedure} Free_Fall @b{is}
19888   @b{subtype} Acceleration @b{is} Mks_Type
19889     @b{with} Dimension => ("m/sec^2", 1, 0, -2, @b{others} => 0);
19890   G : @b{constant} acceleration := 9.81 * m / (s ** 2);
19891   T : Time := 10.0*s;
19892   Distance : Length;
19893 @end group
19894 @group
19895 @b{begin}
19896   Put ("Gravitational constant: ");
19897   Put (G, Aft => 2, Exp => 0); Put_Line ("");
19898   Distance := 0.5 * G * T ** 2;
19899   Put ("distance travelled in 10 seconds of free fall ");
19900   Put (Distance, Aft => 2, Exp => 0);
19901   Put_Line ("");
19902 @b{end} Free_Fall;
19903 @end group
19904 @end smallexample
19906 @noindent
19907 Execution of this program yields:
19908 @smallexample
19909 @group
19910 Gravitational constant:  9.81 m/sec^2
19911 distance travelled in 10 seconds of free fall 490.50 m
19912 @end group
19913 @end smallexample
19915 @noindent
19916 However, incorrect assignments such as:
19918 @smallexample @c ada
19919 @group
19920    Distance := 5.0;
19921    Distance := 5.0 * kg:
19922 @end group
19923 @end smallexample
19925 @noindent
19926 are rejected with the following diagnoses:
19928 @smallexample
19929 @group
19930    Distance := 5.0;
19931       >>> dimensions mismatch in assignment
19932       >>> left-hand side has dimension [L]
19933       >>> right-hand side is dimensionless
19934 @end group
19936 @group
19937    Distance := 5.0 * kg:
19938       >>> dimensions mismatch in assignment
19939       >>> left-hand side has dimension [L]
19940       >>> right-hand side has dimension [M]
19941 @end group
19942 @end smallexample
19944 @noindent
19945 The dimensions of an expression are properly displayed, even if there is
19946 no explicit subtype for it. If we add to the program:
19948 @smallexample @c ada
19949 @group
19950       Put ("Final velocity: ");
19951       Put (G * T, Aft =>2, Exp =>0);
19952       Put_Line ("");
19953 @end group
19954 @end smallexample
19956 @noindent
19957 then the output includes:
19958 @smallexample
19959      Final velocity: 98.10 m.s**(-1)
19960 @end smallexample
19963 @c *********************************
19964 @node Generating Ada Bindings for C and C++ headers
19965 @chapter Generating Ada Bindings for C and C++ headers
19966 @findex binding
19968 @noindent
19969 GNAT now comes with a binding generator for C and C++ headers which is
19970 intended to do 95% of the tedious work of generating Ada specs from C
19971 or C++ header files.
19973 Note that this capability is not intended to generate 100% correct Ada specs,
19974 and will is some cases require manual adjustments, although it can often
19975 be used out of the box in practice.
19977 Some of the known limitations include:
19979 @itemize @bullet
19980 @item only very simple character constant macros are translated into Ada
19981 constants. Function macros (macros with arguments) are partially translated
19982 as comments, to be completed manually if needed.
19983 @item some extensions (e.g. vector types) are not supported
19984 @item pointers to pointers or complex structures are mapped to System.Address
19985 @item identifiers with identical name (except casing) will generate compilation
19986       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19987 @end itemize
19989 The code generated is using the Ada 2005 syntax, which makes it
19990 easier to interface with other languages than previous versions of Ada.
19992 @menu
19993 * Running the binding generator::
19994 * Generating bindings for C++ headers::
19995 * Switches::
19996 @end menu
19998 @node Running the binding generator
19999 @section Running the binding generator
20001 @noindent
20002 The binding generator is part of the @command{gcc} compiler and can be
20003 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20004 spec files for the header files specified on the command line, and all
20005 header files needed by these files transitively. For example:
20007 @smallexample
20008 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
20009 $ gcc -c -gnat05 *.ads
20010 @end smallexample
20012 will generate, under GNU/Linux, the following files: @file{time_h.ads},
20013 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20014 correspond to the files @file{/usr/include/time.h},
20015 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20016 mode these Ada specs.
20018 The @code{-C} switch tells @command{gcc} to extract comments from headers,
20019 and will attempt to generate corresponding Ada comments.
20021 If you want to generate a single Ada file and not the transitive closure, you
20022 can use instead the @option{-fdump-ada-spec-slim} switch.
20024 You can optionally specify a parent unit, of which all generated units will
20025 be children, using @code{-fada-spec-parent=}@var{unit}.
20027 Note that we recommend when possible to use the @command{g++} driver to
20028 generate bindings, even for most C headers, since this will in general
20029 generate better Ada specs. For generating bindings for C++ headers, it is
20030 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20031 is equivalent in this case. If @command{g++} cannot work on your C headers
20032 because of incompatibilities between C and C++, then you can fallback to
20033 @command{gcc} instead.
20035 For an example of better bindings generated from the C++ front-end,
20036 the name of the parameters (when available) are actually ignored by the C
20037 front-end. Consider the following C header:
20039 @smallexample
20040 extern void foo (int variable);
20041 @end smallexample
20043 with the C front-end, @code{variable} is ignored, and the above is handled as:
20045 @smallexample
20046 extern void foo (int);
20047 @end smallexample
20049 generating a generic:
20051 @smallexample
20052 procedure foo (param1 : int);
20053 @end smallexample
20055 with the C++ front-end, the name is available, and we generate:
20057 @smallexample
20058 procedure foo (variable : int);
20059 @end smallexample
20061 In some cases, the generated bindings will be more complete or more meaningful
20062 when defining some macros, which you can do via the @option{-D} switch. This
20063 is for example the case with @file{Xlib.h} under GNU/Linux:
20065 @smallexample
20066 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20067 @end smallexample
20069 The above will generate more complete bindings than a straight call without
20070 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20072 In other cases, it is not possible to parse a header file in a stand-alone
20073 manner, because other include files need to be included first. In this
20074 case, the solution is to create a small header file including the needed
20075 @code{#include} and possible @code{#define} directives. For example, to
20076 generate Ada bindings for @file{readline/readline.h}, you need to first
20077 include @file{stdio.h}, so you can create a file with the following two
20078 lines in e.g. @file{readline1.h}:
20080 @smallexample
20081 #include <stdio.h>
20082 #include <readline/readline.h>
20083 @end smallexample
20085 and then generate Ada bindings from this file:
20087 @smallexample
20088 $ g++ -c -fdump-ada-spec readline1.h
20089 @end smallexample
20091 @node Generating bindings for C++ headers
20092 @section Generating bindings for C++ headers
20094 @noindent
20095 Generating bindings for C++ headers is done using the same options, always
20096 with the @command{g++} compiler.
20098 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20099 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20100 multiple inheritance of abstract classes will be mapped to Ada interfaces
20101 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20102 information on interfacing to C++).
20104 For example, given the following C++ header file:
20106 @smallexample
20107 @group
20108 @cartouche
20109 class Carnivore @{
20110 public:
20111    virtual int Number_Of_Teeth () = 0;
20114 class Domestic @{
20115 public:
20116    virtual void Set_Owner (char* Name) = 0;
20119 class Animal @{
20120 public:
20121   int Age_Count;
20122   virtual void Set_Age (int New_Age);
20125 class Dog : Animal, Carnivore, Domestic @{
20126  public:
20127   int  Tooth_Count;
20128   char *Owner;
20130   virtual int  Number_Of_Teeth ();
20131   virtual void Set_Owner (char* Name);
20133   Dog();
20135 @end cartouche
20136 @end group
20137 @end smallexample
20139 The corresponding Ada code is generated:
20141 @smallexample @c ada
20142 @group
20143 @cartouche
20144   @b{package} Class_Carnivore @b{is}
20145     @b{type} Carnivore @b{is} @b{limited} interface;
20146     @b{pragma} Import (CPP, Carnivore);
20148     @b{function} Number_Of_Teeth (this : @b{access} Carnivore) @b{return} int @b{is} @b{abstract};
20149   @b{end};
20150   @b{use} Class_Carnivore;
20152   @b{package} Class_Domestic @b{is}
20153     @b{type} Domestic @b{is} @b{limited} interface;
20154     @b{pragma} Import (CPP, Domestic);
20156     @b{procedure} Set_Owner
20157       (this : @b{access} Domestic;
20158        Name : Interfaces.C.Strings.chars_ptr) @b{is} @b{abstract};
20159   @b{end};
20160   @b{use} Class_Domestic;
20162   @b{package} Class_Animal @b{is}
20163     @b{type} Animal @b{is} @b{tagged} @b{limited} @b{record}
20164       Age_Count : @b{aliased} int;
20165     @b{end} @b{record};
20166     @b{pragma} Import (CPP, Animal);
20168     @b{procedure} Set_Age (this : @b{access} Animal; New_Age : int);
20169     @b{pragma} Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20170   @b{end};
20171   @b{use} Class_Animal;
20173   @b{package} Class_Dog @b{is}
20174     @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
20175       Tooth_Count : @b{aliased} int;
20176       Owner : Interfaces.C.Strings.chars_ptr;
20177     @b{end} @b{record};
20178     @b{pragma} Import (CPP, Dog);
20180     @b{function} Number_Of_Teeth (this : @b{access} Dog) @b{return} int;
20181     @b{pragma} Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20183     @b{procedure} Set_Owner
20184       (this : @b{access} Dog; Name : Interfaces.C.Strings.chars_ptr);
20185     @b{pragma} Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20187     @b{function} New_Dog @b{return} Dog;
20188     @b{pragma} CPP_Constructor (New_Dog);
20189     @b{pragma} Import (CPP, New_Dog, "_ZN3DogC1Ev");
20190   @b{end};
20191   @b{use} Class_Dog;
20192 @end cartouche
20193 @end group
20194 @end smallexample
20196 @node Switches
20197 @section Switches
20199 @table @option
20200 @item -fdump-ada-spec
20201 @cindex @option{-fdump-ada-spec} (@command{gcc})
20202 Generate Ada spec files for the given header files transitively (including
20203 all header files that these headers depend upon).
20205 @item -fdump-ada-spec-slim
20206 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20207 Generate Ada spec files for the header files specified on the command line
20208 only.
20210 @item -fada-spec-parent=@var{unit}
20211 @cindex -fada-spec-parent (@command{gcc})
20212 Specifies that all files generated by @option{-fdump-ada-spec*} are
20213 to be child units of the specified parent unit.
20215 @item -C
20216 @cindex @option{-C} (@command{gcc})
20217 Extract comments from headers and generate Ada comments in the Ada spec files.
20218 @end table
20220 @node Other Utility Programs
20221 @chapter Other Utility Programs
20223 @noindent
20224 This chapter discusses some other utility programs available in the Ada
20225 environment.
20227 @menu
20228 * Using Other Utility Programs with GNAT::
20229 * The External Symbol Naming Scheme of GNAT::
20230 * Converting Ada Files to html with gnathtml::
20231 * Installing gnathtml::
20232 @end menu
20234 @node Using Other Utility Programs with GNAT
20235 @section Using Other Utility Programs with GNAT
20237 @noindent
20238 The object files generated by GNAT are in standard system format and in
20239 particular the debugging information uses this format. This means
20240 programs generated by GNAT can be used with existing utilities that
20241 depend on these formats.
20243 In general, any utility program that works with C will also often work with
20244 Ada programs generated by GNAT. This includes software utilities such as
20245 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20246 as Purify.
20248 @node The External Symbol Naming Scheme of GNAT
20249 @section The External Symbol Naming Scheme of GNAT
20251 @noindent
20252 In order to interpret the output from GNAT, when using tools that are
20253 originally intended for use with other languages, it is useful to
20254 understand the conventions used to generate link names from the Ada
20255 entity names.
20257 All link names are in all lowercase letters. With the exception of library
20258 procedure names, the mechanism used is simply to use the full expanded
20259 Ada name with dots replaced by double underscores. For example, suppose
20260 we have the following package spec:
20262 @smallexample @c ada
20263 @group
20264 @cartouche
20265 @b{package} QRS @b{is}
20266    MN : Integer;
20267 @b{end} QRS;
20268 @end cartouche
20269 @end group
20270 @end smallexample
20272 @noindent
20273 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20274 the corresponding link name is @code{qrs__mn}.
20275 @findex Export
20276 Of course if a @code{pragma Export} is used this may be overridden:
20278 @smallexample @c ada
20279 @group
20280 @cartouche
20281 @b{package} Exports @b{is}
20282    Var1 : Integer;
20283    @b{pragma} Export (Var1, C, External_Name => "var1_name");
20284    Var2 : Integer;
20285    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
20286 @b{end} Exports;
20287 @end cartouche
20288 @end group
20289 @end smallexample
20291 @noindent
20292 In this case, the link name for @var{Var1} is whatever link name the
20293 C compiler would assign for the C function @var{var1_name}. This typically
20294 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20295 system conventions, but other possibilities exist. The link name for
20296 @var{Var2} is @var{var2_link_name}, and this is not operating system
20297 dependent.
20299 @findex _main
20300 One exception occurs for library level procedures. A potential ambiguity
20301 arises between the required name @code{_main} for the C main program,
20302 and the name we would otherwise assign to an Ada library level procedure
20303 called @code{Main} (which might well not be the main program).
20305 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20306 names. So if we have a library level procedure such as
20308 @smallexample @c ada
20309 @group
20310 @cartouche
20311 @b{procedure} Hello (S : String);
20312 @end cartouche
20313 @end group
20314 @end smallexample
20316 @noindent
20317 the external name of this procedure will be @var{_ada_hello}.
20320 @node Converting Ada Files to html with gnathtml
20321 @section Converting Ada Files to HTML with @code{gnathtml}
20323 @noindent
20324 This @code{Perl} script allows Ada source files to be browsed using
20325 standard Web browsers. For installation procedure, see the section
20326 @xref{Installing gnathtml}.
20328 Ada reserved keywords are highlighted in a bold font and Ada comments in
20329 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20330 switch to suppress the generation of cross-referencing information, user
20331 defined variables and types will appear in a different color; you will
20332 be able to click on any identifier and go to its declaration.
20334 The command line is as follow:
20335 @smallexample
20336 @c $ perl gnathtml.pl @ovar{switches} @var{ada-files}
20337 @c Expanding @ovar macro inline (explanation in macro def comments)
20338 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{ada-files}
20339 @end smallexample
20341 @noindent
20342 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20343 an html file for every ada file, and a global file called @file{index.htm}.
20344 This file is an index of every identifier defined in the files.
20346 The available switches are the following ones:
20348 @table @option
20349 @item -83
20350 @cindex @option{-83} (@code{gnathtml})
20351 Only the Ada 83 subset of keywords will be highlighted.
20353 @item -cc @var{color}
20354 @cindex @option{-cc} (@code{gnathtml})
20355 This option allows you to change the color used for comments. The default
20356 value is green. The color argument can be any name accepted by html.
20358 @item -d
20359 @cindex @option{-d} (@code{gnathtml})
20360 If the Ada files depend on some other files (for instance through
20361 @code{with} clauses, the latter files will also be converted to html.
20362 Only the files in the user project will be converted to html, not the files
20363 in the run-time library itself.
20365 @item -D
20366 @cindex @option{-D} (@code{gnathtml})
20367 This command is the same as @option{-d} above, but @command{gnathtml} will
20368 also look for files in the run-time library, and generate html files for them.
20370 @item -ext @var{extension}
20371 @cindex @option{-ext} (@code{gnathtml})
20372 This option allows you to change the extension of the generated HTML files.
20373 If you do not specify an extension, it will default to @file{htm}.
20375 @item -f
20376 @cindex @option{-f} (@code{gnathtml})
20377 By default, gnathtml will generate html links only for global entities
20378 ('with'ed units, global variables and types,@dots{}).  If you specify
20379 @option{-f} on the command line, then links will be generated for local
20380 entities too.
20382 @item -l @var{number}
20383 @cindex @option{-l} (@code{gnathtml})
20384 If this switch is provided and @var{number} is not 0, then
20385 @code{gnathtml} will number the html files every @var{number} line.
20387 @item -I @var{dir}
20388 @cindex @option{-I} (@code{gnathtml})
20389 Specify a directory to search for library files (@file{.ALI} files) and
20390 source files. You can provide several -I switches on the command line,
20391 and the directories will be parsed in the order of the command line.
20393 @item -o @var{dir}
20394 @cindex @option{-o} (@code{gnathtml})
20395 Specify the output directory for html files. By default, gnathtml will
20396 saved the generated html files in a subdirectory named @file{html/}.
20398 @item -p @var{file}
20399 @cindex @option{-p} (@code{gnathtml})
20400 If you are using Emacs and the most recent Emacs Ada mode, which provides
20401 a full Integrated Development Environment for compiling, checking,
20402 running and debugging applications, you may use @file{.gpr} files
20403 to give the directories where Emacs can find sources and object files.
20405 Using this switch, you can tell gnathtml to use these files.
20406 This allows you to get an html version of your application, even if it
20407 is spread over multiple directories.
20409 @item -sc @var{color}
20410 @cindex @option{-sc} (@code{gnathtml})
20411 This switch allows you to change the color used for symbol
20412 definitions.
20413 The default value is red. The color argument can be any name accepted by html.
20415 @item -t @var{file}
20416 @cindex @option{-t} (@code{gnathtml})
20417 This switch provides the name of a file. This file contains a list of
20418 file names to be converted, and the effect is exactly as though they had
20419 appeared explicitly on the command line. This
20420 is the recommended way to work around the command line length limit on some
20421 systems.
20423 @end table
20425 @node Installing gnathtml
20426 @section Installing @code{gnathtml}
20428 @noindent
20429 @code{Perl} needs to be installed on your machine to run this script.
20430 @code{Perl} is freely available for almost every architecture and
20431 Operating System via the Internet.
20433 On Unix systems, you  may want to modify  the  first line of  the script
20434 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
20435 is. The syntax of this line is:
20436 @smallexample
20437 #!full_path_name_to_perl
20438 @end smallexample
20440 @noindent
20441 Alternatively, you may run the script using the following command line:
20443 @smallexample
20444 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20445 @c Expanding @ovar macro inline (explanation in macro def comments)
20446 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20447 @end smallexample
20450 @c ******************************
20451 @node Code Coverage and Profiling
20452 @chapter Code Coverage and Profiling
20453 @cindex Code Coverage
20454 @cindex Profiling
20456 @noindent
20457 This chapter describes how to use @code{gcov} - coverage testing tool - and
20458 @code{gprof} - profiler tool - on your Ada programs.
20460 @menu
20461 * Code Coverage of Ada Programs with gcov::
20462 * Profiling an Ada Program with gprof::
20463 @end menu
20465 @node Code Coverage of Ada Programs with gcov
20466 @section Code Coverage of Ada Programs with gcov
20467 @cindex gcov
20468 @cindex -fprofile-arcs
20469 @cindex -ftest-coverage
20470 @cindex -coverage
20471 @cindex Code Coverage
20473 @noindent
20474 @code{gcov} is a test coverage program: it analyzes the execution of a given
20475 program on selected tests, to help you determine the portions of the program
20476 that are still untested.
20478 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20479 User's Guide. You can refer to this documentation for a more complete
20480 description.
20482 This chapter provides a quick startup guide, and
20483 details some Gnat-specific features.
20485 @menu
20486 * Quick startup guide::
20487 * Gnat specifics::
20488 @end menu
20490 @node Quick startup guide
20491 @subsection Quick startup guide
20493 In order to perform coverage analysis of a program using @code{gcov}, 3
20494 steps are needed:
20496 @itemize @bullet
20497 @item
20498 Code instrumentation during the compilation process
20499 @item
20500 Execution of the instrumented program
20501 @item
20502 Execution of the @code{gcov} tool to generate the result.
20503 @end itemize
20505 The code instrumentation needed by gcov is created at the object level:
20506 The source code is not modified in any way, because the instrumentation code is
20507 inserted by gcc during the compilation process. To compile your code with code
20508 coverage activated, you need to recompile your whole project using the
20509 switches
20510 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20511 @code{-fprofile-arcs}.
20513 @smallexample
20514 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20515    -largs -fprofile-arcs
20516 @end smallexample
20518 This compilation process will create @file{.gcno} files together with
20519 the usual object files.
20521 Once the program is compiled with coverage instrumentation, you can
20522 run it as many times as needed - on portions of a test suite for
20523 example. The first execution will produce @file{.gcda} files at the
20524 same location as the @file{.gcno} files.  The following executions
20525 will update those files, so that a cumulative result of the covered
20526 portions of the program is generated.
20528 Finally, you need to call the @code{gcov} tool. The different options of
20529 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20531 This will create annotated source files with a @file{.gcov} extension:
20532 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20534 @node Gnat specifics
20535 @subsection Gnat specifics
20537 Because Ada semantics, portions of the source code may be shared among
20538 several object files. This is the case for example when generics are
20539 involved, when inlining is active  or when declarations generate  initialisation
20540 calls. In order to take
20541 into account this shared code, you need to call @code{gcov} on all
20542 source files of the tested program at once.
20544 The list of source files might exceed the system's maximum command line
20545 length. In order to bypass this limitation, a new mechanism has been
20546 implemented in @code{gcov}: you can now list all your project's files into a
20547 text file, and provide this file to gcov as a parameter,  preceded by a @@
20548 (e.g. @samp{gcov @@mysrclist.txt}).
20550 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20551 not supported as there can be unresolved symbols during the final link.
20553 @node Profiling an Ada Program with gprof
20554 @section Profiling an Ada Program with gprof
20555 @cindex gprof
20556 @cindex -pg
20557 @cindex Profiling
20559 @noindent
20560 This section is not meant to be an exhaustive documentation of @code{gprof}.
20561 Full documentation for it can be found in the GNU Profiler User's Guide
20562 documentation that is part of this GNAT distribution.
20564 Profiling a program helps determine the parts of a program that are executed
20565 most often, and are therefore the most time-consuming.
20567 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20568 better handle Ada programs and multitasking.
20569 It is currently supported on the following platforms
20570 @itemize @bullet
20571 @item
20572 linux x86/x86_64
20573 @item
20574 solaris sparc/sparc64/x86
20575 @item
20576 windows x86
20577 @end itemize
20579 @noindent
20580 In order to profile a program using @code{gprof}, 3 steps are needed:
20582 @itemize @bullet
20583 @item
20584 Code instrumentation, requiring a full recompilation of the project with the
20585 proper switches.
20586 @item
20587 Execution of the program under the analysis conditions, i.e. with the desired
20588 input.
20589 @item
20590 Analysis of the results using the @code{gprof} tool.
20591 @end itemize
20593 @noindent
20594 The following sections detail the different steps, and indicate how
20595 to interpret the results:
20596 @menu
20597 * Compilation for profiling::
20598 * Program execution::
20599 * Running gprof::
20600 * Interpretation of profiling results::
20601 @end menu
20603 @node Compilation for profiling
20604 @subsection Compilation for profiling
20605 @cindex -pg
20606 @cindex Profiling
20608 In order to profile a program the first step is to tell the compiler
20609 to generate the necessary profiling information. The compiler switch to be used
20610 is @code{-pg}, which must be added to other compilation switches. This
20611 switch needs to be specified both during compilation and link stages, and can
20612 be specified once when using gnatmake:
20614 @smallexample
20615 gnatmake -f -pg -P my_project
20616 @end smallexample
20618 @noindent
20619 Note that only the objects that were compiled with the @samp{-pg} switch will
20620 be profiled; if you need to profile your whole project, use the @samp{-f}
20621 gnatmake switch to force full recompilation.
20623 @node Program execution
20624 @subsection Program execution
20626 @noindent
20627 Once the program has been compiled for profiling, you can run it as usual.
20629 The only constraint imposed by profiling is that the program must terminate
20630 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20631 properly analyzed.
20633 Once the program completes execution, a data file called @file{gmon.out} is
20634 generated in the directory where the program was launched from. If this file
20635 already exists, it will be overwritten.
20637 @node Running gprof
20638 @subsection Running gprof
20640 @noindent
20641 The @code{gprof} tool is called as follow:
20643 @smallexample
20644 gprof my_prog gmon.out
20645 @end smallexample
20647 @noindent
20648 or simpler:
20650 @smallexample
20651 gprof my_prog
20652 @end smallexample
20654 @noindent
20655 The complete form of the gprof command line is the following:
20657 @smallexample
20658 gprof [switches] [executable [data-file]]
20659 @end smallexample
20661 @noindent
20662 @code{gprof} supports numerous switch. The order of these
20663 switch does not matter. The full list of options can be found in
20664 the GNU Profiler User's Guide documentation that comes with this documentation.
20666 The following is the subset of those switches that is most relevant:
20668 @table @option
20670 @item --demangle[=@var{style}]
20671 @itemx --no-demangle
20672 @cindex @option{--demangle} (@code{gprof})
20673 These options control whether symbol names should be demangled when
20674 printing output.  The default is to demangle C++ symbols.  The
20675 @code{--no-demangle} option may be used to turn off demangling. Different
20676 compilers have different mangling styles.  The optional demangling style
20677 argument can be used to choose an appropriate demangling style for your
20678 compiler, in particular Ada symbols generated by GNAT can be demangled using
20679 @code{--demangle=gnat}.
20681 @item -e @var{function_name}
20682 @cindex @option{-e} (@code{gprof})
20683 The @samp{-e @var{function}} option tells @code{gprof} not to print
20684 information about the function @var{function_name} (and its
20685 children@dots{}) in the call graph.  The function will still be listed
20686 as a child of any functions that call it, but its index number will be
20687 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
20688 given; only one @var{function_name} may be indicated with each @samp{-e}
20689 option.
20691 @item -E @var{function_name}
20692 @cindex @option{-E} (@code{gprof})
20693 The @code{-E @var{function}} option works like the @code{-e} option, but
20694 execution time spent in the function (and children who were not called from
20695 anywhere else), will not be used to compute the percentages-of-time for
20696 the call graph.  More than one @samp{-E} option may be given; only one
20697 @var{function_name} may be indicated with each @samp{-E} option.
20699 @item -f @var{function_name}
20700 @cindex @option{-f} (@code{gprof})
20701 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20702 call graph to the function @var{function_name} and its children (and
20703 their children@dots{}).  More than one @samp{-f} option may be given;
20704 only one @var{function_name} may be indicated with each @samp{-f}
20705 option.
20707 @item -F @var{function_name}
20708 @cindex @option{-F} (@code{gprof})
20709 The @samp{-F @var{function}} option works like the @code{-f} option, but
20710 only time spent in the function and its children (and their
20711 children@dots{}) will be used to determine total-time and
20712 percentages-of-time for the call graph.  More than one @samp{-F} option
20713 may be given; only one @var{function_name} may be indicated with each
20714 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
20716 @end table
20718 @node Interpretation of profiling results
20719 @subsection Interpretation of profiling results
20721 @noindent
20723 The results of the profiling analysis are represented by two arrays: the
20724 'flat profile' and the 'call graph'. Full documentation of those outputs
20725 can be found in the GNU Profiler User's Guide.
20727 The flat profile shows the time spent in each function of the program, and how
20728 many time it has been called. This allows you to locate easily the most
20729 time-consuming functions.
20731 The call graph shows, for each subprogram, the subprograms that call it,
20732 and the subprograms that it calls. It also provides an estimate of the time
20733 spent in each of those callers/called subprograms.
20735 @c ******************************
20736 @node Running and Debugging Ada Programs
20737 @chapter Running and Debugging Ada Programs
20738 @cindex Debugging
20740 @noindent
20741 This chapter discusses how to debug Ada programs.
20743 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20745 @enumerate
20746 @item
20747 The illegality may be a violation of the static semantics of Ada. In
20748 that case GNAT diagnoses the constructs in the program that are illegal.
20749 It is then a straightforward matter for the user to modify those parts of
20750 the program.
20752 @item
20753 The illegality may be a violation of the dynamic semantics of Ada. In
20754 that case the program compiles and executes, but may generate incorrect
20755 results, or may terminate abnormally with some exception.
20757 @item
20758 When presented with a program that contains convoluted errors, GNAT
20759 itself may terminate abnormally without providing full diagnostics on
20760 the incorrect user program.
20761 @end enumerate
20763 @menu
20764 * The GNAT Debugger GDB::
20765 * Running GDB::
20766 * Introduction to GDB Commands::
20767 * Using Ada Expressions::
20768 * Calling User-Defined Subprograms::
20769 * Using the Next Command in a Function::
20770 * Ada Exceptions::
20771 * Ada Tasks::
20772 * Debugging Generic Units::
20773 * Remote Debugging with gdbserver::
20774 * GNAT Abnormal Termination or Failure to Terminate::
20775 * Naming Conventions for GNAT Source Files::
20776 * Getting Internal Debugging Information::
20777 * Stack Traceback::
20778 @end menu
20780 @cindex Debugger
20781 @findex gdb
20783 @node The GNAT Debugger GDB
20784 @section The GNAT Debugger GDB
20786 @noindent
20787 @code{GDB} is a general purpose, platform-independent debugger that
20788 can be used to debug mixed-language programs compiled with @command{gcc},
20789 and in particular is capable of debugging Ada programs compiled with
20790 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20791 complex Ada data structures.
20793 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20794 for full details on the usage of @code{GDB}, including a section on
20795 its usage on programs. This manual should be consulted for full
20796 details. The section that follows is a brief introduction to the
20797 philosophy and use of @code{GDB}.
20799 When GNAT programs are compiled, the compiler optionally writes debugging
20800 information into the generated object file, including information on
20801 line numbers, and on declared types and variables. This information is
20802 separate from the generated code. It makes the object files considerably
20803 larger, but it does not add to the size of the actual executable that
20804 will be loaded into memory, and has no impact on run-time performance. The
20805 generation of debug information is triggered by the use of the
20806 -g switch in the @command{gcc} or @command{gnatmake} command
20807 used to carry out the compilations. It is important to emphasize that
20808 the use of these options does not change the generated code.
20810 The debugging information is written in standard system formats that
20811 are used by many tools, including debuggers and profilers. The format
20812 of the information is typically designed to describe C types and
20813 semantics, but GNAT implements a translation scheme which allows full
20814 details about Ada types and variables to be encoded into these
20815 standard C formats. Details of this encoding scheme may be found in
20816 the file exp_dbug.ads in the GNAT source distribution. However, the
20817 details of this encoding are, in general, of no interest to a user,
20818 since @code{GDB} automatically performs the necessary decoding.
20820 When a program is bound and linked, the debugging information is
20821 collected from the object files, and stored in the executable image of
20822 the program. Again, this process significantly increases the size of
20823 the generated executable file, but it does not increase the size of
20824 the executable program itself. Furthermore, if this program is run in
20825 the normal manner, it runs exactly as if the debug information were
20826 not present, and takes no more actual memory.
20828 However, if the program is run under control of @code{GDB}, the
20829 debugger is activated.  The image of the program is loaded, at which
20830 point it is ready to run.  If a run command is given, then the program
20831 will run exactly as it would have if @code{GDB} were not present. This
20832 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
20833 entirely non-intrusive until a breakpoint is encountered.  If no
20834 breakpoint is ever hit, the program will run exactly as it would if no
20835 debugger were present. When a breakpoint is hit, @code{GDB} accesses
20836 the debugging information and can respond to user commands to inspect
20837 variables, and more generally to report on the state of execution.
20839 @c **************
20840 @node Running GDB
20841 @section Running GDB
20843 @noindent
20844 This section describes how to initiate the debugger.
20845 @c The above sentence is really just filler, but it was otherwise
20846 @c clumsy to get the first paragraph nonindented given the conditional
20847 @c nature of the description
20849 The debugger can be launched from a @code{GPS} menu or
20850 directly from the command line. The description below covers the latter use.
20851 All the commands shown can be used in the @code{GPS} debug console window,
20852 but there are usually more GUI-based ways to achieve the same effect.
20854 The command to run @code{GDB} is
20856 @smallexample
20857 $ gdb program
20858 @end smallexample
20860 @noindent
20861 where @code{program} is the name of the executable file. This
20862 activates the debugger and results in a prompt for debugger commands.
20863 The simplest command is simply @code{run}, which causes the program to run
20864 exactly as if the debugger were not present. The following section
20865 describes some of the additional commands that can be given to @code{GDB}.
20867 @c *******************************
20868 @node Introduction to GDB Commands
20869 @section Introduction to GDB Commands
20871 @noindent
20872 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
20873 Debugging with GDB, gdb, Debugging with GDB},
20874 for extensive documentation on the use
20875 of these commands, together with examples of their use. Furthermore,
20876 the command @command{help} invoked from within GDB activates a simple help
20877 facility which summarizes the available commands and their options.
20878 In this section we summarize a few of the most commonly
20879 used commands to give an idea of what @code{GDB} is about. You should create
20880 a simple program with debugging information and experiment with the use of
20881 these @code{GDB} commands on the program as you read through the
20882 following section.
20884 @table @code
20885 @item set args @var{arguments}
20886 The @var{arguments} list above is a list of arguments to be passed to
20887 the program on a subsequent run command, just as though the arguments
20888 had been entered on a normal invocation of the program. The @code{set args}
20889 command is not needed if the program does not require arguments.
20891 @item run
20892 The @code{run} command causes execution of the program to start from
20893 the beginning. If the program is already running, that is to say if
20894 you are currently positioned at a breakpoint, then a prompt will ask
20895 for confirmation that you want to abandon the current execution and
20896 restart.
20898 @item breakpoint @var{location}
20899 The breakpoint command sets a breakpoint, that is to say a point at which
20900 execution will halt and @code{GDB} will await further
20901 commands. @var{location} is
20902 either a line number within a file, given in the format @code{file:linenumber},
20903 or it is the name of a subprogram. If you request that a breakpoint be set on
20904 a subprogram that is overloaded, a prompt will ask you to specify on which of
20905 those subprograms you want to breakpoint. You can also
20906 specify that all of them should be breakpointed. If the program is run
20907 and execution encounters the breakpoint, then the program
20908 stops and @code{GDB} signals that the breakpoint was encountered by
20909 printing the line of code before which the program is halted.
20911 @item catch exception @var{name}
20912 This command causes the program execution to stop whenever exception
20913 @var{name} is raised.  If @var{name} is omitted, then the execution is
20914 suspended when any exception is raised.
20916 @item print @var{expression}
20917 This will print the value of the given expression. Most simple
20918 Ada expression formats are properly handled by @code{GDB}, so the expression
20919 can contain function calls, variables, operators, and attribute references.
20921 @item continue
20922 Continues execution following a breakpoint, until the next breakpoint or the
20923 termination of the program.
20925 @item step
20926 Executes a single line after a breakpoint. If the next statement
20927 is a subprogram call, execution continues into (the first statement of)
20928 the called subprogram.
20930 @item next
20931 Executes a single line. If this line is a subprogram call, executes and
20932 returns from the call.
20934 @item list
20935 Lists a few lines around the current source location. In practice, it
20936 is usually more convenient to have a separate edit window open with the
20937 relevant source file displayed. Successive applications of this command
20938 print subsequent lines. The command can be given an argument which is a
20939 line number, in which case it displays a few lines around the specified one.
20941 @item backtrace
20942 Displays a backtrace of the call chain. This command is typically
20943 used after a breakpoint has occurred, to examine the sequence of calls that
20944 leads to the current breakpoint. The display includes one line for each
20945 activation record (frame) corresponding to an active subprogram.
20947 @item up
20948 At a breakpoint, @code{GDB} can display the values of variables local
20949 to the current frame. The command @code{up} can be used to
20950 examine the contents of other active frames, by moving the focus up
20951 the stack, that is to say from callee to caller, one frame at a time.
20953 @item down
20954 Moves the focus of @code{GDB} down from the frame currently being
20955 examined to the frame of its callee (the reverse of the previous command),
20957 @item frame @var{n}
20958 Inspect the frame with the given number. The value 0 denotes the frame
20959 of the current breakpoint, that is to say the top of the call stack.
20961 @item kill
20962 Kills the child process in which the program is running under GDB.
20963 This may be useful for several purposes:
20964 @itemize @bullet
20965 @item
20966 It allows you to recompile and relink your program, since on many systems
20967 you cannot regenerate an executable file while it is running in a process.
20968 @item
20969 You can run your program outside the debugger, on systems that do not
20970 permit executing a program outside GDB while breakpoints are set
20971 within GDB.
20972 @item
20973 It allows you to debug a core dump rather than a running process.
20974 @end itemize
20975 @end table
20977 @noindent
20978 The above list is a very short introduction to the commands that
20979 @code{GDB} provides. Important additional capabilities, including conditional
20980 breakpoints, the ability to execute command sequences on a breakpoint,
20981 the ability to debug at the machine instruction level and many other
20982 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20983 Debugging with GDB}.  Note that most commands can be abbreviated
20984 (for example, c for continue, bt for backtrace).
20986 @node Using Ada Expressions
20987 @section Using Ada Expressions
20988 @cindex Ada expressions
20990 @noindent
20991 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20992 extensions. The philosophy behind the design of this subset is
20994 @itemize @bullet
20995 @item
20996 That @code{GDB} should provide basic literals and access to operations for
20997 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20998 leaving more sophisticated computations to subprograms written into the
20999 program (which therefore may be called from @code{GDB}).
21001 @item
21002 That type safety and strict adherence to Ada language restrictions
21003 are not particularly important to the @code{GDB} user.
21005 @item
21006 That brevity is important to the @code{GDB} user.
21007 @end itemize
21009 @noindent
21010 Thus, for brevity, the debugger acts as if there were
21011 implicit @code{with} and @code{use} clauses in effect for all user-written
21012 packages, thus making it unnecessary to fully qualify most names with
21013 their packages, regardless of context. Where this causes ambiguity,
21014 @code{GDB} asks the user's intent.
21016 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21017 GDB, gdb, Debugging with GDB}.
21019 @node Calling User-Defined Subprograms
21020 @section Calling User-Defined Subprograms
21022 @noindent
21023 An important capability of @code{GDB} is the ability to call user-defined
21024 subprograms while debugging. This is achieved simply by entering
21025 a subprogram call statement in the form:
21027 @smallexample
21028 call subprogram-name (parameters)
21029 @end smallexample
21031 @noindent
21032 The keyword @code{call} can be omitted in the normal case where the
21033 @code{subprogram-name} does not coincide with any of the predefined
21034 @code{GDB} commands.
21036 The effect is to invoke the given subprogram, passing it the
21037 list of parameters that is supplied. The parameters can be expressions and
21038 can include variables from the program being debugged. The
21039 subprogram must be defined
21040 at the library level within your program, and @code{GDB} will call the
21041 subprogram within the environment of your program execution (which
21042 means that the subprogram is free to access or even modify variables
21043 within your program).
21045 The most important use of this facility is in allowing the inclusion of
21046 debugging routines that are tailored to particular data structures
21047 in your program. Such debugging routines can be written to provide a suitably
21048 high-level description of an abstract type, rather than a low-level dump
21049 of its physical layout. After all, the standard
21050 @code{GDB print} command only knows the physical layout of your
21051 types, not their abstract meaning. Debugging routines can provide information
21052 at the desired semantic level and are thus enormously useful.
21054 For example, when debugging GNAT itself, it is crucial to have access to
21055 the contents of the tree nodes used to represent the program internally.
21056 But tree nodes are represented simply by an integer value (which in turn
21057 is an index into a table of nodes).
21058 Using the @code{print} command on a tree node would simply print this integer
21059 value, which is not very useful. But the PN routine (defined in file
21060 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21061 a useful high level representation of the tree node, which includes the
21062 syntactic category of the node, its position in the source, the integers
21063 that denote descendant nodes and parent node, as well as varied
21064 semantic information. To study this example in more detail, you might want to
21065 look at the body of the PN procedure in the stated file.
21067 Another useful application of this capability is to deal with situations of
21068 complex data which are not handled suitably by GDB. For example, if you specify
21069 Convention Fortran for a multi-dimensional array, GDB does not know that
21070 the ordering of array elements has been switched and will not properly
21071 address the array elements. In such a case, instead of trying to print the
21072 elements directly from GDB, you can write a callable procedure that prints
21073 the elements in the desired format.
21075 @node Using the Next Command in a Function
21076 @section Using the Next Command in a Function
21078 @noindent
21079 When you use the @code{next} command in a function, the current source
21080 location will advance to the next statement as usual. A special case
21081 arises in the case of a @code{return} statement.
21083 Part of the code for a return statement is the ``epilogue'' of the function.
21084 This is the code that returns to the caller. There is only one copy of
21085 this epilogue code, and it is typically associated with the last return
21086 statement in the function if there is more than one return. In some
21087 implementations, this epilogue is associated with the first statement
21088 of the function.
21090 The result is that if you use the @code{next} command from a return
21091 statement that is not the last return statement of the function you
21092 may see a strange apparent jump to the last return statement or to
21093 the start of the function. You should simply ignore this odd jump.
21094 The value returned is always that from the first return statement
21095 that was stepped through.
21097 @node Ada Exceptions
21098 @section Stopping when Ada Exceptions are Raised
21099 @cindex Exceptions
21101 @noindent
21102 You can set catchpoints that stop the program execution when your program
21103 raises selected exceptions.
21105 @table @code
21106 @item catch exception
21107 Set a catchpoint that stops execution whenever (any task in the) program
21108 raises any exception.
21110 @item catch exception @var{name}
21111 Set a catchpoint that stops execution whenever (any task in the) program
21112 raises the exception @var{name}.
21114 @item catch exception unhandled
21115 Set a catchpoint that stops executing whenever (any task in the) program
21116 raises an exception for which there is no handler.
21118 @item info exceptions
21119 @itemx info exceptions @var{regexp}
21120 The @code{info exceptions} command permits the user to examine all defined
21121 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21122 argument, prints out only those exceptions whose name matches @var{regexp}.
21123 @end table
21125 @node Ada Tasks
21126 @section Ada Tasks
21127 @cindex Tasks
21129 @noindent
21130 @code{GDB} allows the following task-related commands:
21132 @table @code
21133 @item info tasks
21134 This command shows a list of current Ada tasks, as in the following example:
21136 @smallexample
21137 @iftex
21138 @leftskip=0cm
21139 @end iftex
21140 (gdb) info tasks
21141   ID       TID P-ID   Thread Pri State                 Name
21142    1   8088000   0   807e000  15 Child Activation Wait main_task
21143    2   80a4000   1   80ae000  15 Accept/Select Wait    b
21144    3   809a800   1   80a4800  15 Child Activation Wait a
21145 *  4   80ae800   3   80b8000  15 Running               c
21146 @end smallexample
21148 @noindent
21149 In this listing, the asterisk before the first task indicates it to be the
21150 currently running task. The first column lists the task ID that is used
21151 to refer to tasks in the following commands.
21153 @item break @var{linespec} task @var{taskid}
21154 @itemx break @var{linespec} task @var{taskid} if @dots{}
21155 @cindex Breakpoints and tasks
21156 These commands are like the @code{break @dots{} thread @dots{}}.
21157 @var{linespec} specifies source lines.
21159 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21160 to specify that you only want @code{GDB} to stop the program when a
21161 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21162 numeric task identifiers assigned by @code{GDB}, shown in the first
21163 column of the @samp{info tasks} display.
21165 If you do not specify @samp{task @var{taskid}} when you set a
21166 breakpoint, the breakpoint applies to @emph{all} tasks of your
21167 program.
21169 You can use the @code{task} qualifier on conditional breakpoints as
21170 well; in this case, place @samp{task @var{taskid}} before the
21171 breakpoint condition (before the @code{if}).
21173 @item task @var{taskno}
21174 @cindex Task switching
21176 This command allows switching to the task referred by @var{taskno}. In
21177 particular, this allows browsing of the backtrace of the specified
21178 task. It is advisable to switch back to the original task before
21179 continuing execution otherwise the scheduling of the program may be
21180 perturbed.
21181 @end table
21183 @noindent
21184 For more detailed information on the tasking support,
21185 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21187 @node Debugging Generic Units
21188 @section Debugging Generic Units
21189 @cindex Debugging Generic Units
21190 @cindex Generics
21192 @noindent
21193 GNAT always uses code expansion for generic instantiation. This means that
21194 each time an instantiation occurs, a complete copy of the original code is
21195 made, with appropriate substitutions of formals by actuals.
21197 It is not possible to refer to the original generic entities in
21198 @code{GDB}, but it is always possible to debug a particular instance of
21199 a generic, by using the appropriate expanded names. For example, if we have
21201 @smallexample @c ada
21202 @group
21203 @cartouche
21204 @b{procedure} g @b{is}
21206    @b{generic} @b{package} k @b{is}
21207       @b{procedure} kp (v1 : @b{in} @b{out} integer);
21208    @b{end} k;
21210    @b{package} @b{body} k @b{is}
21211       @b{procedure} kp (v1 : @b{in} @b{out} integer) @b{is}
21212       @b{begin}
21213          v1 := v1 + 1;
21214       @b{end} kp;
21215    @b{end} k;
21217    @b{package} k1 @b{is} @b{new} k;
21218    @b{package} k2 @b{is} @b{new} k;
21220    var : integer := 1;
21222 @b{begin}
21223    k1.kp (var);
21224    k2.kp (var);
21225    k1.kp (var);
21226    k2.kp (var);
21227 @b{end};
21228 @end cartouche
21229 @end group
21230 @end smallexample
21232 @noindent
21233 Then to break on a call to procedure kp in the k2 instance, simply
21234 use the command:
21236 @smallexample
21237 (gdb) break g.k2.kp
21238 @end smallexample
21240 @noindent
21241 When the breakpoint occurs, you can step through the code of the
21242 instance in the normal manner and examine the values of local variables, as for
21243 other units.
21245 @node Remote Debugging with gdbserver
21246 @section Remote Debugging with gdbserver
21247 @cindex Remote Debugging with gdbserver
21249 @noindent
21250 On platforms where gdbserver is supported, it is possible to use this tool
21251 to debug your application remotely.  This can be useful in situations
21252 where the program needs to be run on a target host that is different
21253 from the host used for development, particularly when the target has
21254 a limited amount of resources (either CPU and/or memory).
21256 To do so, start your program using gdbserver on the target machine.
21257 gdbserver then automatically suspends the execution of your program
21258 at its entry point, waiting for a debugger to connect to it.  The
21259 following commands starts an application and tells gdbserver to
21260 wait for a connection with the debugger on localhost port 4444.
21262 @smallexample
21263 $ gdbserver localhost:4444 program
21264 Process program created; pid = 5685
21265 Listening on port 4444
21266 @end smallexample
21268 Once gdbserver has started listening, we can tell the debugger to establish
21269 a connection with this gdbserver, and then start the same debugging session
21270 as if the program was being debugged on the same host, directly under
21271 the control of GDB.
21273 @smallexample
21274 $ gdb program
21275 (gdb) target remote targethost:4444
21276 Remote debugging using targethost:4444
21277 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21278 (gdb) b foo.adb:3
21279 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21280 (gdb) continue
21281 Continuing.
21283 Breakpoint 1, foo () at foo.adb:4
21284 4       end foo;
21285 @end smallexample
21287 It is also possible to use gdbserver to attach to an already running
21288 program, in which case the execution of that program is simply suspended
21289 until the connection between the debugger and gdbserver is established.
21291 For more information on how to use gdbserver, @ref{Top, Server, Using
21292 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
21293 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21295 @node GNAT Abnormal Termination or Failure to Terminate
21296 @section GNAT Abnormal Termination or Failure to Terminate
21297 @cindex GNAT Abnormal Termination or Failure to Terminate
21299 @noindent
21300 When presented with programs that contain serious errors in syntax
21301 or semantics,
21302 GNAT may on rare occasions  experience problems in operation, such
21303 as aborting with a
21304 segmentation fault or illegal memory access, raising an internal
21305 exception, terminating abnormally, or failing to terminate at all.
21306 In such cases, you can activate
21307 various features of GNAT that can help you pinpoint the construct in your
21308 program that is the likely source of the problem.
21310 The following strategies are presented in increasing order of
21311 difficulty, corresponding to your experience in using GNAT and your
21312 familiarity with compiler internals.
21314 @enumerate
21315 @item
21316 Run @command{gcc} with the @option{-gnatf}. This first
21317 switch causes all errors on a given line to be reported. In its absence,
21318 only the first error on a line is displayed.
21320 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21321 are encountered, rather than after compilation is terminated. If GNAT
21322 terminates prematurely or goes into an infinite loop, the last error
21323 message displayed may help to pinpoint the culprit.
21325 @item
21326 Run @command{gcc} with the @option{-v (verbose)} switch. In this
21327 mode, @command{gcc} produces ongoing information about the progress of the
21328 compilation and provides the name of each procedure as code is
21329 generated. This switch allows you to find which Ada procedure was being
21330 compiled when it encountered a code generation problem.
21332 @item
21333 @cindex @option{-gnatdc} switch
21334 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21335 switch that does for the front-end what @option{-v} does
21336 for the back end. The system prints the name of each unit,
21337 either a compilation unit or nested unit, as it is being analyzed.
21338 @item
21339 Finally, you can start
21340 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21341 front-end of GNAT, and can be run independently (normally it is just
21342 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21343 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21344 @code{where} command is the first line of attack; the variable
21345 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21346 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21347 which the execution stopped, and @code{input_file name} indicates the name of
21348 the source file.
21349 @end enumerate
21351 @node Naming Conventions for GNAT Source Files
21352 @section Naming Conventions for GNAT Source Files
21354 @noindent
21355 In order to examine the workings of the GNAT system, the following
21356 brief description of its organization may be helpful:
21358 @itemize @bullet
21359 @item
21360 Files with prefix @file{sc} contain the lexical scanner.
21362 @item
21363 All files prefixed with @file{par} are components of the parser. The
21364 numbers correspond to chapters of the Ada Reference Manual. For example,
21365 parsing of select statements can be found in @file{par-ch9.adb}.
21367 @item
21368 All files prefixed with @file{sem} perform semantic analysis. The
21369 numbers correspond to chapters of the Ada standard. For example, all
21370 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21371 addition, some features of the language require sufficient special processing
21372 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21373 dynamic dispatching, etc.
21375 @item
21376 All files prefixed with @file{exp} perform normalization and
21377 expansion of the intermediate representation (abstract syntax tree, or AST).
21378 these files use the same numbering scheme as the parser and semantics files.
21379 For example, the construction of record initialization procedures is done in
21380 @file{exp_ch3.adb}.
21382 @item
21383 The files prefixed with @file{bind} implement the binder, which
21384 verifies the consistency of the compilation, determines an order of
21385 elaboration, and generates the bind file.
21387 @item
21388 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21389 data structures used by the front-end.
21391 @item
21392 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21393 the abstract syntax tree as produced by the parser.
21395 @item
21396 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21397 all entities, computed during semantic analysis.
21399 @item
21400 Library management issues are dealt with in files with prefix
21401 @file{lib}.
21403 @item
21404 @findex Ada
21405 @cindex Annex A
21406 Ada files with the prefix @file{a-} are children of @code{Ada}, as
21407 defined in Annex A.
21409 @item
21410 @findex Interfaces
21411 @cindex Annex B
21412 Files with prefix @file{i-} are children of @code{Interfaces}, as
21413 defined in Annex B.
21415 @item
21416 @findex System
21417 Files with prefix @file{s-} are children of @code{System}. This includes
21418 both language-defined children and GNAT run-time routines.
21420 @item
21421 @findex GNAT
21422 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
21423 general-purpose packages, fully documented in their specs. All
21424 the other @file{.c} files are modifications of common @command{gcc} files.
21425 @end itemize
21427 @node Getting Internal Debugging Information
21428 @section Getting Internal Debugging Information
21430 @noindent
21431 Most compilers have internal debugging switches and modes. GNAT
21432 does also, except GNAT internal debugging switches and modes are not
21433 secret. A summary and full description of all the compiler and binder
21434 debug flags are in the file @file{debug.adb}. You must obtain the
21435 sources of the compiler to see the full detailed effects of these flags.
21437 The switches that print the source of the program (reconstructed from
21438 the internal tree) are of general interest for user programs, as are the
21439 options to print
21440 the full internal tree, and the entity table (the symbol table
21441 information). The reconstructed source provides a readable version of the
21442 program after the front-end has completed analysis and  expansion,
21443 and is useful when studying the performance of specific constructs.
21444 For example, constraint checks are indicated, complex aggregates
21445 are replaced with loops and assignments, and tasking primitives
21446 are replaced with run-time calls.
21448 @node Stack Traceback
21449 @section Stack Traceback
21450 @cindex traceback
21451 @cindex stack traceback
21452 @cindex stack unwinding
21454 @noindent
21455 Traceback is a mechanism to display the sequence of subprogram calls that
21456 leads to a specified execution point in a program. Often (but not always)
21457 the execution point is an instruction at which an exception has been raised.
21458 This mechanism is also known as @i{stack unwinding} because it obtains
21459 its information by scanning the run-time stack and recovering the activation
21460 records of all active subprograms. Stack unwinding is one of the most
21461 important tools for program debugging.
21463 The first entry stored in traceback corresponds to the deepest calling level,
21464 that is to say the subprogram currently executing the instruction
21465 from which we want to obtain the traceback.
21467 Note that there is no runtime performance penalty when stack traceback
21468 is enabled, and no exception is raised during program execution.
21470 @menu
21471 * Non-Symbolic Traceback::
21472 * Symbolic Traceback::
21473 @end menu
21475 @node Non-Symbolic Traceback
21476 @subsection Non-Symbolic Traceback
21477 @cindex traceback, non-symbolic
21479 @noindent
21480 Note: this feature is not supported on all platforms. See
21481 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21482 platforms.
21484 @menu
21485 * Tracebacks From an Unhandled Exception::
21486 * Tracebacks From Exception Occurrences (non-symbolic)::
21487 * Tracebacks From Anywhere in a Program (non-symbolic)::
21488 @end menu
21490 @node Tracebacks From an Unhandled Exception
21491 @subsubsection Tracebacks From an Unhandled Exception
21493 @noindent
21494 A runtime non-symbolic traceback is a list of addresses of call instructions.
21495 To enable this feature you must use the @option{-E}
21496 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21497 of exception information. You can retrieve this information using the
21498 @code{addr2line} tool.
21500 Here is a simple example:
21502 @smallexample @c ada
21503 @cartouche
21504 @b{procedure} STB @b{is}
21506    @b{procedure} P1 @b{is}
21507    @b{begin}
21508       @b{raise} Constraint_Error;
21509    @b{end} P1;
21511    @b{procedure} P2 @b{is}
21512    @b{begin}
21513       P1;
21514    @b{end} P2;
21516 @b{begin}
21517    P2;
21518 @b{end} STB;
21519 @end cartouche
21520 @end smallexample
21522 @smallexample
21523 $ gnatmake stb -bargs -E
21524 $ stb
21526 Execution terminated by unhandled exception
21527 Exception name: CONSTRAINT_ERROR
21528 Message: stb.adb:5
21529 Call stack traceback locations:
21530 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21531 @end smallexample
21533 @noindent
21534 As we see the traceback lists a sequence of addresses for the unhandled
21535 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21536 guess that this exception come from procedure P1. To translate these
21537 addresses into the source lines where the calls appear, the
21538 @code{addr2line} tool, described below, is invaluable. The use of this tool
21539 requires the program to be compiled with debug information.
21541 @smallexample
21542 $ gnatmake -g stb -bargs -E
21543 $ stb
21545 Execution terminated by unhandled exception
21546 Exception name: CONSTRAINT_ERROR
21547 Message: stb.adb:5
21548 Call stack traceback locations:
21549 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21551 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21552    0x4011f1 0x77e892a4
21554 00401373 at d:/stb/stb.adb:5
21555 0040138B at d:/stb/stb.adb:10
21556 0040139C at d:/stb/stb.adb:14
21557 00401335 at d:/stb/b~stb.adb:104
21558 004011C4 at /build/@dots{}/crt1.c:200
21559 004011F1 at /build/@dots{}/crt1.c:222
21560 77E892A4 in ?? at ??:0
21561 @end smallexample
21563 @noindent
21564 The @code{addr2line} tool has several other useful options:
21566 @table @code
21567 @item --functions
21568 to get the function name corresponding to any location
21570 @item --demangle=gnat
21571 to use the gnat decoding mode for the function names. Note that
21572 for binutils version 2.9.x the option is simply @option{--demangle}.
21573 @end table
21575 @smallexample
21576 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21577    0x40139c 0x401335 0x4011c4 0x4011f1
21579 00401373 in stb.p1 at d:/stb/stb.adb:5
21580 0040138B in stb.p2 at d:/stb/stb.adb:10
21581 0040139C in stb at d:/stb/stb.adb:14
21582 00401335 in main at d:/stb/b~stb.adb:104
21583 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21584 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21585 @end smallexample
21587 @noindent
21588 From this traceback we can see that the exception was raised in
21589 @file{stb.adb} at line 5, which was reached from a procedure call in
21590 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21591 which contains the call to the main program.
21592 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21593 and the output will vary from platform to platform.
21595 It is also possible to use @code{GDB} with these traceback addresses to debug
21596 the program. For example, we can break at a given code location, as reported
21597 in the stack traceback:
21599 @smallexample
21600 $ gdb -nw stb
21601 @noindent
21602 Furthermore, this feature is not implemented inside Windows DLL. Only
21603 the non-symbolic traceback is reported in this case.
21605 (gdb) break *0x401373
21606 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21607 @end smallexample
21609 @noindent
21610 It is important to note that the stack traceback addresses
21611 do not change when debug information is included. This is particularly useful
21612 because it makes it possible to release software without debug information (to
21613 minimize object size), get a field report that includes a stack traceback
21614 whenever an internal bug occurs, and then be able to retrieve the sequence
21615 of calls with the same program compiled with debug information.
21617 @node Tracebacks From Exception Occurrences (non-symbolic)
21618 @subsubsection Tracebacks From Exception Occurrences
21620 @noindent
21621 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21622 The stack traceback is attached to the exception information string, and can
21623 be retrieved in an exception handler within the Ada program, by means of the
21624 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21626 @smallexample @c ada
21627 @b{with} Ada.Text_IO;
21628 @b{with} Ada.Exceptions;
21630 @b{procedure} STB @b{is}
21632    @b{use} Ada;
21633    @b{use} Ada.Exceptions;
21635    @b{procedure} P1 @b{is}
21636       K : Positive := 1;
21637    @b{begin}
21638       K := K - 1;
21639    @b{exception}
21640       @b{when} E : @b{others} =>
21641          Text_IO.Put_Line (Exception_Information (E));
21642    @b{end} P1;
21644    @b{procedure} P2 @b{is}
21645    @b{begin}
21646       P1;
21647    @b{end} P2;
21649 @b{begin}
21650    P2;
21651 @b{end} STB;
21652 @end smallexample
21654 @noindent
21655 This program will output:
21657 @smallexample
21658 $ stb
21660 Exception name: CONSTRAINT_ERROR
21661 Message: stb.adb:12
21662 Call stack traceback locations:
21663 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21664 @end smallexample
21666 @node Tracebacks From Anywhere in a Program (non-symbolic)
21667 @subsubsection Tracebacks From Anywhere in a Program
21669 @noindent
21670 It is also possible to retrieve a stack traceback from anywhere in a
21671 program. For this you need to
21672 use the @code{GNAT.Traceback} API. This package includes a procedure called
21673 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21674 display procedures described below. It is not necessary to use the
21675 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21676 is invoked explicitly.
21678 @noindent
21679 In the following example we compute a traceback at a specific location in
21680 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21681 convert addresses to strings:
21683 @smallexample @c ada
21684 @b{with} Ada.Text_IO;
21685 @b{with} GNAT.Traceback;
21686 @b{with} GNAT.Debug_Utilities;
21688 @b{procedure} STB @b{is}
21690    @b{use} Ada;
21691    @b{use} GNAT;
21692    @b{use} GNAT.Traceback;
21694    @b{procedure} P1 @b{is}
21695       TB  : Tracebacks_Array (1 .. 10);
21696       --@i{  We are asking for a maximum of 10 stack frames.}
21697       Len : Natural;
21698       --@i{  Len will receive the actual number of stack frames returned.}
21699    @b{begin}
21700       Call_Chain (TB, Len);
21702       Text_IO.Put ("In STB.P1 : ");
21704       @b{for} K @b{in} 1 .. Len @b{loop}
21705          Text_IO.Put (Debug_Utilities.Image (TB (K)));
21706          Text_IO.Put (' ');
21707       @b{end} @b{loop};
21709       Text_IO.New_Line;
21710    @b{end} P1;
21712    @b{procedure} P2 @b{is}
21713    @b{begin}
21714       P1;
21715    @b{end} P2;
21717 @b{begin}
21718    P2;
21719 @b{end} STB;
21720 @end smallexample
21722 @smallexample
21723 $ gnatmake -g stb
21724 $ stb
21726 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21727 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21728 @end smallexample
21730 @noindent
21731 You can then get further information by invoking the @code{addr2line}
21732 tool as described earlier (note that the hexadecimal addresses
21733 need to be specified in C format, with a leading ``0x'').
21735 @node Symbolic Traceback
21736 @subsection Symbolic Traceback
21737 @cindex traceback, symbolic
21739 @noindent
21740 A symbolic traceback is a stack traceback in which procedure names are
21741 associated with each code location.
21743 @noindent
21744 Note that this feature is not supported on all platforms. See
21745 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21746 list of currently supported platforms.
21748 @noindent
21749 Note that the symbolic traceback requires that the program be compiled
21750 with debug information. If it is not compiled with debug information
21751 only the non-symbolic information will be valid.
21753 @menu
21754 * Tracebacks From Exception Occurrences (symbolic)::
21755 * Tracebacks From Anywhere in a Program (symbolic)::
21756 @end menu
21758 @node Tracebacks From Exception Occurrences (symbolic)
21759 @subsubsection Tracebacks From Exception Occurrences
21761 @smallexample @c ada
21762 @b{with} Ada.Text_IO;
21763 @b{with} GNAT.Traceback.Symbolic;
21765 @b{procedure} STB @b{is}
21767    @b{procedure} P1 @b{is}
21768    @b{begin}
21769       @b{raise} Constraint_Error;
21770    @b{end} P1;
21772    @b{procedure} P2 @b{is}
21773    @b{begin}
21774       P1;
21775    @b{end} P2;
21777    @b{procedure} P3 @b{is}
21778    @b{begin}
21779       P2;
21780    @b{end} P3;
21782 @b{begin}
21783    P3;
21784 @b{exception}
21785    @b{when} E : @b{others} =>
21786       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21787 @b{end} STB;
21788 @end smallexample
21790 @smallexample
21791 $ gnatmake -g .\stb -bargs -E
21792 $ stb
21794 0040149F in stb.p1 at stb.adb:8
21795 004014B7 in stb.p2 at stb.adb:13
21796 004014CF in stb.p3 at stb.adb:18
21797 004015DD in ada.stb at stb.adb:22
21798 00401461 in main at b~stb.adb:168
21799 004011C4 in __mingw_CRTStartup at crt1.c:200
21800 004011F1 in mainCRTStartup at crt1.c:222
21801 77E892A4 in ?? at ??:0
21802 @end smallexample
21804 @noindent
21805 In the above example the ``.\'' syntax in the @command{gnatmake} command
21806 is currently required by @command{addr2line} for files that are in
21807 the current working directory.
21808 Moreover, the exact sequence of linker options may vary from platform
21809 to platform.
21810 The above @option{-largs} section is for Windows platforms. By contrast,
21811 under Unix there is no need for the @option{-largs} section.
21812 Differences across platforms are due to details of linker implementation.
21814 @node Tracebacks From Anywhere in a Program (symbolic)
21815 @subsubsection Tracebacks From Anywhere in a Program
21817 @noindent
21818 It is possible to get a symbolic stack traceback
21819 from anywhere in a program, just as for non-symbolic tracebacks.
21820 The first step is to obtain a non-symbolic
21821 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21822 information. Here is an example:
21824 @smallexample @c ada
21825 @b{with} Ada.Text_IO;
21826 @b{with} GNAT.Traceback;
21827 @b{with} GNAT.Traceback.Symbolic;
21829 @b{procedure} STB @b{is}
21831    @b{use} Ada;
21832    @b{use} GNAT.Traceback;
21833    @b{use} GNAT.Traceback.Symbolic;
21835    @b{procedure} P1 @b{is}
21836       TB  : Tracebacks_Array (1 .. 10);
21837       --@i{  We are asking for a maximum of 10 stack frames.}
21838       Len : Natural;
21839       --@i{  Len will receive the actual number of stack frames returned.}
21840    @b{begin}
21841       Call_Chain (TB, Len);
21842       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
21843    @b{end} P1;
21845    @b{procedure} P2 @b{is}
21846    @b{begin}
21847       P1;
21848    @b{end} P2;
21850 @b{begin}
21851    P2;
21852 @b{end} STB;
21853 @end smallexample
21855 @c ******************************
21857 @c **************************************
21858 @node Platform-Specific Information for the Run-Time Libraries
21859 @appendix Platform-Specific Information for the Run-Time Libraries
21860 @cindex Tasking and threads libraries
21861 @cindex Threads libraries and tasking
21862 @cindex Run-time libraries (platform-specific information)
21864 @noindent
21865 The GNAT run-time implementation may vary with respect to both the
21866 underlying threads library and the exception handling scheme.
21867 For threads support, one or more of the following are supplied:
21868 @itemize @bullet
21869 @item @b{native threads library}, a binding to the thread package from
21870 the underlying operating system
21872 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21873 POSIX thread package
21874 @end itemize
21876 @noindent
21877 For exception handling, either or both of two models are supplied:
21878 @itemize @bullet
21879 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21880 Most programs should experience a substantial speed improvement by
21881 being compiled with a ZCX run-time.
21882 This is especially true for
21883 tasking applications or applications with many exception handlers.}
21884 @cindex Zero-Cost Exceptions
21885 @cindex ZCX (Zero-Cost Exceptions)
21886 which uses binder-generated tables that
21887 are interrogated at run time to locate a handler
21889 @item @b{setjmp / longjmp} (``SJLJ''),
21890 @cindex setjmp/longjmp Exception Model
21891 @cindex SJLJ (setjmp/longjmp Exception Model)
21892 which uses dynamically-set data to establish
21893 the set of handlers
21894 @end itemize
21896 @noindent
21897 This appendix summarizes which combinations of threads and exception support
21898 are supplied on various GNAT platforms.
21899 It then shows how to select a particular library either
21900 permanently or temporarily,
21901 explains the properties of (and tradeoffs among) the various threads
21902 libraries, and provides some additional
21903 information about several specific platforms.
21905 @menu
21906 * Summary of Run-Time Configurations::
21907 * Specifying a Run-Time Library::
21908 * Choosing the Scheduling Policy::
21909 * Solaris-Specific Considerations::
21910 * Linux-Specific Considerations::
21911 * AIX-Specific Considerations::
21912 * RTX-Specific Considerations::
21913 * HP-UX-Specific Considerations::
21914 @end menu
21916 @node Summary of Run-Time Configurations
21917 @section Summary of Run-Time Configurations
21919 @multitable @columnfractions .30 .70
21920 @item @b{alpha-openvms}
21921 @item @code{@ @ }@i{rts-native (default)}
21922 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21923 @item @code{@ @ @ @ }Exceptions @tab ZCX
21925 @item @code{@ @ }@i{rts-sjlj}
21926 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21927 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21929 @item @b{ia64-hp_linux}
21930 @item @code{@ @ }@i{rts-native (default)}
21931 @item @code{@ @ @ @ }Tasking    @tab pthread library
21932 @item @code{@ @ @ @ }Exceptions @tab ZCX
21934 @item @b{ia64-hpux}
21935 @item @code{@ @ }@i{rts-native (default)}
21936 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21937 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21939 @item @b{ia64-openvms}
21940 @item @code{@ @ }@i{rts-native (default)}
21941 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21942 @item @code{@ @ @ @ }Exceptions @tab ZCX
21944 @item @b{ia64-sgi_linux}
21945 @item @code{@ @ }@i{rts-native (default)}
21946 @item @code{@ @ @ @ }Tasking    @tab pthread library
21947 @item @code{@ @ @ @ }Exceptions @tab ZCX
21949 @item @b{pa-hpux}
21950 @item @code{@ @ }@i{rts-native (default)}
21951 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21952 @item @code{@ @ @ @ }Exceptions @tab ZCX
21954 @item @code{@ @ }@i{rts-sjlj}
21955 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21956 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21958 @item @b{ppc-aix}
21959 @item @code{@ @ }@i{rts-native (default)}
21960 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21961 @item @code{@ @ @ @ }Exceptions @tab ZCX
21963 @item @code{@ @ }@i{rts-sjlj}
21964 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21965 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21967 @item @b{ppc-darwin}
21968 @item @code{@ @ }@i{rts-native (default)}
21969 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21970 @item @code{@ @ @ @ }Exceptions @tab ZCX
21972 @item @b{sparc-solaris}  @tab
21973 @item @code{@ @ }@i{rts-native (default)}
21974 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21975 @item @code{@ @ @ @ }Exceptions @tab ZCX
21977 @item @code{@ @ }@i{rts-pthread}
21978 @item @code{@ @ @ @ }Tasking    @tab pthread library
21979 @item @code{@ @ @ @ }Exceptions @tab ZCX
21981 @item @code{@ @ }@i{rts-sjlj}
21982 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21983 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21985 @item @b{sparc64-solaris}  @tab
21986 @item @code{@ @ }@i{rts-native (default)}
21987 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21988 @item @code{@ @ @ @ }Exceptions @tab ZCX
21990 @item @b{x86-linux}
21991 @item @code{@ @ }@i{rts-native (default)}
21992 @item @code{@ @ @ @ }Tasking    @tab pthread library
21993 @item @code{@ @ @ @ }Exceptions @tab ZCX
21995 @item @code{@ @ }@i{rts-sjlj}
21996 @item @code{@ @ @ @ }Tasking    @tab pthread library
21997 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21999 @item @b{x86-lynx}
22000 @item @code{@ @ }@i{rts-native (default)}
22001 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22002 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22004 @item @b{x86-solaris}
22005 @item @code{@ @ }@i{rts-native (default)}
22006 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
22007 @item @code{@ @ @ @ }Exceptions @tab ZCX
22009 @item @code{@ @ }@i{rts-sjlj}
22010 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22011 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22013 @item @b{x86-windows}
22014 @item @code{@ @ }@i{rts-native (default)}
22015 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22016 @item @code{@ @ @ @ }Exceptions @tab ZCX
22018 @item @code{@ @ }@i{rts-sjlj}
22019 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22020 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22022 @item @b{x86-windows-rtx}
22023 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22024 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
22025 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22027 @item @code{@ @ }@i{rts-rtx-w32}
22028 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
22029 @item @code{@ @ @ @ }Exceptions @tab ZCX
22031 @item @b{x86_64-linux}
22032 @item @code{@ @ }@i{rts-native (default)}
22033 @item @code{@ @ @ @ }Tasking    @tab pthread library
22034 @item @code{@ @ @ @ }Exceptions @tab ZCX
22036 @item @code{@ @ }@i{rts-sjlj}
22037 @item @code{@ @ @ @ }Tasking    @tab pthread library
22038 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22040 @end multitable
22042 @node Specifying a Run-Time Library
22043 @section Specifying a Run-Time Library
22045 @noindent
22046 The @file{adainclude} subdirectory containing the sources of the GNAT
22047 run-time library, and the @file{adalib} subdirectory containing the
22048 @file{ALI} files and the static and/or shared GNAT library, are located
22049 in the gcc target-dependent area:
22051 @smallexample
22052 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22053 @end smallexample
22055 @noindent
22056 As indicated above, on some platforms several run-time libraries are supplied.
22057 These libraries are installed in the target dependent area and
22058 contain a complete source and binary subdirectory. The detailed description
22059 below explains the differences between the different libraries in terms of
22060 their thread support.
22062 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22063 This default run time is selected by the means of soft links.
22064 For example on x86-linux:
22066 @smallexample
22067 @group
22068  $(target-dir)
22069      |
22070      +--- adainclude----------+
22071      |                        |
22072      +--- adalib-----------+  |
22073      |                     |  |
22074      +--- rts-native       |  |
22075      |    |                |  |
22076      |    +--- adainclude <---+
22077      |    |                |
22078      |    +--- adalib <----+
22079      |
22080      +--- rts-sjlj
22081           |
22082           +--- adainclude
22083           |
22084           +--- adalib
22085 @end group
22086 @end smallexample
22088 @noindent
22089 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22090 these soft links can be modified with the following commands:
22092 @smallexample
22093 $ cd $target
22094 $ rm -f adainclude adalib
22095 $ ln -s rts-sjlj/adainclude adainclude
22096 $ ln -s rts-sjlj/adalib adalib
22097 @end smallexample
22099 @noindent
22100 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22101 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22102 @file{$target/ada_object_path}.
22104 Selecting another run-time library temporarily can be
22105 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22106 @cindex @option{--RTS} option
22108 @node Choosing the Scheduling Policy
22109 @section Choosing the Scheduling Policy
22111 @noindent
22112 When using a POSIX threads implementation, you have a choice of several
22113 scheduling policies: @code{SCHED_FIFO},
22114 @cindex @code{SCHED_FIFO} scheduling policy
22115 @code{SCHED_RR}
22116 @cindex @code{SCHED_RR} scheduling policy
22117 and @code{SCHED_OTHER}.
22118 @cindex @code{SCHED_OTHER} scheduling policy
22119 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22120 or @code{SCHED_RR} requires special (e.g., root) privileges.
22122 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22123 @code{SCHED_FIFO},
22124 @cindex @code{SCHED_FIFO} scheduling policy
22125 you can use one of the following:
22127 @itemize @bullet
22128 @item
22129 @code{pragma Time_Slice (0.0)}
22130 @cindex pragma Time_Slice
22131 @item
22132 the corresponding binder option @option{-T0}
22133 @cindex @option{-T0} option
22134 @item
22135 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22136 @cindex pragma Task_Dispatching_Policy
22137 @end itemize
22139 @noindent
22140 To specify @code{SCHED_RR},
22141 @cindex @code{SCHED_RR} scheduling policy
22142 you should use @code{pragma Time_Slice} with a
22143 value greater than @code{0.0}, or else use the corresponding @option{-T}
22144 binder option.
22146 @node Solaris-Specific Considerations
22147 @section Solaris-Specific Considerations
22148 @cindex Solaris Sparc threads libraries
22150 @noindent
22151 This section addresses some topics related to the various threads libraries
22152 on Sparc Solaris.
22154 @menu
22155 * Solaris Threads Issues::
22156 @end menu
22158 @node Solaris Threads Issues
22159 @subsection Solaris Threads Issues
22161 @noindent
22162 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22163 library based on POSIX threads --- @emph{rts-pthread}.
22164 @cindex rts-pthread threads library
22165 This run-time library has the advantage of being mostly shared across all
22166 POSIX-compliant thread implementations, and it also provides under
22167 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22168 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22169 and @code{PTHREAD_PRIO_PROTECT}
22170 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22171 semantics that can be selected using the predefined pragma
22172 @code{Locking_Policy}
22173 @cindex pragma Locking_Policy (under rts-pthread)
22174 with respectively
22175 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22176 @cindex @code{Inheritance_Locking} (under rts-pthread)
22177 @cindex @code{Ceiling_Locking} (under rts-pthread)
22179 As explained above, the native run-time library is based on the Solaris thread
22180 library (@code{libthread}) and is the default library.
22182 When the Solaris threads library is used (this is the default), programs
22183 compiled with GNAT can automatically take advantage of
22184 and can thus execute on multiple processors.
22185 The user can alternatively specify a processor on which the program should run
22186 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22187 is made by
22188 setting the environment variable @env{GNAT_PROCESSOR}
22189 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22190 to one of the following:
22192 @table @code
22193 @item -2
22194 Use the default configuration (run the program on all
22195 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22196 unset
22198 @item -1
22199 Let the run-time implementation choose one processor and run the program on
22200 that processor
22202 @item 0 .. Last_Proc
22203 Run the program on the specified processor.
22204 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22205 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22206 @end table
22208 @node Linux-Specific Considerations
22209 @section Linux-Specific Considerations
22210 @cindex Linux threads libraries
22212 @noindent
22213 On GNU/Linux without NPTL support (usually system with GNU C Library
22214 older than 2.3), the signal model is not POSIX compliant, which means
22215 that to send a signal to the process, you need to send the signal to all
22216 threads, e.g.@: by using @code{killpg()}.
22218 @node AIX-Specific Considerations
22219 @section AIX-Specific Considerations
22220 @cindex AIX resolver library
22222 @noindent
22223 On AIX, the resolver library initializes some internal structure on
22224 the first call to @code{get*by*} functions, which are used to implement
22225 @code{GNAT.Sockets.Get_Host_By_Name} and
22226 @code{GNAT.Sockets.Get_Host_By_Address}.
22227 If such initialization occurs within an Ada task, and the stack size for
22228 the task is the default size, a stack overflow may occur.
22230 To avoid this overflow, the user should either ensure that the first call
22231 to @code{GNAT.Sockets.Get_Host_By_Name} or
22232 @code{GNAT.Sockets.Get_Host_By_Addrss}
22233 occurs in the environment task, or use @code{pragma Storage_Size} to
22234 specify a sufficiently large size for the stack of the task that contains
22235 this call.
22237 @node RTX-Specific Considerations
22238 @section RTX-Specific Considerations
22239 @cindex RTX libraries
22241 @noindent
22242 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22243 API. Applications can be built to work in two different modes:
22245 @itemize @bullet
22246 @item
22247 Windows executables that run in Ring 3 to utilize memory protection
22248 (@emph{rts-rtx-w32}).
22250 @item
22251 Real-time subsystem (RTSS) executables that run in Ring 0, where
22252 performance can be optimized with RTSS applications taking precedent
22253 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22254 the Microsoft linker to handle RTSS libraries.
22256 @end itemize
22258 @node HP-UX-Specific Considerations
22259 @section HP-UX-Specific Considerations
22260 @cindex HP-UX Scheduling
22262 @noindent
22263 On HP-UX, appropriate privileges are required to change the scheduling
22264 parameters of a task. The calling process must have appropriate
22265 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22266 successfully change the scheduling parameters.
22268 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22269 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22270 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22272 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22273 one of the following:
22275 @itemize @bullet
22276 @item
22277 @code{pragma Time_Slice (0.0)}
22278 @cindex pragma Time_Slice
22279 @item
22280 the corresponding binder option @option{-T0}
22281 @cindex @option{-T0} option
22282 @item
22283 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22284 @cindex pragma Task_Dispatching_Policy
22285 @end itemize
22287 @noindent
22288 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22289 you should use @code{pragma Time_Slice} with a
22290 value greater than @code{0.0}, or use the corresponding @option{-T}
22291 binder option, or set the @code{pragma Task_Dispatching_Policy
22292 (Round_Robin_Within_Priorities)}.
22294 @c *******************************
22295 @node Example of Binder Output File
22296 @appendix Example of Binder Output File
22298 @noindent
22299 This Appendix displays the source code for @command{gnatbind}'s output
22300 file generated for a simple ``Hello World'' program.
22301 Comments have been added for clarification purposes.
22303 @smallexample @c adanocomment
22304 @iftex
22305 @leftskip=0cm
22306 @end iftex
22307 --  The package is called Ada_Main unless this name is actually used
22308 --  as a unit name in the partition, in which case some other unique
22309 --  name is used.
22311 @b{with} System;
22312 @b{package} ada_main @b{is}
22314    Elab_Final_Code : Integer;
22315    @b{pragma} Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22317    --  The main program saves the parameters (argument count,
22318    --  argument values, environment pointer) in global variables
22319    --  for later access by other units including
22320    --  Ada.Command_Line.
22322    gnat_argc : Integer;
22323    gnat_argv : System.Address;
22324    gnat_envp : System.Address;
22326    --  The actual variables are stored in a library routine. This
22327    --  is useful for some shared library situations, where there
22328    --  are problems if variables are not in the library.
22330    @b{pragma} Import (C, gnat_argc);
22331    @b{pragma} Import (C, gnat_argv);
22332    @b{pragma} Import (C, gnat_envp);
22334    --  The exit status is similarly an external location
22336    gnat_exit_status : Integer;
22337    @b{pragma} Import (C, gnat_exit_status);
22339    GNAT_Version : @b{constant} String :=
22340                     "GNAT Version: 6.0.0w (20061115)";
22341    @b{pragma} Export (C, GNAT_Version, "__gnat_version");
22343    --  This is the generated adafinal routine that performs
22344    --  finalization at the end of execution. In the case where
22345    --  Ada is the main program, this main program makes a call
22346    --  to adafinal at program termination.
22348    @b{procedure} adafinal;
22349    @b{pragma} Export (C, adafinal, "adafinal");
22351    --  This is the generated adainit routine that performs
22352    --  initialization at the start of execution. In the case
22353    --  where Ada is the main program, this main program makes
22354    --  a call to adainit at program startup.
22356    @b{procedure} adainit;
22357    @b{pragma} Export (C, adainit, "adainit");
22359    --  This routine is called at the start of execution. It is
22360    --  a dummy routine that is used by the debugger to breakpoint
22361    --  at the start of execution.
22363    @b{procedure} Break_Start;
22364    @b{pragma} Import (C, Break_Start, "__gnat_break_start");
22366    --  This is the actual generated main program (it would be
22367    --  suppressed if the no main program switch were used). As
22368    --  required by standard system conventions, this program has
22369    --  the external name main.
22371    @b{function} main
22372      (argc : Integer;
22373       argv : System.Address;
22374       envp : System.Address)
22375       @b{return} Integer;
22376    @b{pragma} Export (C, main, "main");
22378    --  The following set of constants give the version
22379    --  identification values for every unit in the bound
22380    --  partition. This identification is computed from all
22381    --  dependent semantic units, and corresponds to the
22382    --  string that would be returned by use of the
22383    --  Body_Version or Version attributes.
22385    @b{type} Version_32 @b{is} @b{mod} 2 ** 32;
22386    u00001 : @b{constant} Version_32 := 16#7880BEB3#;
22387    u00002 : @b{constant} Version_32 := 16#0D24CBD0#;
22388    u00003 : @b{constant} Version_32 := 16#3283DBEB#;
22389    u00004 : @b{constant} Version_32 := 16#2359F9ED#;
22390    u00005 : @b{constant} Version_32 := 16#664FB847#;
22391    u00006 : @b{constant} Version_32 := 16#68E803DF#;
22392    u00007 : @b{constant} Version_32 := 16#5572E604#;
22393    u00008 : @b{constant} Version_32 := 16#46B173D8#;
22394    u00009 : @b{constant} Version_32 := 16#156A40CF#;
22395    u00010 : @b{constant} Version_32 := 16#033DABE0#;
22396    u00011 : @b{constant} Version_32 := 16#6AB38FEA#;
22397    u00012 : @b{constant} Version_32 := 16#22B6217D#;
22398    u00013 : @b{constant} Version_32 := 16#68A22947#;
22399    u00014 : @b{constant} Version_32 := 16#18CC4A56#;
22400    u00015 : @b{constant} Version_32 := 16#08258E1B#;
22401    u00016 : @b{constant} Version_32 := 16#367D5222#;
22402    u00017 : @b{constant} Version_32 := 16#20C9ECA4#;
22403    u00018 : @b{constant} Version_32 := 16#50D32CB6#;
22404    u00019 : @b{constant} Version_32 := 16#39A8BB77#;
22405    u00020 : @b{constant} Version_32 := 16#5CF8FA2B#;
22406    u00021 : @b{constant} Version_32 := 16#2F1EB794#;
22407    u00022 : @b{constant} Version_32 := 16#31AB6444#;
22408    u00023 : @b{constant} Version_32 := 16#1574B6E9#;
22409    u00024 : @b{constant} Version_32 := 16#5109C189#;
22410    u00025 : @b{constant} Version_32 := 16#56D770CD#;
22411    u00026 : @b{constant} Version_32 := 16#02F9DE3D#;
22412    u00027 : @b{constant} Version_32 := 16#08AB6B2C#;
22413    u00028 : @b{constant} Version_32 := 16#3FA37670#;
22414    u00029 : @b{constant} Version_32 := 16#476457A0#;
22415    u00030 : @b{constant} Version_32 := 16#731E1B6E#;
22416    u00031 : @b{constant} Version_32 := 16#23C2E789#;
22417    u00032 : @b{constant} Version_32 := 16#0F1BD6A1#;
22418    u00033 : @b{constant} Version_32 := 16#7C25DE96#;
22419    u00034 : @b{constant} Version_32 := 16#39ADFFA2#;
22420    u00035 : @b{constant} Version_32 := 16#571DE3E7#;
22421    u00036 : @b{constant} Version_32 := 16#5EB646AB#;
22422    u00037 : @b{constant} Version_32 := 16#4249379B#;
22423    u00038 : @b{constant} Version_32 := 16#0357E00A#;
22424    u00039 : @b{constant} Version_32 := 16#3784FB72#;
22425    u00040 : @b{constant} Version_32 := 16#2E723019#;
22426    u00041 : @b{constant} Version_32 := 16#623358EA#;
22427    u00042 : @b{constant} Version_32 := 16#107F9465#;
22428    u00043 : @b{constant} Version_32 := 16#6843F68A#;
22429    u00044 : @b{constant} Version_32 := 16#63305874#;
22430    u00045 : @b{constant} Version_32 := 16#31E56CE1#;
22431    u00046 : @b{constant} Version_32 := 16#02917970#;
22432    u00047 : @b{constant} Version_32 := 16#6CCBA70E#;
22433    u00048 : @b{constant} Version_32 := 16#41CD4204#;
22434    u00049 : @b{constant} Version_32 := 16#572E3F58#;
22435    u00050 : @b{constant} Version_32 := 16#20729FF5#;
22436    u00051 : @b{constant} Version_32 := 16#1D4F93E8#;
22437    u00052 : @b{constant} Version_32 := 16#30B2EC3D#;
22438    u00053 : @b{constant} Version_32 := 16#34054F96#;
22439    u00054 : @b{constant} Version_32 := 16#5A199860#;
22440    u00055 : @b{constant} Version_32 := 16#0E7F912B#;
22441    u00056 : @b{constant} Version_32 := 16#5760634A#;
22442    u00057 : @b{constant} Version_32 := 16#5D851835#;
22444    --  The following Export pragmas export the version numbers
22445    --  with symbolic names ending in B (for body) or S
22446    --  (for spec) so that they can be located in a link. The
22447    --  information provided here is sufficient to track down
22448    --  the exact versions of units used in a given build.
22450    @b{pragma} Export (C, u00001, "helloB");
22451    @b{pragma} Export (C, u00002, "system__standard_libraryB");
22452    @b{pragma} Export (C, u00003, "system__standard_libraryS");
22453    @b{pragma} Export (C, u00004, "adaS");
22454    @b{pragma} Export (C, u00005, "ada__text_ioB");
22455    @b{pragma} Export (C, u00006, "ada__text_ioS");
22456    @b{pragma} Export (C, u00007, "ada__exceptionsB");
22457    @b{pragma} Export (C, u00008, "ada__exceptionsS");
22458    @b{pragma} Export (C, u00009, "gnatS");
22459    @b{pragma} Export (C, u00010, "gnat__heap_sort_aB");
22460    @b{pragma} Export (C, u00011, "gnat__heap_sort_aS");
22461    @b{pragma} Export (C, u00012, "systemS");
22462    @b{pragma} Export (C, u00013, "system__exception_tableB");
22463    @b{pragma} Export (C, u00014, "system__exception_tableS");
22464    @b{pragma} Export (C, u00015, "gnat__htableB");
22465    @b{pragma} Export (C, u00016, "gnat__htableS");
22466    @b{pragma} Export (C, u00017, "system__exceptionsS");
22467    @b{pragma} Export (C, u00018, "system__machine_state_operationsB");
22468    @b{pragma} Export (C, u00019, "system__machine_state_operationsS");
22469    @b{pragma} Export (C, u00020, "system__machine_codeS");
22470    @b{pragma} Export (C, u00021, "system__storage_elementsB");
22471    @b{pragma} Export (C, u00022, "system__storage_elementsS");
22472    @b{pragma} Export (C, u00023, "system__secondary_stackB");
22473    @b{pragma} Export (C, u00024, "system__secondary_stackS");
22474    @b{pragma} Export (C, u00025, "system__parametersB");
22475    @b{pragma} Export (C, u00026, "system__parametersS");
22476    @b{pragma} Export (C, u00027, "system__soft_linksB");
22477    @b{pragma} Export (C, u00028, "system__soft_linksS");
22478    @b{pragma} Export (C, u00029, "system__stack_checkingB");
22479    @b{pragma} Export (C, u00030, "system__stack_checkingS");
22480    @b{pragma} Export (C, u00031, "system__tracebackB");
22481    @b{pragma} Export (C, u00032, "system__tracebackS");
22482    @b{pragma} Export (C, u00033, "ada__streamsS");
22483    @b{pragma} Export (C, u00034, "ada__tagsB");
22484    @b{pragma} Export (C, u00035, "ada__tagsS");
22485    @b{pragma} Export (C, u00036, "system__string_opsB");
22486    @b{pragma} Export (C, u00037, "system__string_opsS");
22487    @b{pragma} Export (C, u00038, "interfacesS");
22488    @b{pragma} Export (C, u00039, "interfaces__c_streamsB");
22489    @b{pragma} Export (C, u00040, "interfaces__c_streamsS");
22490    @b{pragma} Export (C, u00041, "system__file_ioB");
22491    @b{pragma} Export (C, u00042, "system__file_ioS");
22492    @b{pragma} Export (C, u00043, "ada__finalizationB");
22493    @b{pragma} Export (C, u00044, "ada__finalizationS");
22494    @b{pragma} Export (C, u00045, "system__finalization_rootB");
22495    @b{pragma} Export (C, u00046, "system__finalization_rootS");
22496    @b{pragma} Export (C, u00047, "system__finalization_implementationB");
22497    @b{pragma} Export (C, u00048, "system__finalization_implementationS");
22498    @b{pragma} Export (C, u00049, "system__string_ops_concat_3B");
22499    @b{pragma} Export (C, u00050, "system__string_ops_concat_3S");
22500    @b{pragma} Export (C, u00051, "system__stream_attributesB");
22501    @b{pragma} Export (C, u00052, "system__stream_attributesS");
22502    @b{pragma} Export (C, u00053, "ada__io_exceptionsS");
22503    @b{pragma} Export (C, u00054, "system__unsigned_typesS");
22504    @b{pragma} Export (C, u00055, "system__file_control_blockS");
22505    @b{pragma} Export (C, u00056, "ada__finalization__list_controllerB");
22506    @b{pragma} Export (C, u00057, "ada__finalization__list_controllerS");
22508    -- BEGIN ELABORATION ORDER
22509    -- ada (spec)
22510    -- gnat (spec)
22511    -- gnat.heap_sort_a (spec)
22512    -- gnat.heap_sort_a (body)
22513    -- gnat.htable (spec)
22514    -- gnat.htable (body)
22515    -- interfaces (spec)
22516    -- system (spec)
22517    -- system.machine_code (spec)
22518    -- system.parameters (spec)
22519    -- system.parameters (body)
22520    -- interfaces.c_streams (spec)
22521    -- interfaces.c_streams (body)
22522    -- system.standard_library (spec)
22523    -- ada.exceptions (spec)
22524    -- system.exception_table (spec)
22525    -- system.exception_table (body)
22526    -- ada.io_exceptions (spec)
22527    -- system.exceptions (spec)
22528    -- system.storage_elements (spec)
22529    -- system.storage_elements (body)
22530    -- system.machine_state_operations (spec)
22531    -- system.machine_state_operations (body)
22532    -- system.secondary_stack (spec)
22533    -- system.stack_checking (spec)
22534    -- system.soft_links (spec)
22535    -- system.soft_links (body)
22536    -- system.stack_checking (body)
22537    -- system.secondary_stack (body)
22538    -- system.standard_library (body)
22539    -- system.string_ops (spec)
22540    -- system.string_ops (body)
22541    -- ada.tags (spec)
22542    -- ada.tags (body)
22543    -- ada.streams (spec)
22544    -- system.finalization_root (spec)
22545    -- system.finalization_root (body)
22546    -- system.string_ops_concat_3 (spec)
22547    -- system.string_ops_concat_3 (body)
22548    -- system.traceback (spec)
22549    -- system.traceback (body)
22550    -- ada.exceptions (body)
22551    -- system.unsigned_types (spec)
22552    -- system.stream_attributes (spec)
22553    -- system.stream_attributes (body)
22554    -- system.finalization_implementation (spec)
22555    -- system.finalization_implementation (body)
22556    -- ada.finalization (spec)
22557    -- ada.finalization (body)
22558    -- ada.finalization.list_controller (spec)
22559    -- ada.finalization.list_controller (body)
22560    -- system.file_control_block (spec)
22561    -- system.file_io (spec)
22562    -- system.file_io (body)
22563    -- ada.text_io (spec)
22564    -- ada.text_io (body)
22565    -- hello (body)
22566    -- END ELABORATION ORDER
22568 @b{end} ada_main;
22570 --  The following source file name pragmas allow the generated file
22571 --  names to be unique for different main programs. They are needed
22572 --  since the package name will always be Ada_Main.
22574 @b{pragma} Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22575 @b{pragma} Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22577 --  Generated package body for Ada_Main starts here
22579 @b{package} @b{body} ada_main @b{is}
22581    --  The actual finalization is performed by calling the
22582    --  library routine in System.Standard_Library.Adafinal
22584    @b{procedure} Do_Finalize;
22585    @b{pragma} Import (C, Do_Finalize, "system__standard_library__adafinal");
22587    -------------
22588    -- adainit --
22589    -------------
22591 @findex adainit
22592    @b{procedure} adainit @b{is}
22594       --  These booleans are set to True once the associated unit has
22595       --  been elaborated. It is also used to avoid elaborating the
22596       --  same unit twice.
22598       E040 : Boolean;
22599       @b{pragma} Import (Ada, E040, "interfaces__c_streams_E");
22601       E008 : Boolean;
22602       @b{pragma} Import (Ada, E008, "ada__exceptions_E");
22604       E014 : Boolean;
22605       @b{pragma} Import (Ada, E014, "system__exception_table_E");
22607       E053 : Boolean;
22608       @b{pragma} Import (Ada, E053, "ada__io_exceptions_E");
22610       E017 : Boolean;
22611       @b{pragma} Import (Ada, E017, "system__exceptions_E");
22613       E024 : Boolean;
22614       @b{pragma} Import (Ada, E024, "system__secondary_stack_E");
22616       E030 : Boolean;
22617       @b{pragma} Import (Ada, E030, "system__stack_checking_E");
22619       E028 : Boolean;
22620       @b{pragma} Import (Ada, E028, "system__soft_links_E");
22622       E035 : Boolean;
22623       @b{pragma} Import (Ada, E035, "ada__tags_E");
22625       E033 : Boolean;
22626       @b{pragma} Import (Ada, E033, "ada__streams_E");
22628       E046 : Boolean;
22629       @b{pragma} Import (Ada, E046, "system__finalization_root_E");
22631       E048 : Boolean;
22632       @b{pragma} Import (Ada, E048, "system__finalization_implementation_E");
22634       E044 : Boolean;
22635       @b{pragma} Import (Ada, E044, "ada__finalization_E");
22637       E057 : Boolean;
22638       @b{pragma} Import (Ada, E057, "ada__finalization__list_controller_E");
22640       E055 : Boolean;
22641       @b{pragma} Import (Ada, E055, "system__file_control_block_E");
22643       E042 : Boolean;
22644       @b{pragma} Import (Ada, E042, "system__file_io_E");
22646       E006 : Boolean;
22647       @b{pragma} Import (Ada, E006, "ada__text_io_E");
22649       --  Set_Globals is a library routine that stores away the
22650       --  value of the indicated set of global values in global
22651       --  variables within the library.
22653       @b{procedure} Set_Globals
22654         (Main_Priority            : Integer;
22655          Time_Slice_Value         : Integer;
22656          WC_Encoding              : Character;
22657          Locking_Policy           : Character;
22658          Queuing_Policy           : Character;
22659          Task_Dispatching_Policy  : Character;
22660          Adafinal                 : System.Address;
22661          Unreserve_All_Interrupts : Integer;
22662          Exception_Tracebacks     : Integer);
22663 @findex __gnat_set_globals
22664       @b{pragma} Import (C, Set_Globals, "__gnat_set_globals");
22666       --  SDP_Table_Build is a library routine used to build the
22667       --  exception tables. See unit Ada.Exceptions in files
22668       --  a-except.ads/adb for full details of how zero cost
22669       --  exception handling works. This procedure, the call to
22670       --  it, and the two following tables are all omitted if the
22671       --  build is in longjmp/setjmp exception mode.
22673 @findex SDP_Table_Build
22674 @findex Zero Cost Exceptions
22675       @b{procedure} SDP_Table_Build
22676         (SDP_Addresses   : System.Address;
22677          SDP_Count       : Natural;
22678          Elab_Addresses  : System.Address;
22679          Elab_Addr_Count : Natural);
22680       @b{pragma} Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22682       --  Table of Unit_Exception_Table addresses. Used for zero
22683       --  cost exception handling to build the top level table.
22685       ST : @b{aliased} @b{constant} @b{array} (1 .. 23) @b{of} System.Address := (
22686         Hello'UET_Address,
22687         Ada.Text_Io'UET_Address,
22688         Ada.Exceptions'UET_Address,
22689         Gnat.Heap_Sort_A'UET_Address,
22690         System.Exception_Table'UET_Address,
22691         System.Machine_State_Operations'UET_Address,
22692         System.Secondary_Stack'UET_Address,
22693         System.Parameters'UET_Address,
22694         System.Soft_Links'UET_Address,
22695         System.Stack_Checking'UET_Address,
22696         System.Traceback'UET_Address,
22697         Ada.Streams'UET_Address,
22698         Ada.Tags'UET_Address,
22699         System.String_Ops'UET_Address,
22700         Interfaces.C_Streams'UET_Address,
22701         System.File_Io'UET_Address,
22702         Ada.Finalization'UET_Address,
22703         System.Finalization_Root'UET_Address,
22704         System.Finalization_Implementation'UET_Address,
22705         System.String_Ops_Concat_3'UET_Address,
22706         System.Stream_Attributes'UET_Address,
22707         System.File_Control_Block'UET_Address,
22708         Ada.Finalization.List_Controller'UET_Address);
22710       --  Table of addresses of elaboration routines. Used for
22711       --  zero cost exception handling to make sure these
22712       --  addresses are included in the top level procedure
22713       --  address table.
22715       EA : @b{aliased} @b{constant} @b{array} (1 .. 23) @b{of} System.Address := (
22716         adainit'Code_Address,
22717         Do_Finalize'Code_Address,
22718         Ada.Exceptions'Elab_Spec'Address,
22719         System.Exceptions'Elab_Spec'Address,
22720         Interfaces.C_Streams'Elab_Spec'Address,
22721         System.Exception_Table'Elab_Body'Address,
22722         Ada.Io_Exceptions'Elab_Spec'Address,
22723         System.Stack_Checking'Elab_Spec'Address,
22724         System.Soft_Links'Elab_Body'Address,
22725         System.Secondary_Stack'Elab_Body'Address,
22726         Ada.Tags'Elab_Spec'Address,
22727         Ada.Tags'Elab_Body'Address,
22728         Ada.Streams'Elab_Spec'Address,
22729         System.Finalization_Root'Elab_Spec'Address,
22730         Ada.Exceptions'Elab_Body'Address,
22731         System.Finalization_Implementation'Elab_Spec'Address,
22732         System.Finalization_Implementation'Elab_Body'Address,
22733         Ada.Finalization'Elab_Spec'Address,
22734         Ada.Finalization.List_Controller'Elab_Spec'Address,
22735         System.File_Control_Block'Elab_Spec'Address,
22736         System.File_Io'Elab_Body'Address,
22737         Ada.Text_Io'Elab_Spec'Address,
22738         Ada.Text_Io'Elab_Body'Address);
22740    --  Start of processing for adainit
22742    @b{begin}
22744       --  Call SDP_Table_Build to build the top level procedure
22745       --  table for zero cost exception handling (omitted in
22746       --  longjmp/setjmp mode).
22748       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22750       --  Call Set_Globals to record various information for
22751       --  this partition.  The values are derived by the binder
22752       --  from information stored in the ali files by the compiler.
22754 @findex __gnat_set_globals
22755       Set_Globals
22756         (Main_Priority            => -1,
22757          --  Priority of main program, -1 if no pragma Priority used
22759          Time_Slice_Value         => -1,
22760          --  Time slice from Time_Slice pragma, -1 if none used
22762          WC_Encoding              => 'b',
22763          --  Wide_Character encoding used, default is brackets
22765          Locking_Policy           => ' ',
22766          --  Locking_Policy used, default of space means not
22767          --  specified, otherwise it is the first character of
22768          --  the policy name.
22770          Queuing_Policy           => ' ',
22771          --  Queuing_Policy used, default of space means not
22772          --  specified, otherwise it is the first character of
22773          --  the policy name.
22775          Task_Dispatching_Policy  => ' ',
22776          --  Task_Dispatching_Policy used, default of space means
22777          --  not specified, otherwise first character of the
22778          --  policy name.
22780          Adafinal                 => System.Null_Address,
22781          --  Address of Adafinal routine, not used anymore
22783          Unreserve_All_Interrupts => 0,
22784          --  Set true if pragma Unreserve_All_Interrupts was used
22786          Exception_Tracebacks     => 0);
22787          --  Indicates if exception tracebacks are enabled
22789       Elab_Final_Code := 1;
22791       --  Now we have the elaboration calls for all units in the partition.
22792       --  The Elab_Spec and Elab_Body attributes generate references to the
22793       --  implicit elaboration procedures generated by the compiler for
22794       --  each unit that requires elaboration.
22796       @b{if} @b{not} E040 @b{then}
22797          Interfaces.C_Streams'Elab_Spec;
22798       @b{end} @b{if};
22799       E040 := True;
22800       @b{if} @b{not} E008 @b{then}
22801          Ada.Exceptions'Elab_Spec;
22802       @b{end} @b{if};
22803       @b{if} @b{not} E014 @b{then}
22804          System.Exception_Table'Elab_Body;
22805          E014 := True;
22806       @b{end} @b{if};
22807       @b{if} @b{not} E053 @b{then}
22808          Ada.Io_Exceptions'Elab_Spec;
22809          E053 := True;
22810       @b{end} @b{if};
22811       @b{if} @b{not} E017 @b{then}
22812          System.Exceptions'Elab_Spec;
22813          E017 := True;
22814       @b{end} @b{if};
22815       @b{if} @b{not} E030 @b{then}
22816          System.Stack_Checking'Elab_Spec;
22817       @b{end} @b{if};
22818       @b{if} @b{not} E028 @b{then}
22819          System.Soft_Links'Elab_Body;
22820          E028 := True;
22821       @b{end} @b{if};
22822       E030 := True;
22823       @b{if} @b{not} E024 @b{then}
22824          System.Secondary_Stack'Elab_Body;
22825          E024 := True;
22826       @b{end} @b{if};
22827       @b{if} @b{not} E035 @b{then}
22828          Ada.Tags'Elab_Spec;
22829       @b{end} @b{if};
22830       @b{if} @b{not} E035 @b{then}
22831          Ada.Tags'Elab_Body;
22832          E035 := True;
22833       @b{end} @b{if};
22834       @b{if} @b{not} E033 @b{then}
22835          Ada.Streams'Elab_Spec;
22836          E033 := True;
22837       @b{end} @b{if};
22838       @b{if} @b{not} E046 @b{then}
22839          System.Finalization_Root'Elab_Spec;
22840       @b{end} @b{if};
22841       E046 := True;
22842       @b{if} @b{not} E008 @b{then}
22843          Ada.Exceptions'Elab_Body;
22844          E008 := True;
22845       @b{end} @b{if};
22846       @b{if} @b{not} E048 @b{then}
22847          System.Finalization_Implementation'Elab_Spec;
22848       @b{end} @b{if};
22849       @b{if} @b{not} E048 @b{then}
22850          System.Finalization_Implementation'Elab_Body;
22851          E048 := True;
22852       @b{end} @b{if};
22853       @b{if} @b{not} E044 @b{then}
22854          Ada.Finalization'Elab_Spec;
22855       @b{end} @b{if};
22856       E044 := True;
22857       @b{if} @b{not} E057 @b{then}
22858          Ada.Finalization.List_Controller'Elab_Spec;
22859       @b{end} @b{if};
22860       E057 := True;
22861       @b{if} @b{not} E055 @b{then}
22862          System.File_Control_Block'Elab_Spec;
22863          E055 := True;
22864       @b{end} @b{if};
22865       @b{if} @b{not} E042 @b{then}
22866          System.File_Io'Elab_Body;
22867          E042 := True;
22868       @b{end} @b{if};
22869       @b{if} @b{not} E006 @b{then}
22870          Ada.Text_Io'Elab_Spec;
22871       @b{end} @b{if};
22872       @b{if} @b{not} E006 @b{then}
22873          Ada.Text_Io'Elab_Body;
22874          E006 := True;
22875       @b{end} @b{if};
22877       Elab_Final_Code := 0;
22878    @b{end} adainit;
22880    --------------
22881    -- adafinal --
22882    --------------
22884 @findex adafinal
22885    @b{procedure} adafinal @b{is}
22886    @b{begin}
22887       Do_Finalize;
22888    @b{end} adafinal;
22890    ----------
22891    -- main --
22892    ----------
22894    --  main is actually a function, as in the ANSI C standard,
22895    --  defined to return the exit status. The three parameters
22896    --  are the argument count, argument values and environment
22897    --  pointer.
22899 @findex Main Program
22900    @b{function} main
22901      (argc : Integer;
22902       argv : System.Address;
22903       envp : System.Address)
22904       @b{return} Integer
22905    @b{is}
22906       --  The initialize routine performs low level system
22907       --  initialization using a standard library routine which
22908       --  sets up signal handling and performs any other
22909       --  required setup. The routine can be found in file
22910       --  a-init.c.
22912 @findex __gnat_initialize
22913       @b{procedure} initialize;
22914       @b{pragma} Import (C, initialize, "__gnat_initialize");
22916       --  The finalize routine performs low level system
22917       --  finalization using a standard library routine. The
22918       --  routine is found in file a-final.c and in the standard
22919       --  distribution is a dummy routine that does nothing, so
22920       --  really this is a hook for special user finalization.
22922 @findex __gnat_finalize
22923       @b{procedure} finalize;
22924       @b{pragma} Import (C, finalize, "__gnat_finalize");
22926       --  We get to the main program of the partition by using
22927       --  pragma Import because if we try to with the unit and
22928       --  call it Ada style, then not only do we waste time
22929       --  recompiling it, but also, we don't really know the right
22930       --  switches (e.g.@: identifier character set) to be used
22931       --  to compile it.
22933       @b{procedure} Ada_Main_Program;
22934       @b{pragma} Import (Ada, Ada_Main_Program, "_ada_hello");
22936    --  Start of processing for main
22938    @b{begin}
22939       --  Save global variables
22941       gnat_argc := argc;
22942       gnat_argv := argv;
22943       gnat_envp := envp;
22945       --  Call low level system initialization
22947       Initialize;
22949       --  Call our generated Ada initialization routine
22951       adainit;
22953       --  This is the point at which we want the debugger to get
22954       --  control
22956       Break_Start;
22958       --  Now we call the main program of the partition
22960       Ada_Main_Program;
22962       --  Perform Ada finalization
22964       adafinal;
22966       --  Perform low level system finalization
22968       Finalize;
22970       --  Return the proper exit status
22971       @b{return} (gnat_exit_status);
22972    @b{end};
22974 --  This section is entirely comments, so it has no effect on the
22975 --  compilation of the Ada_Main package. It provides the list of
22976 --  object files and linker options, as well as some standard
22977 --  libraries needed for the link. The gnatlink utility parses
22978 --  this b~hello.adb file to read these comment lines to generate
22979 --  the appropriate command line arguments for the call to the
22980 --  system linker. The BEGIN/END lines are used for sentinels for
22981 --  this parsing operation.
22983 --  The exact file names will of course depend on the environment,
22984 --  host/target and location of files on the host system.
22986 @findex Object file list
22987 -- BEGIN Object file/option list
22988    --   ./hello.o
22989    --   -L./
22990    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22991    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22992 -- END Object file/option list
22994 @b{end} ada_main;
22995 @end smallexample
22997 @noindent
22998 The Ada code in the above example is exactly what is generated by the
22999 binder. We have added comments to more clearly indicate the function
23000 of each part of the generated @code{Ada_Main} package.
23002 The code is standard Ada in all respects, and can be processed by any
23003 tools that handle Ada. In particular, it is possible to use the debugger
23004 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23005 suppose that for reasons that you do not understand, your program is crashing
23006 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23007 you can place a breakpoint on the call:
23009 @smallexample @c ada
23010 Ada.Text_Io'Elab_Body;
23011 @end smallexample
23013 @noindent
23014 and trace the elaboration routine for this package to find out where
23015 the problem might be (more usually of course you would be debugging
23016 elaboration code in your own application).
23018 @node Elaboration Order Handling in GNAT
23019 @appendix Elaboration Order Handling in GNAT
23020 @cindex Order of elaboration
23021 @cindex Elaboration control
23023 @menu
23024 * Elaboration Code::
23025 * Checking the Elaboration Order::
23026 * Controlling the Elaboration Order::
23027 * Controlling Elaboration in GNAT - Internal Calls::
23028 * Controlling Elaboration in GNAT - External Calls::
23029 * Default Behavior in GNAT - Ensuring Safety::
23030 * Treatment of Pragma Elaborate::
23031 * Elaboration Issues for Library Tasks::
23032 * Mixing Elaboration Models::
23033 * What to Do If the Default Elaboration Behavior Fails::
23034 * Elaboration for Indirect Calls::
23035 * Summary of Procedures for Elaboration Control::
23036 * Other Elaboration Order Considerations::
23037 * Determining the Chosen Elaboration Order::
23038 @end menu
23040 @noindent
23041 This chapter describes the handling of elaboration code in Ada and
23042 in GNAT, and discusses how the order of elaboration of program units can
23043 be controlled in GNAT, either automatically or with explicit programming
23044 features.
23046 @node Elaboration Code
23047 @section Elaboration Code
23049 @noindent
23050 Ada provides rather general mechanisms for executing code at elaboration
23051 time, that is to say before the main program starts executing. Such code arises
23052 in three contexts:
23054 @table @asis
23055 @item Initializers for variables.
23056 Variables declared at the library level, in package specs or bodies, can
23057 require initialization that is performed at elaboration time, as in:
23058 @smallexample @c ada
23059 @cartouche
23060 Sqrt_Half : Float := Sqrt (0.5);
23061 @end cartouche
23062 @end smallexample
23064 @item Package initialization code
23065 Code in a @code{BEGIN-END} section at the outer level of a package body is
23066 executed as part of the package body elaboration code.
23068 @item Library level task allocators
23069 Tasks that are declared using task allocators at the library level
23070 start executing immediately and hence can execute at elaboration time.
23071 @end table
23073 @noindent
23074 Subprogram calls are possible in any of these contexts, which means that
23075 any arbitrary part of the program may be executed as part of the elaboration
23076 code. It is even possible to write a program which does all its work at
23077 elaboration time, with a null main program, although stylistically this
23078 would usually be considered an inappropriate way to structure
23079 a program.
23081 An important concern arises in the context of elaboration code:
23082 we have to be sure that it is executed in an appropriate order. What we
23083 have is a series of elaboration code sections, potentially one section
23084 for each unit in the program. It is important that these execute
23085 in the correct order. Correctness here means that, taking the above
23086 example of the declaration of @code{Sqrt_Half},
23087 if some other piece of
23088 elaboration code references @code{Sqrt_Half},
23089 then it must run after the
23090 section of elaboration code that contains the declaration of
23091 @code{Sqrt_Half}.
23093 There would never be any order of elaboration problem if we made a rule
23094 that whenever you @code{with} a unit, you must elaborate both the spec and body
23095 of that unit before elaborating the unit doing the @code{with}'ing:
23097 @smallexample @c ada
23098 @group
23099 @cartouche
23100 @b{with} Unit_1;
23101 @b{package} Unit_2 @b{is} @dots{}
23102 @end cartouche
23103 @end group
23104 @end smallexample
23106 @noindent
23107 would require that both the body and spec of @code{Unit_1} be elaborated
23108 before the spec of @code{Unit_2}. However, a rule like that would be far too
23109 restrictive. In particular, it would make it impossible to have routines
23110 in separate packages that were mutually recursive.
23112 You might think that a clever enough compiler could look at the actual
23113 elaboration code and determine an appropriate correct order of elaboration,
23114 but in the general case, this is not possible. Consider the following
23115 example.
23117 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23118 that references
23119 the variable @code{Sqrt_1}, which is declared in the elaboration code
23120 of the body of @code{Unit_1}:
23122 @smallexample @c ada
23123 @cartouche
23124 Sqrt_1 : Float := Sqrt (0.1);
23125 @end cartouche
23126 @end smallexample
23128 @noindent
23129 The elaboration code of the body of @code{Unit_1} also contains:
23131 @smallexample @c ada
23132 @group
23133 @cartouche
23134 @b{if} expression_1 = 1 @b{then}
23135    Q := Unit_2.Func_2;
23136 @b{end} @b{if};
23137 @end cartouche
23138 @end group
23139 @end smallexample
23141 @noindent
23142 @code{Unit_2} is exactly parallel,
23143 it has a procedure @code{Func_2} that references
23144 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23145 the body @code{Unit_2}:
23147 @smallexample @c ada
23148 @cartouche
23149 Sqrt_2 : Float := Sqrt (0.1);
23150 @end cartouche
23151 @end smallexample
23153 @noindent
23154 The elaboration code of the body of @code{Unit_2} also contains:
23156 @smallexample @c ada
23157 @group
23158 @cartouche
23159 @b{if} expression_2 = 2 @b{then}
23160    Q := Unit_1.Func_1;
23161 @b{end} @b{if};
23162 @end cartouche
23163 @end group
23164 @end smallexample
23166 @noindent
23167 Now the question is, which of the following orders of elaboration is
23168 acceptable:
23170 @smallexample
23171 @group
23172 Spec of Unit_1
23173 Spec of Unit_2
23174 Body of Unit_1
23175 Body of Unit_2
23176 @end group
23177 @end smallexample
23179 @noindent
23182 @smallexample
23183 @group
23184 Spec of Unit_2
23185 Spec of Unit_1
23186 Body of Unit_2
23187 Body of Unit_1
23188 @end group
23189 @end smallexample
23191 @noindent
23192 If you carefully analyze the flow here, you will see that you cannot tell
23193 at compile time the answer to this question.
23194 If @code{expression_1} is not equal to 1,
23195 and @code{expression_2} is not equal to 2,
23196 then either order is acceptable, because neither of the function calls is
23197 executed. If both tests evaluate to true, then neither order is acceptable
23198 and in fact there is no correct order.
23200 If one of the two expressions is true, and the other is false, then one
23201 of the above orders is correct, and the other is incorrect. For example,
23202 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23203 then the call to @code{Func_1}
23204 will occur, but not the call to @code{Func_2.}
23205 This means that it is essential
23206 to elaborate the body of @code{Unit_1} before
23207 the body of @code{Unit_2}, so the first
23208 order of elaboration is correct and the second is wrong.
23210 By making @code{expression_1} and @code{expression_2}
23211 depend on input data, or perhaps
23212 the time of day, we can make it impossible for the compiler or binder
23213 to figure out which of these expressions will be true, and hence it
23214 is impossible to guarantee a safe order of elaboration at run time.
23216 @node Checking the Elaboration Order
23217 @section Checking the Elaboration Order
23219 @noindent
23220 In some languages that involve the same kind of elaboration problems,
23221 e.g.@: Java and C++, the programmer is expected to worry about these
23222 ordering problems himself, and it is common to
23223 write a program in which an incorrect elaboration order  gives
23224 surprising results, because it references variables before they
23225 are initialized.
23226 Ada is designed to be a safe language, and a programmer-beware approach is
23227 clearly not sufficient. Consequently, the language provides three lines
23228 of defense:
23230 @table @asis
23231 @item Standard rules
23232 Some standard rules restrict the possible choice of elaboration
23233 order. In particular, if you @code{with} a unit, then its spec is always
23234 elaborated before the unit doing the @code{with}. Similarly, a parent
23235 spec is always elaborated before the child spec, and finally
23236 a spec is always elaborated before its corresponding body.
23238 @item Dynamic elaboration checks
23239 @cindex Elaboration checks
23240 @cindex Checks, elaboration
23241 Dynamic checks are made at run time, so that if some entity is accessed
23242 before it is elaborated (typically  by means of a subprogram call)
23243 then the exception (@code{Program_Error}) is raised.
23245 @item Elaboration control
23246 Facilities are provided for the programmer to specify the desired order
23247 of elaboration.
23248 @end table
23250 Let's look at these facilities in more detail. First, the rules for
23251 dynamic checking. One possible rule would be simply to say that the
23252 exception is raised if you access a variable which has not yet been
23253 elaborated. The trouble with this approach is that it could require
23254 expensive checks on every variable reference. Instead Ada has two
23255 rules which are a little more restrictive, but easier to check, and
23256 easier to state:
23258 @table @asis
23259 @item Restrictions on calls
23260 A subprogram can only be called at elaboration time if its body
23261 has been elaborated. The rules for elaboration given above guarantee
23262 that the spec of the subprogram has been elaborated before the
23263 call, but not the body. If this rule is violated, then the
23264 exception @code{Program_Error} is raised.
23266 @item Restrictions on instantiations
23267 A generic unit can only be instantiated if the body of the generic
23268 unit has been elaborated. Again, the rules for elaboration given above
23269 guarantee that the spec of the generic unit has been elaborated
23270 before the instantiation, but not the body. If this rule is
23271 violated, then the exception @code{Program_Error} is raised.
23272 @end table
23274 @noindent
23275 The idea is that if the body has been elaborated, then any variables
23276 it references must have been elaborated; by checking for the body being
23277 elaborated we guarantee that none of its references causes any
23278 trouble. As we noted above, this is a little too restrictive, because a
23279 subprogram that has no non-local references in its body may in fact be safe
23280 to call. However, it really would be unsafe to rely on this, because
23281 it would mean that the caller was aware of details of the implementation
23282 in the body. This goes against the basic tenets of Ada.
23284 A plausible implementation can be described as follows.
23285 A Boolean variable is associated with each subprogram
23286 and each generic unit. This variable is initialized to False, and is set to
23287 True at the point body is elaborated. Every call or instantiation checks the
23288 variable, and raises @code{Program_Error} if the variable is False.
23290 Note that one might think that it would be good enough to have one Boolean
23291 variable for each package, but that would not deal with cases of trying
23292 to call a body in the same package as the call
23293 that has not been elaborated yet.
23294 Of course a compiler may be able to do enough analysis to optimize away
23295 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23296 does such optimizations, but still the easiest conceptual model is to
23297 think of there being one variable per subprogram.
23299 @node Controlling the Elaboration Order
23300 @section Controlling the Elaboration Order
23302 @noindent
23303 In the previous section we discussed the rules in Ada which ensure
23304 that @code{Program_Error} is raised if an incorrect elaboration order is
23305 chosen. This prevents erroneous executions, but we need mechanisms to
23306 specify a correct execution and avoid the exception altogether.
23307 To achieve this, Ada provides a number of features for controlling
23308 the order of elaboration. We discuss these features in this section.
23310 First, there are several ways of indicating to the compiler that a given
23311 unit has no elaboration problems:
23313 @table @asis
23314 @item packages that do not require a body
23315 A library package that does not require a body does not permit
23316 a body (this rule was introduced in Ada 95).
23317 Thus if we have a such a package, as in:
23319 @smallexample @c ada
23320 @group
23321 @cartouche
23322 @b{package} Definitions @b{is}
23323    @b{generic}
23324       @b{type} m @b{is} @b{new} integer;
23325    @b{package} Subp @b{is}
23326       @b{type} a @b{is} @b{array} (1 .. 10) @b{of} m;
23327       @b{type} b @b{is} @b{array} (1 .. 20) @b{of} m;
23328    @b{end} Subp;
23329 @b{end} Definitions;
23330 @end cartouche
23331 @end group
23332 @end smallexample
23334 @noindent
23335 A package that @code{with}'s @code{Definitions} may safely instantiate
23336 @code{Definitions.Subp} because the compiler can determine that there
23337 definitely is no package body to worry about in this case
23339 @item pragma Pure
23340 @cindex pragma Pure
23341 @findex Pure
23342 Places sufficient restrictions on a unit to guarantee that
23343 no call to any subprogram in the unit can result in an
23344 elaboration problem. This means that the compiler does not need
23345 to worry about the point of elaboration of such units, and in
23346 particular, does not need to check any calls to any subprograms
23347 in this unit.
23349 @item pragma Preelaborate
23350 @findex Preelaborate
23351 @cindex pragma Preelaborate
23352 This pragma places slightly less stringent restrictions on a unit than
23353 does pragma Pure,
23354 but these restrictions are still sufficient to ensure that there
23355 are no elaboration problems with any calls to the unit.
23357 @item pragma Elaborate_Body
23358 @findex Elaborate_Body
23359 @cindex pragma Elaborate_Body
23360 This pragma requires that the body of a unit be elaborated immediately
23361 after its spec. Suppose a unit @code{A} has such a pragma,
23362 and unit @code{B} does
23363 a @code{with} of unit @code{A}. Recall that the standard rules require
23364 the spec of unit @code{A}
23365 to be elaborated before the @code{with}'ing unit; given the pragma in
23366 @code{A}, we also know that the body of @code{A}
23367 will be elaborated before @code{B}, so
23368 that calls to @code{A} are safe and do not need a check.
23369 @end table
23371 @noindent
23372 Note that,
23373 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23374 the use of
23375 @code{Elaborate_Body} does not guarantee that the program is
23376 free of elaboration problems, because it may not be possible
23377 to satisfy the requested elaboration order.
23378 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23379 If a programmer
23380 marks @code{Unit_1} as @code{Elaborate_Body},
23381 and not @code{Unit_2,} then the order of
23382 elaboration will be:
23384 @smallexample
23385 @group
23386 Spec of Unit_2
23387 Spec of Unit_1
23388 Body of Unit_1
23389 Body of Unit_2
23390 @end group
23391 @end smallexample
23393 @noindent
23394 Now that means that the call to @code{Func_1} in @code{Unit_2}
23395 need not be checked,
23396 it must be safe. But the call to @code{Func_2} in
23397 @code{Unit_1} may still fail if
23398 @code{Expression_1} is equal to 1,
23399 and the programmer must still take
23400 responsibility for this not being the case.
23402 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23403 eliminated, except for calls entirely within a body, which are
23404 in any case fully under programmer control. However, using the pragma
23405 everywhere is not always possible.
23406 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23407 we marked both of them as having pragma @code{Elaborate_Body}, then
23408 clearly there would be no possible elaboration order.
23410 The above pragmas allow a server to guarantee safe use by clients, and
23411 clearly this is the preferable approach. Consequently a good rule
23412 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23413 and if this is not possible,
23414 mark them as @code{Elaborate_Body} if possible.
23415 As we have seen, there are situations where neither of these
23416 three pragmas can be used.
23417 So we also provide methods for clients to control the
23418 order of elaboration of the servers on which they depend:
23420 @table @asis
23421 @item pragma Elaborate (unit)
23422 @findex Elaborate
23423 @cindex pragma Elaborate
23424 This pragma is placed in the context clause, after a @code{with} clause,
23425 and it requires that the body of the named unit be elaborated before
23426 the unit in which the pragma occurs. The idea is to use this pragma
23427 if the current unit calls at elaboration time, directly or indirectly,
23428 some subprogram in the named unit.
23430 @item pragma Elaborate_All (unit)
23431 @findex Elaborate_All
23432 @cindex pragma Elaborate_All
23433 This is a stronger version of the Elaborate pragma. Consider the
23434 following example:
23436 @smallexample
23437 Unit A @code{with}'s unit B and calls B.Func in elab code
23438 Unit B @code{with}'s unit C, and B.Func calls C.Func
23439 @end smallexample
23441 @noindent
23442 Now if we put a pragma @code{Elaborate (B)}
23443 in unit @code{A}, this ensures that the
23444 body of @code{B} is elaborated before the call, but not the
23445 body of @code{C}, so
23446 the call to @code{C.Func} could still cause @code{Program_Error} to
23447 be raised.
23449 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23450 not only that the body of the named unit be elaborated before the
23451 unit doing the @code{with}, but also the bodies of all units that the
23452 named unit uses, following @code{with} links transitively. For example,
23453 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23454 then it requires
23455 not only that the body of @code{B} be elaborated before @code{A},
23456 but also the
23457 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23458 @end table
23460 @noindent
23461 We are now in a position to give a usage rule in Ada for avoiding
23462 elaboration problems, at least if dynamic dispatching and access to
23463 subprogram values are not used. We will handle these cases separately
23464 later.
23466 The rule is simple. If a unit has elaboration code that can directly or
23467 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23468 a generic package in a @code{with}'ed unit,
23469 then if the @code{with}'ed unit does not have
23470 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23471 a pragma @code{Elaborate_All}
23472 for the @code{with}'ed unit. By following this rule a client is
23473 assured that calls can be made without risk of an exception.
23475 For generic subprogram instantiations, the rule can be relaxed to
23476 require only a pragma @code{Elaborate} since elaborating the body
23477 of a subprogram cannot cause any transitive elaboration (we are
23478 not calling the subprogram in this case, just elaborating its
23479 declaration).
23481 If this rule is not followed, then a program may be in one of four
23482 states:
23484 @table @asis
23485 @item No order exists
23486 No order of elaboration exists which follows the rules, taking into
23487 account any @code{Elaborate}, @code{Elaborate_All},
23488 or @code{Elaborate_Body} pragmas. In
23489 this case, an Ada compiler must diagnose the situation at bind
23490 time, and refuse to build an executable program.
23492 @item One or more orders exist, all incorrect
23493 One or more acceptable elaboration orders exist, and all of them
23494 generate an elaboration order problem. In this case, the binder
23495 can build an executable program, but @code{Program_Error} will be raised
23496 when the program is run.
23498 @item Several orders exist, some right, some incorrect
23499 One or more acceptable elaboration orders exists, and some of them
23500 work, and some do not. The programmer has not controlled
23501 the order of elaboration, so the binder may or may not pick one of
23502 the correct orders, and the program may or may not raise an
23503 exception when it is run. This is the worst case, because it means
23504 that the program may fail when moved to another compiler, or even
23505 another version of the same compiler.
23507 @item One or more orders exists, all correct
23508 One ore more acceptable elaboration orders exist, and all of them
23509 work. In this case the program runs successfully. This state of
23510 affairs can be guaranteed by following the rule we gave above, but
23511 may be true even if the rule is not followed.
23512 @end table
23514 @noindent
23515 Note that one additional advantage of following our rules on the use
23516 of @code{Elaborate} and @code{Elaborate_All}
23517 is that the program continues to stay in the ideal (all orders OK) state
23518 even if maintenance
23519 changes some bodies of some units. Conversely, if a program that does
23520 not follow this rule happens to be safe at some point, this state of affairs
23521 may deteriorate silently as a result of maintenance changes.
23523 You may have noticed that the above discussion did not mention
23524 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23525 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23526 code in the body makes calls to some other unit, so it is still necessary
23527 to use @code{Elaborate_All} on such units.
23529 @node Controlling Elaboration in GNAT - Internal Calls
23530 @section Controlling Elaboration in GNAT - Internal Calls
23532 @noindent
23533 In the case of internal calls, i.e., calls within a single package, the
23534 programmer has full control over the order of elaboration, and it is up
23535 to the programmer to elaborate declarations in an appropriate order. For
23536 example writing:
23538 @smallexample @c ada
23539 @group
23540 @cartouche
23541 @b{function} One @b{return} Float;
23543 Q : Float := One;
23545 @b{function} One @b{return} Float @b{is}
23546 @b{begin}
23547      @b{return} 1.0;
23548 @b{end} One;
23549 @end cartouche
23550 @end group
23551 @end smallexample
23553 @noindent
23554 will obviously raise @code{Program_Error} at run time, because function
23555 One will be called before its body is elaborated. In this case GNAT will
23556 generate a warning that the call will raise @code{Program_Error}:
23558 @smallexample
23559 @group
23560 @cartouche
23561  1. procedure y is
23562  2.    function One return Float;
23563  3.
23564  4.    Q : Float := One;
23565                     |
23566     >>> warning: cannot call "One" before body is elaborated
23567     >>> warning: Program_Error will be raised at run time
23569  5.
23570  6.    function One return Float is
23571  7.    begin
23572  8.         return 1.0;
23573  9.    end One;
23575 11. begin
23576 12.    null;
23577 13. end;
23578 @end cartouche
23579 @end group
23580 @end smallexample
23582 @noindent
23583 Note that in this particular case, it is likely that the call is safe, because
23584 the function @code{One} does not access any global variables.
23585 Nevertheless in Ada, we do not want the validity of the check to depend on
23586 the contents of the body (think about the separate compilation case), so this
23587 is still wrong, as we discussed in the previous sections.
23589 The error is easily corrected by rearranging the declarations so that the
23590 body of @code{One} appears before the declaration containing the call
23591 (note that in Ada 95 and Ada 2005,
23592 declarations can appear in any order, so there is no restriction that
23593 would prevent this reordering, and if we write:
23595 @smallexample @c ada
23596 @group
23597 @cartouche
23598 @b{function} One @b{return} Float;
23600 @b{function} One @b{return} Float @b{is}
23601 @b{begin}
23602      @b{return} 1.0;
23603 @b{end} One;
23605 Q : Float := One;
23606 @end cartouche
23607 @end group
23608 @end smallexample
23610 @noindent
23611 then all is well, no warning is generated, and no
23612 @code{Program_Error} exception
23613 will be raised.
23614 Things are more complicated when a chain of subprograms is executed:
23616 @smallexample @c ada
23617 @group
23618 @cartouche
23619 @b{function} A @b{return} Integer;
23620 @b{function} B @b{return} Integer;
23621 @b{function} C @b{return} Integer;
23623 @b{function} B @b{return} Integer @b{is} @b{begin} @b{return} A; @b{end};
23624 @b{function} C @b{return} Integer @b{is} @b{begin} @b{return} B; @b{end};
23626 X : Integer := C;
23628 @b{function} A @b{return} Integer @b{is} @b{begin} @b{return} 1; @b{end};
23629 @end cartouche
23630 @end group
23631 @end smallexample
23633 @noindent
23634 Now the call to @code{C}
23635 at elaboration time in the declaration of @code{X} is correct, because
23636 the body of @code{C} is already elaborated,
23637 and the call to @code{B} within the body of
23638 @code{C} is correct, but the call
23639 to @code{A} within the body of @code{B} is incorrect, because the body
23640 of @code{A} has not been elaborated, so @code{Program_Error}
23641 will be raised on the call to @code{A}.
23642 In this case GNAT will generate a
23643 warning that @code{Program_Error} may be
23644 raised at the point of the call. Let's look at the warning:
23646 @smallexample
23647 @group
23648 @cartouche
23649  1. procedure x is
23650  2.    function A return Integer;
23651  3.    function B return Integer;
23652  4.    function C return Integer;
23653  5.
23654  6.    function B return Integer is begin return A; end;
23655                                                     |
23656     >>> warning: call to "A" before body is elaborated may
23657                  raise Program_Error
23658     >>> warning: "B" called at line 7
23659     >>> warning: "C" called at line 9
23661  7.    function C return Integer is begin return B; end;
23662  8.
23663  9.    X : Integer := C;
23665 11.    function A return Integer is begin return 1; end;
23667 13. begin
23668 14.    null;
23669 15. end;
23670 @end cartouche
23671 @end group
23672 @end smallexample
23674 @noindent
23675 Note that the message here says ``may raise'', instead of the direct case,
23676 where the message says ``will be raised''. That's because whether
23677 @code{A} is
23678 actually called depends in general on run-time flow of control.
23679 For example, if the body of @code{B} said
23681 @smallexample @c ada
23682 @group
23683 @cartouche
23684 @b{function} B @b{return} Integer @b{is}
23685 @b{begin}
23686    @b{if} some-condition-depending-on-input-data @b{then}
23687       @b{return} A;
23688    @b{else}
23689       @b{return} 1;
23690    @b{end} @b{if};
23691 @b{end} B;
23692 @end cartouche
23693 @end group
23694 @end smallexample
23696 @noindent
23697 then we could not know until run time whether the incorrect call to A would
23698 actually occur, so @code{Program_Error} might
23699 or might not be raised. It is possible for a compiler to
23700 do a better job of analyzing bodies, to
23701 determine whether or not @code{Program_Error}
23702 might be raised, but it certainly
23703 couldn't do a perfect job (that would require solving the halting problem
23704 and is provably impossible), and because this is a warning anyway, it does
23705 not seem worth the effort to do the analysis. Cases in which it
23706 would be relevant are rare.
23708 In practice, warnings of either of the forms given
23709 above will usually correspond to
23710 real errors, and should be examined carefully and eliminated.
23711 In the rare case where a warning is bogus, it can be suppressed by any of
23712 the following methods:
23714 @itemize @bullet
23715 @item
23716 Compile with the @option{-gnatws} switch set
23718 @item
23719 Suppress @code{Elaboration_Check} for the called subprogram
23721 @item
23722 Use pragma @code{Warnings_Off} to turn warnings off for the call
23723 @end itemize
23725 @noindent
23726 For the internal elaboration check case,
23727 GNAT by default generates the
23728 necessary run-time checks to ensure
23729 that @code{Program_Error} is raised if any
23730 call fails an elaboration check. Of course this can only happen if a
23731 warning has been issued as described above. The use of pragma
23732 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23733 some of these checks, meaning that it may be possible (but is not
23734 guaranteed) for a program to be able to call a subprogram whose body
23735 is not yet elaborated, without raising a @code{Program_Error} exception.
23737 @node Controlling Elaboration in GNAT - External Calls
23738 @section Controlling Elaboration in GNAT - External Calls
23740 @noindent
23741 The previous section discussed the case in which the execution of a
23742 particular thread of elaboration code occurred entirely within a
23743 single unit. This is the easy case to handle, because a programmer
23744 has direct and total control over the order of elaboration, and
23745 furthermore, checks need only be generated in cases which are rare
23746 and which the compiler can easily detect.
23747 The situation is more complex when separate compilation is taken into account.
23748 Consider the following:
23750 @smallexample @c ada
23751 @cartouche
23752 @group
23753 @b{package} Math @b{is}
23754    @b{function} Sqrt (Arg : Float) @b{return} Float;
23755 @b{end} Math;
23757 @b{package} @b{body} Math @b{is}
23758    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
23759    @b{begin}
23760          @dots{}
23761    @b{end} Sqrt;
23762 @b{end} Math;
23763 @end group
23764 @group
23765 @b{with} Math;
23766 @b{package} Stuff @b{is}
23767    X : Float := Math.Sqrt (0.5);
23768 @b{end} Stuff;
23770 @b{with} Stuff;
23771 @b{procedure} Main @b{is}
23772 @b{begin}
23773    @dots{}
23774 @b{end} Main;
23775 @end group
23776 @end cartouche
23777 @end smallexample
23779 @noindent
23780 where @code{Main} is the main program. When this program is executed, the
23781 elaboration code must first be executed, and one of the jobs of the
23782 binder is to determine the order in which the units of a program are
23783 to be elaborated. In this case we have four units: the spec and body
23784 of @code{Math},
23785 the spec of @code{Stuff} and the body of @code{Main}).
23786 In what order should the four separate sections of elaboration code
23787 be executed?
23789 There are some restrictions in the order of elaboration that the binder
23790 can choose. In particular, if unit U has a @code{with}
23791 for a package @code{X}, then you
23792 are assured that the spec of @code{X}
23793 is elaborated before U , but you are
23794 not assured that the body of @code{X}
23795 is elaborated before U.
23796 This means that in the above case, the binder is allowed to choose the
23797 order:
23799 @smallexample
23800 spec of Math
23801 spec of Stuff
23802 body of Math
23803 body of Main
23804 @end smallexample
23806 @noindent
23807 but that's not good, because now the call to @code{Math.Sqrt}
23808 that happens during
23809 the elaboration of the @code{Stuff}
23810 spec happens before the body of @code{Math.Sqrt} is
23811 elaborated, and hence causes @code{Program_Error} exception to be raised.
23812 At first glance, one might say that the binder is misbehaving, because
23813 obviously you want to elaborate the body of something you @code{with}
23814 first, but
23815 that is not a general rule that can be followed in all cases. Consider
23817 @smallexample @c ada
23818 @group
23819 @cartouche
23820 @b{package} X @b{is} @dots{}
23822 @b{package} Y @b{is} @dots{}
23824 @b{with} X;
23825 @b{package} @b{body} Y @b{is} @dots{}
23827 @b{with} Y;
23828 @b{package} @b{body} X @b{is} @dots{}
23829 @end cartouche
23830 @end group
23831 @end smallexample
23833 @noindent
23834 This is a common arrangement, and, apart from the order of elaboration
23835 problems that might arise in connection with elaboration code, this works fine.
23836 A rule that says that you must first elaborate the body of anything you
23837 @code{with} cannot work in this case:
23838 the body of @code{X} @code{with}'s @code{Y},
23839 which means you would have to
23840 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23841 which means
23842 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23843 loop that cannot be broken.
23845 It is true that the binder can in many cases guess an order of elaboration
23846 that is unlikely to cause a @code{Program_Error}
23847 exception to be raised, and it tries to do so (in the
23848 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23849 by default
23850 elaborate the body of @code{Math} right after its spec, so all will be well).
23852 However, a program that blindly relies on the binder to be helpful can
23853 get into trouble, as we discussed in the previous sections, so
23854 GNAT
23855 provides a number of facilities for assisting the programmer in
23856 developing programs that are robust with respect to elaboration order.
23858 @node Default Behavior in GNAT - Ensuring Safety
23859 @section Default Behavior in GNAT - Ensuring Safety
23861 @noindent
23862 The default behavior in GNAT ensures elaboration safety. In its
23863 default mode GNAT implements the
23864 rule we previously described as the right approach. Let's restate it:
23866 @itemize
23867 @item
23868 @emph{If a unit has elaboration code that can directly or indirectly make a
23869 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23870 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23871 does not have pragma @code{Pure} or
23872 @code{Preelaborate}, then the client should have an
23873 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23875 @emph{In the case of instantiating a generic subprogram, it is always
23876 sufficient to have only an @code{Elaborate} pragma for the
23877 @code{with}'ed unit.}
23878 @end itemize
23880 @noindent
23881 By following this rule a client is assured that calls and instantiations
23882 can be made without risk of an exception.
23884 In this mode GNAT traces all calls that are potentially made from
23885 elaboration code, and puts in any missing implicit @code{Elaborate}
23886 and @code{Elaborate_All} pragmas.
23887 The advantage of this approach is that no elaboration problems
23888 are possible if the binder can find an elaboration order that is
23889 consistent with these implicit @code{Elaborate} and
23890 @code{Elaborate_All} pragmas. The
23891 disadvantage of this approach is that no such order may exist.
23893 If the binder does not generate any diagnostics, then it means that it has
23894 found an elaboration order that is guaranteed to be safe. However, the binder
23895 may still be relying on implicitly generated @code{Elaborate} and
23896 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23897 guaranteed.
23899 If it is important to guarantee portability, then the compilations should
23900 use the
23901 @option{-gnatel}
23902 (info messages for elaboration prag mas) switch. This will cause info messages
23903 to be generated indicating the missing @code{Elaborate} and
23904 @code{Elaborate_All} pragmas.
23905 Consider the following source program:
23907 @smallexample @c ada
23908 @group
23909 @cartouche
23910 @b{with} k;
23911 @b{package} j @b{is}
23912   m : integer := k.r;
23913 @b{end};
23914 @end cartouche
23915 @end group
23916 @end smallexample
23918 @noindent
23919 where it is clear that there
23920 should be a pragma @code{Elaborate_All}
23921 for unit @code{k}. An implicit pragma will be generated, and it is
23922 likely that the binder will be able to honor it. However, if you want
23923 to port this program to some other Ada compiler than GNAT.
23924 it is safer to include the pragma explicitly in the source. If this
23925 unit is compiled with the
23926 @option{-gnatel}
23927 switch, then the compiler outputs an information message:
23929 @smallexample
23930 @group
23931 @cartouche
23932 1. with k;
23933 2. package j is
23934 3.   m : integer := k.r;
23935                      |
23936    >>> info: call to "r" may raise Program_Error
23937    >>> info: missing pragma Elaborate_All for "k"
23939 4. end;
23940 @end cartouche
23941 @end group
23942 @end smallexample
23944 @noindent
23945 and these messages can be used as a guide for supplying manually
23946 the missing pragmas. It is usually a bad idea to use this
23947 option during development. That's because it will tell you when
23948 you need to put in a pragma, but cannot tell you when it is time
23949 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23950 unnecessary dependencies and even false circularities.
23952 This default mode is more restrictive than the Ada Reference
23953 Manual, and it is possible to construct programs which will compile
23954 using the dynamic model described there, but will run into a
23955 circularity using the safer static model we have described.
23957 Of course any Ada compiler must be able to operate in a mode
23958 consistent with the requirements of the Ada Reference Manual,
23959 and in particular must have the capability of implementing the
23960 standard dynamic model of elaboration with run-time checks.
23962 In GNAT, this standard mode can be achieved either by the use of
23963 the @option{-gnatE} switch on the compiler (@command{gcc} or
23964 @command{gnatmake}) command, or by the use of the configuration pragma:
23966 @smallexample @c ada
23967 @b{pragma} Elaboration_Checks (DYNAMIC);
23968 @end smallexample
23970 @noindent
23971 Either approach will cause the unit affected to be compiled using the
23972 standard dynamic run-time elaboration checks described in the Ada
23973 Reference Manual. The static model is generally preferable, since it
23974 is clearly safer to rely on compile and link time checks rather than
23975 run-time checks. However, in the case of legacy code, it may be
23976 difficult to meet the requirements of the static model. This
23977 issue is further discussed in
23978 @ref{What to Do If the Default Elaboration Behavior Fails}.
23980 Note that the static model provides a strict subset of the allowed
23981 behavior and programs of the Ada Reference Manual, so if you do
23982 adhere to the static model and no circularities exist,
23983 then you are assured that your program will
23984 work using the dynamic model, providing that you remove any
23985 pragma Elaborate statements from the source.
23987 @node Treatment of Pragma Elaborate
23988 @section Treatment of Pragma Elaborate
23989 @cindex Pragma Elaborate
23991 @noindent
23992 The use of @code{pragma Elaborate}
23993 should generally be avoided in Ada 95 and Ada 2005 programs,
23994 since there is no guarantee that transitive calls
23995 will be properly handled. Indeed at one point, this pragma was placed
23996 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23998 Now that's a bit restrictive. In practice, the case in which
23999 @code{pragma Elaborate} is useful is when the caller knows that there
24000 are no transitive calls, or that the called unit contains all necessary
24001 transitive @code{pragma Elaborate} statements, and legacy code often
24002 contains such uses.
24004 Strictly speaking the static mode in GNAT should ignore such pragmas,
24005 since there is no assurance at compile time that the necessary safety
24006 conditions are met. In practice, this would cause GNAT to be incompatible
24007 with correctly written Ada 83 code that had all necessary
24008 @code{pragma Elaborate} statements in place. Consequently, we made the
24009 decision that GNAT in its default mode will believe that if it encounters
24010 a @code{pragma Elaborate} then the programmer knows what they are doing,
24011 and it will trust that no elaboration errors can occur.
24013 The result of this decision is two-fold. First to be safe using the
24014 static mode, you should remove all @code{pragma Elaborate} statements.
24015 Second, when fixing circularities in existing code, you can selectively
24016 use @code{pragma Elaborate} statements to convince the static mode of
24017 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24018 statement.
24020 When using the static mode with @option{-gnatwl}, any use of
24021 @code{pragma Elaborate} will generate a warning about possible
24022 problems.
24024 @node Elaboration Issues for Library Tasks
24025 @section Elaboration Issues for Library Tasks
24026 @cindex Library tasks, elaboration issues
24027 @cindex Elaboration of library tasks
24029 @noindent
24030 In this section we examine special elaboration issues that arise for
24031 programs that declare library level tasks.
24033 Generally the model of execution of an Ada program is that all units are
24034 elaborated, and then execution of the program starts. However, the
24035 declaration of library tasks definitely does not fit this model. The
24036 reason for this is that library tasks start as soon as they are declared
24037 (more precisely, as soon as the statement part of the enclosing package
24038 body is reached), that is to say before elaboration
24039 of the program is complete. This means that if such a task calls a
24040 subprogram, or an entry in another task, the callee may or may not be
24041 elaborated yet, and in the standard
24042 Reference Manual model of dynamic elaboration checks, you can even
24043 get timing dependent Program_Error exceptions, since there can be
24044 a race between the elaboration code and the task code.
24046 The static model of elaboration in GNAT seeks to avoid all such
24047 dynamic behavior, by being conservative, and the conservative
24048 approach in this particular case is to assume that all the code
24049 in a task body is potentially executed at elaboration time if
24050 a task is declared at the library level.
24052 This can definitely result in unexpected circularities. Consider
24053 the following example
24055 @smallexample @c ada
24056 @b{package} Decls @b{is}
24057   @b{task} Lib_Task @b{is}
24058      @b{entry} Start;
24059   @b{end} Lib_Task;
24061   @b{type} My_Int @b{is} @b{new} Integer;
24063   @b{function} Ident (M : My_Int) @b{return} My_Int;
24064 @b{end} Decls;
24066 @b{with} Utils;
24067 @b{package} @b{body} Decls @b{is}
24068   @b{task} @b{body} Lib_Task @b{is}
24069   @b{begin}
24070      @b{accept} Start;
24071      Utils.Put_Val (2);
24072   @b{end} Lib_Task;
24074   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24075   @b{begin}
24076      @b{return} M;
24077   @b{end} Ident;
24078 @b{end} Decls;
24080 @b{with} Decls;
24081 @b{package} Utils @b{is}
24082   @b{procedure} Put_Val (Arg : Decls.My_Int);
24083 @b{end} Utils;
24085 @b{with} Text_IO;
24086 @b{package} @b{body} Utils @b{is}
24087   @b{procedure} Put_Val (Arg : Decls.My_Int) @b{is}
24088   @b{begin}
24089      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24090   @b{end} Put_Val;
24091 @b{end} Utils;
24093 @b{with} Decls;
24094 @b{procedure} Main @b{is}
24095 @b{begin}
24096    Decls.Lib_Task.Start;
24097 @b{end};
24098 @end smallexample
24100 @noindent
24101 If the above example is compiled in the default static elaboration
24102 mode, then a circularity occurs. The circularity comes from the call
24103 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24104 this call occurs in elaboration code, we need an implicit pragma
24105 @code{Elaborate_All} for @code{Utils}. This means that not only must
24106 the spec and body of @code{Utils} be elaborated before the body
24107 of @code{Decls}, but also the spec and body of any unit that is
24108 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24109 the body of @code{Decls}. This is the transitive implication of
24110 pragma @code{Elaborate_All} and it makes sense, because in general
24111 the body of @code{Put_Val} might have a call to something in a
24112 @code{with'ed} unit.
24114 In this case, the body of Utils (actually its spec) @code{with's}
24115 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24116 must be elaborated before itself, in case there is a call from the
24117 body of @code{Utils}.
24119 Here is the exact chain of events we are worrying about:
24121 @enumerate
24122 @item
24123 In the body of @code{Decls} a call is made from within the body of a library
24124 task to a subprogram in the package @code{Utils}. Since this call may
24125 occur at elaboration time (given that the task is activated at elaboration
24126 time), we have to assume the worst, i.e., that the
24127 call does happen at elaboration time.
24129 @item
24130 This means that the body and spec of @code{Util} must be elaborated before
24131 the body of @code{Decls} so that this call does not cause an access before
24132 elaboration.
24134 @item
24135 Within the body of @code{Util}, specifically within the body of
24136 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24137 by this package.
24139 @item
24140 One such @code{with}'ed package is package @code{Decls}, so there
24141 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24142 In fact there is such a call in this example, but we would have to
24143 assume that there was such a call even if it were not there, since
24144 we are not supposed to write the body of @code{Decls} knowing what
24145 is in the body of @code{Utils}; certainly in the case of the
24146 static elaboration model, the compiler does not know what is in
24147 other bodies and must assume the worst.
24149 @item
24150 This means that the spec and body of @code{Decls} must also be
24151 elaborated before we elaborate the unit containing the call, but
24152 that unit is @code{Decls}! This means that the body of @code{Decls}
24153 must be elaborated before itself, and that's a circularity.
24154 @end enumerate
24156 @noindent
24157 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24158 the body of @code{Decls} you will get a true Ada Reference Manual
24159 circularity that makes the program illegal.
24161 In practice, we have found that problems with the static model of
24162 elaboration in existing code often arise from library tasks, so
24163 we must address this particular situation.
24165 Note that if we compile and run the program above, using the dynamic model of
24166 elaboration (that is to say use the @option{-gnatE} switch),
24167 then it compiles, binds,
24168 links, and runs, printing the expected result of 2. Therefore in some sense
24169 the circularity here is only apparent, and we need to capture
24170 the properties of this program that  distinguish it from other library-level
24171 tasks that have real elaboration problems.
24173 We have four possible answers to this question:
24175 @itemize @bullet
24177 @item
24178 Use the dynamic model of elaboration.
24180 If we use the @option{-gnatE} switch, then as noted above, the program works.
24181 Why is this? If we examine the task body, it is apparent that the task cannot
24182 proceed past the
24183 @code{accept} statement until after elaboration has been completed, because
24184 the corresponding entry call comes from the main program, not earlier.
24185 This is why the dynamic model works here. But that's really giving
24186 up on a precise analysis, and we prefer to take this approach only if we cannot
24187 solve the
24188 problem in any other manner. So let us examine two ways to reorganize
24189 the program to avoid the potential elaboration problem.
24191 @item
24192 Split library tasks into separate packages.
24194 Write separate packages, so that library tasks are isolated from
24195 other declarations as much as possible. Let us look at a variation on
24196 the above program.
24198 @smallexample @c ada
24199 @b{package} Decls1 @b{is}
24200   @b{task} Lib_Task @b{is}
24201      @b{entry} Start;
24202   @b{end} Lib_Task;
24203 @b{end} Decls1;
24205 @b{with} Utils;
24206 @b{package} @b{body} Decls1 @b{is}
24207   @b{task} @b{body} Lib_Task @b{is}
24208   @b{begin}
24209      @b{accept} Start;
24210      Utils.Put_Val (2);
24211   @b{end} Lib_Task;
24212 @b{end} Decls1;
24214 @b{package} Decls2 @b{is}
24215   @b{type} My_Int @b{is} @b{new} Integer;
24216   @b{function} Ident (M : My_Int) @b{return} My_Int;
24217 @b{end} Decls2;
24219 @b{with} Utils;
24220 @b{package} @b{body} Decls2 @b{is}
24221   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24222   @b{begin}
24223      @b{return} M;
24224   @b{end} Ident;
24225 @b{end} Decls2;
24227 @b{with} Decls2;
24228 @b{package} Utils @b{is}
24229   @b{procedure} Put_Val (Arg : Decls2.My_Int);
24230 @b{end} Utils;
24232 @b{with} Text_IO;
24233 @b{package} @b{body} Utils @b{is}
24234   @b{procedure} Put_Val (Arg : Decls2.My_Int) @b{is}
24235   @b{begin}
24236      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24237   @b{end} Put_Val;
24238 @b{end} Utils;
24240 @b{with} Decls1;
24241 @b{procedure} Main @b{is}
24242 @b{begin}
24243    Decls1.Lib_Task.Start;
24244 @b{end};
24245 @end smallexample
24247 @noindent
24248 All we have done is to split @code{Decls} into two packages, one
24249 containing the library task, and one containing everything else. Now
24250 there is no cycle, and the program compiles, binds, links and executes
24251 using the default static model of elaboration.
24253 @item
24254 Declare separate task types.
24256 A significant part of the problem arises because of the use of the
24257 single task declaration form. This means that the elaboration of
24258 the task type, and the elaboration of the task itself (i.e.@: the
24259 creation of the task) happen at the same time. A good rule
24260 of style in Ada is to always create explicit task types. By
24261 following the additional step of placing task objects in separate
24262 packages from the task type declaration, many elaboration problems
24263 are avoided. Here is another modified example of the example program:
24265 @smallexample @c ada
24266 @b{package} Decls @b{is}
24267   @b{task} @b{type} Lib_Task_Type @b{is}
24268      @b{entry} Start;
24269   @b{end} Lib_Task_Type;
24271   @b{type} My_Int @b{is} @b{new} Integer;
24273   @b{function} Ident (M : My_Int) @b{return} My_Int;
24274 @b{end} Decls;
24276 @b{with} Utils;
24277 @b{package} @b{body} Decls @b{is}
24278   @b{task} @b{body} Lib_Task_Type @b{is}
24279   @b{begin}
24280      @b{accept} Start;
24281      Utils.Put_Val (2);
24282   @b{end} Lib_Task_Type;
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} Decls;
24290 @b{with} Decls;
24291 @b{package} Utils @b{is}
24292   @b{procedure} Put_Val (Arg : Decls.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 : Decls.My_Int) @b{is}
24298   @b{begin}
24299      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24300   @b{end} Put_Val;
24301 @b{end} Utils;
24303 @b{with} Decls;
24304 @b{package} Declst @b{is}
24305    Lib_Task : Decls.Lib_Task_Type;
24306 @b{end} Declst;
24308 @b{with} Declst;
24309 @b{procedure} Main @b{is}
24310 @b{begin}
24311    Declst.Lib_Task.Start;
24312 @b{end};
24313 @end smallexample
24315 @noindent
24316 What we have done here is to replace the @code{task} declaration in
24317 package @code{Decls} with a @code{task type} declaration. Then we
24318 introduce a separate package @code{Declst} to contain the actual
24319 task object. This separates the elaboration issues for
24320 the @code{task type}
24321 declaration, which causes no trouble, from the elaboration issues
24322 of the task object, which is also unproblematic, since it is now independent
24323 of the elaboration of  @code{Utils}.
24324 This separation of concerns also corresponds to
24325 a generally sound engineering principle of separating declarations
24326 from instances. This version of the program also compiles, binds, links,
24327 and executes, generating the expected output.
24329 @item
24330 Use No_Entry_Calls_In_Elaboration_Code restriction.
24331 @cindex No_Entry_Calls_In_Elaboration_Code
24333 The previous two approaches described how a program can be restructured
24334 to avoid the special problems caused by library task bodies. in practice,
24335 however, such restructuring may be difficult to apply to existing legacy code,
24336 so we must consider solutions that do not require massive rewriting.
24338 Let us consider more carefully why our original sample program works
24339 under the dynamic model of elaboration. The reason is that the code
24340 in the task body blocks immediately on the @code{accept}
24341 statement. Now of course there is nothing to prohibit elaboration
24342 code from making entry calls (for example from another library level task),
24343 so we cannot tell in isolation that
24344 the task will not execute the accept statement  during elaboration.
24346 However, in practice it is very unusual to see elaboration code
24347 make any entry calls, and the pattern of tasks starting
24348 at elaboration time and then immediately blocking on @code{accept} or
24349 @code{select} statements is very common. What this means is that
24350 the compiler is being too pessimistic when it analyzes the
24351 whole package body as though it might be executed at elaboration
24352 time.
24354 If we know that the elaboration code contains no entry calls, (a very safe
24355 assumption most of the time, that could almost be made the default
24356 behavior), then we can compile all units of the program under control
24357 of the following configuration pragma:
24359 @smallexample
24360 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24361 @end smallexample
24363 @noindent
24364 This pragma can be placed in the @file{gnat.adc} file in the usual
24365 manner. If we take our original unmodified program and compile it
24366 in the presence of a @file{gnat.adc} containing the above pragma,
24367 then once again, we can compile, bind, link, and execute, obtaining
24368 the expected result. In the presence of this pragma, the compiler does
24369 not trace calls in a task body, that appear after the first @code{accept}
24370 or @code{select} statement, and therefore does not report a potential
24371 circularity in the original program.
24373 The compiler will check to the extent it can that the above
24374 restriction is not violated, but it is not always possible to do a
24375 complete check at compile time, so it is important to use this
24376 pragma only if the stated restriction is in fact met, that is to say
24377 no task receives an entry call before elaboration of all units is completed.
24379 @end itemize
24381 @node Mixing Elaboration Models
24382 @section Mixing Elaboration Models
24383 @noindent
24384 So far, we have assumed that the entire program is either compiled
24385 using the dynamic model or static model, ensuring consistency. It
24386 is possible to mix the two models, but rules have to be followed
24387 if this mixing is done to ensure that elaboration checks are not
24388 omitted.
24390 The basic rule is that @emph{a unit compiled with the static model cannot
24391 be @code{with'ed} by a unit compiled with the dynamic model}. The
24392 reason for this is that in the static model, a unit assumes that
24393 its clients guarantee to use (the equivalent of) pragma
24394 @code{Elaborate_All} so that no elaboration checks are required
24395 in inner subprograms, and this assumption is violated if the
24396 client is compiled with dynamic checks.
24398 The precise rule is as follows. A unit that is compiled with dynamic
24399 checks can only @code{with} a unit that meets at least one of the
24400 following criteria:
24402 @itemize @bullet
24404 @item
24405 The @code{with'ed} unit is itself compiled with dynamic elaboration
24406 checks (that is with the @option{-gnatE} switch.
24408 @item
24409 The @code{with'ed} unit is an internal GNAT implementation unit from
24410 the System, Interfaces, Ada, or GNAT hierarchies.
24412 @item
24413 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24415 @item
24416 The @code{with'ing} unit (that is the client) has an explicit pragma
24417 @code{Elaborate_All} for the @code{with'ed} unit.
24419 @end itemize
24421 @noindent
24422 If this rule is violated, that is if a unit with dynamic elaboration
24423 checks @code{with's} a unit that does not meet one of the above four
24424 criteria, then the binder (@code{gnatbind}) will issue a warning
24425 similar to that in the following example:
24427 @smallexample
24428 warning: "x.ads" has dynamic elaboration checks and with's
24429 warning:   "y.ads" which has static elaboration checks
24430 @end smallexample
24432 @noindent
24433 These warnings indicate that the rule has been violated, and that as a result
24434 elaboration checks may be missed in the resulting executable file.
24435 This warning may be suppressed using the @option{-ws} binder switch
24436 in the usual manner.
24438 One useful application of this mixing rule is in the case of a subsystem
24439 which does not itself @code{with} units from the remainder of the
24440 application. In this case, the entire subsystem can be compiled with
24441 dynamic checks to resolve a circularity in the subsystem, while
24442 allowing the main application that uses this subsystem to be compiled
24443 using the more reliable default static model.
24445 @node What to Do If the Default Elaboration Behavior Fails
24446 @section What to Do If the Default Elaboration Behavior Fails
24448 @noindent
24449 If the binder cannot find an acceptable order, it outputs detailed
24450 diagnostics. For example:
24451 @smallexample
24452 @group
24453 @iftex
24454 @leftskip=0cm
24455 @end iftex
24456 error: elaboration circularity detected
24457 info:   "proc (body)" must be elaborated before "pack (body)"
24458 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24459 info:     recompile "pack (body)" with -gnatel
24460 info:                             for full details
24461 info:       "proc (body)"
24462 info:         is needed by its spec:
24463 info:       "proc (spec)"
24464 info:         which is withed by:
24465 info:       "pack (body)"
24466 info:  "pack (body)" must be elaborated before "proc (body)"
24467 info:     reason: pragma Elaborate in unit "proc (body)"
24468 @end group
24470 @end smallexample
24472 @noindent
24473 In this case we have a cycle that the binder cannot break. On the one
24474 hand, there is an explicit pragma Elaborate in @code{proc} for
24475 @code{pack}. This means that the body of @code{pack} must be elaborated
24476 before the body of @code{proc}. On the other hand, there is elaboration
24477 code in @code{pack} that calls a subprogram in @code{proc}. This means
24478 that for maximum safety, there should really be a pragma
24479 Elaborate_All in @code{pack} for @code{proc} which would require that
24480 the body of @code{proc} be elaborated before the body of
24481 @code{pack}. Clearly both requirements cannot be satisfied.
24482 Faced with a circularity of this kind, you have three different options.
24484 @table @asis
24485 @item Fix the program
24486 The most desirable option from the point of view of long-term maintenance
24487 is to rearrange the program so that the elaboration problems are avoided.
24488 One useful technique is to place the elaboration code into separate
24489 child packages. Another is to move some of the initialization code to
24490 explicitly called subprograms, where the program controls the order
24491 of initialization explicitly. Although this is the most desirable option,
24492 it may be impractical and involve too much modification, especially in
24493 the case of complex legacy code.
24495 @item Perform dynamic checks
24496 If the compilations are done using the
24497 @option{-gnatE}
24498 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24499 manner. Dynamic checks are generated for all calls that could possibly result
24500 in raising an exception. With this switch, the compiler does not generate
24501 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24502 exactly as specified in the @cite{Ada Reference Manual}.
24503 The binder will generate
24504 an executable program that may or may not raise @code{Program_Error}, and then
24505 it is the programmer's job to ensure that it does not raise an exception. Note
24506 that it is important to compile all units with the switch, it cannot be used
24507 selectively.
24509 @item Suppress checks
24510 The drawback of dynamic checks is that they generate a
24511 significant overhead at run time, both in space and time. If you
24512 are absolutely sure that your program cannot raise any elaboration
24513 exceptions, and you still want to use the dynamic elaboration model,
24514 then you can use the configuration pragma
24515 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24516 example this pragma could be placed in the @file{gnat.adc} file.
24518 @item Suppress checks selectively
24519 When you know that certain calls or instantiations in elaboration code cannot
24520 possibly lead to an elaboration error, and the binder nevertheless complains
24521 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24522 elaboration circularities, it is possible to remove those warnings locally and
24523 obtain a program that will bind. Clearly this can be unsafe, and it is the
24524 responsibility of the programmer to make sure that the resulting program has no
24525 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24526 used with different granularity to suppress warnings and break elaboration
24527 circularities:
24529 @itemize @bullet
24530 @item
24531 Place the pragma that names the called subprogram in the declarative part
24532 that contains the call.
24534 @item
24535 Place the pragma in the declarative part, without naming an entity. This
24536 disables warnings on all calls in the corresponding  declarative region.
24538 @item
24539 Place the pragma in the package spec that declares the called subprogram,
24540 and name the subprogram. This disables warnings on all elaboration calls to
24541 that subprogram.
24543 @item
24544 Place the pragma in the package spec that declares the called subprogram,
24545 without naming any entity. This disables warnings on all elaboration calls to
24546 all subprograms declared in this spec.
24548 @item Use Pragma Elaborate
24549 As previously described in section @xref{Treatment of Pragma Elaborate},
24550 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24551 that no elaboration checks are required on calls to the designated unit.
24552 There may be cases in which the caller knows that no transitive calls
24553 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24554 case where @code{pragma Elaborate_All} would cause a circularity.
24555 @end itemize
24557 @noindent
24558 These five cases are listed in order of decreasing safety, and therefore
24559 require increasing programmer care in their application. Consider the
24560 following program:
24562 @smallexample @c adanocomment
24563 @b{package} Pack1 @b{is}
24564   @b{function} F1 @b{return} Integer;
24565   X1 : Integer;
24566 @b{end} Pack1;
24568 @b{package} Pack2 @b{is}
24569   @b{function} F2 @b{return} Integer;
24570   @b{function} Pure (x : integer) @b{return} integer;
24571   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24572   --  pragma Suppress (Elaboration_Check);              -- (4)
24573 @b{end} Pack2;
24575 @b{with} Pack2;
24576 @b{package} @b{body} Pack1 @b{is}
24577   @b{function} F1 @b{return} Integer @b{is}
24578   @b{begin}
24579     @b{return} 100;
24580   @b{end} F1;
24581   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24582 @b{begin}
24583   @b{declare}
24584     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24585     --  pragma Suppress(Elaboration_Check);             -- (2)
24586   @b{begin}
24587     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24588   @b{end};
24589 @b{end} Pack1;
24591 @b{with} Pack1;
24592 @b{package} @b{body} Pack2 @b{is}
24593   @b{function} F2 @b{return} Integer @b{is}
24594   @b{begin}
24595      @b{return} Pack1.F1;
24596   @b{end} F2;
24597   @b{function} Pure (x : integer) @b{return} integer @b{is}
24598   @b{begin}
24599      @b{return} x ** 3 - 3 * x;
24600   @b{end};
24601 @b{end} Pack2;
24603 @b{with} Pack1, Ada.Text_IO;
24604 @b{procedure} Proc3 @b{is}
24605 @b{begin}
24606   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24607 @b{end} Proc3;
24608 @end smallexample
24609 In the absence of any pragmas, an attempt to bind this program produces
24610 the following diagnostics:
24611 @smallexample
24612 @group
24613 @iftex
24614 @leftskip=.5cm
24615 @end iftex
24616 error: elaboration circularity detected
24617 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24618 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24619 info:       recompile "pack1 (body)" with -gnatel for full details
24620 info:          "pack1 (body)"
24621 info:             must be elaborated along with its spec:
24622 info:          "pack1 (spec)"
24623 info:             which is withed by:
24624 info:          "pack2 (body)"
24625 info:             which must be elaborated along with its spec:
24626 info:          "pack2 (spec)"
24627 info:             which is withed by:
24628 info:          "pack1 (body)"
24629 @end group
24630 @end smallexample
24631 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24632 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24633 F2 is safe, even though F2 calls F1, because the call appears after the
24634 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24635 remove the warning on the call. It is also possible to use pragma (2)
24636 because there are no other potentially unsafe calls in the block.
24638 @noindent
24639 The call to @code{Pure} is safe because this function does not depend on the
24640 state of @code{Pack2}. Therefore any call to this function is safe, and it
24641 is correct to place pragma (3) in the corresponding package spec.
24643 @noindent
24644 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24645 warnings on all calls to functions declared therein. Note that this is not
24646 necessarily safe, and requires more detailed examination of the subprogram
24647 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24648 be already elaborated.
24649 @end table
24651 @noindent
24652 It is hard to generalize on which of these four approaches should be
24653 taken. Obviously if it is possible to fix the program so that the default
24654 treatment works, this is preferable, but this may not always be practical.
24655 It is certainly simple enough to use
24656 @option{-gnatE}
24657 but the danger in this case is that, even if the GNAT binder
24658 finds a correct elaboration order, it may not always do so,
24659 and certainly a binder from another Ada compiler might not. A
24660 combination of testing and analysis (for which the
24661 information messages generated with the
24662 @option{-gnatel}
24663 switch can be useful) must be used to ensure that the program is free
24664 of errors. One switch that is useful in this testing is the
24665 @option{-p (pessimistic elaboration order)}
24666 switch for
24667 @code{gnatbind}.
24668 Normally the binder tries to find an order that has the best chance
24669 of avoiding elaboration problems. However, if this switch is used, the binder
24670 plays a devil's advocate role, and tries to choose the order that
24671 has the best chance of failing. If your program works even with this
24672 switch, then it has a better chance of being error free, but this is still
24673 not a guarantee.
24675 For an example of this approach in action, consider the C-tests (executable
24676 tests) from the ACVC suite. If these are compiled and run with the default
24677 treatment, then all but one of them succeed without generating any error
24678 diagnostics from the binder. However, there is one test that fails, and
24679 this is not surprising, because the whole point of this test is to ensure
24680 that the compiler can handle cases where it is impossible to determine
24681 a correct order statically, and it checks that an exception is indeed
24682 raised at run time.
24684 This one test must be compiled and run using the
24685 @option{-gnatE}
24686 switch, and then it passes. Alternatively, the entire suite can
24687 be run using this switch. It is never wrong to run with the dynamic
24688 elaboration switch if your code is correct, and we assume that the
24689 C-tests are indeed correct (it is less efficient, but efficiency is
24690 not a factor in running the ACVC tests.)
24692 @node Elaboration for Indirect Calls
24693 @section Elaboration for Indirect Calls
24694 @cindex Dispatching calls
24695 @cindex Indirect calls
24697 @noindent
24698 In rare cases, the static elaboration model fails to prevent
24699 dispatching calls to not-yet-elaborated subprograms. In such cases, we
24700 fall back to run-time checks; premature calls to any primitive
24701 operation of a tagged type before the body of the operation has been
24702 elaborated will raise @code{Program_Error}.
24704 Access-to-subprogram types, however, are handled conservatively, and
24705 do not require run-time checks. This was not true in earlier versions
24706 of the compiler; you can use the @option{-gnatd.U} debug switch to
24707 revert to the old behavior if the new conservative behavior causes
24708 elaboration cycles. Here, ``conservative'' means that if you do
24709 @code{P'Access} during elaboration, the compiler will assume that you
24710 might call @code{P} indirectly during elaboration, so it adds an
24711 implicit @code{pragma Elaborate_All} on the library unit containing
24712 @code{P}. The @option{-gnatd.U} switch is safe if you know there are
24713 no such calls. If the program worked before, it will continue to work
24714 with @option{-gnatd.U}. But beware that code modifications such as
24715 adding an indirect call can cause erroneous behavior in the presence
24716 of @option{-gnatd.U}.
24718 @node Summary of Procedures for Elaboration Control
24719 @section Summary of Procedures for Elaboration Control
24720 @cindex Elaboration control
24722 @noindent
24723 First, compile your program with the default options, using none of
24724 the special elaboration control switches. If the binder successfully
24725 binds your program, then you can be confident that, apart from issues
24726 raised by the use of access-to-subprogram types and dynamic dispatching,
24727 the program is free of elaboration errors. If it is important that the
24728 program be portable to other compilers than GNAT, then use the
24729 @option{-gnatel}
24730 switch to generate messages about missing @code{Elaborate} or
24731 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24733 If the program fails to bind using the default static elaboration
24734 handling, then you can fix the program to eliminate the binder
24735 message, or recompile the entire program with the
24736 @option{-gnatE} switch to generate dynamic elaboration checks,
24737 and, if you are sure there really are no elaboration problems,
24738 use a global pragma @code{Suppress (Elaboration_Check)}.
24740 @node Other Elaboration Order Considerations
24741 @section Other Elaboration Order Considerations
24742 @noindent
24743 This section has been entirely concerned with the issue of finding a valid
24744 elaboration order, as defined by the Ada Reference Manual. In a case
24745 where several elaboration orders are valid, the task is to find one
24746 of the possible valid elaboration orders (and the static model in GNAT
24747 will ensure that this is achieved).
24749 The purpose of the elaboration rules in the Ada Reference Manual is to
24750 make sure that no entity is accessed before it has been elaborated. For
24751 a subprogram, this means that the spec and body must have been elaborated
24752 before the subprogram is called. For an object, this means that the object
24753 must have been elaborated before its value is read or written. A violation
24754 of either of these two requirements is an access before elaboration order,
24755 and this section has been all about avoiding such errors.
24757 In the case where more than one order of elaboration is possible, in the
24758 sense that access before elaboration errors are avoided, then any one of
24759 the orders is ``correct'' in the sense that it meets the requirements of
24760 the Ada Reference Manual, and no such error occurs.
24762 However, it may be the case for a given program, that there are
24763 constraints on the order of elaboration that come not from consideration
24764 of avoiding elaboration errors, but rather from extra-lingual logic
24765 requirements. Consider this example:
24767 @smallexample @c ada
24768 @b{with} Init_Constants;
24769 @b{package} Constants @b{is}
24770    X : Integer := 0;
24771    Y : Integer := 0;
24772 @b{end} Constants;
24774 @b{package} Init_Constants @b{is}
24775    @b{procedure} P; --@i{ require a body}
24776 @b{end} Init_Constants;
24778 @b{with} Constants;
24779 @b{package} @b{body} Init_Constants @b{is}
24780    @b{procedure} P @b{is} @b{begin} @b{null}; @b{end};
24781 @b{begin}
24782    Constants.X := 3;
24783    Constants.Y := 4;
24784 @b{end} Init_Constants;
24786 @b{with} Constants;
24787 @b{package} Calc @b{is}
24788    Z : Integer := Constants.X + Constants.Y;
24789 @b{end} Calc;
24791 @b{with} Calc;
24792 @b{with} Text_IO; @b{use} Text_IO;
24793 @b{procedure} Main @b{is}
24794 @b{begin}
24795    Put_Line (Calc.Z'Img);
24796 @b{end} Main;
24797 @end smallexample
24799 @noindent
24800 In this example, there is more than one valid order of elaboration. For
24801 example both the following are correct orders:
24803 @smallexample
24804 Init_Constants spec
24805 Constants spec
24806 Calc spec
24807 Init_Constants body
24808 Main body
24810   and
24812 Init_Constants spec
24813 Init_Constants body
24814 Constants spec
24815 Calc spec
24816 Main body
24817 @end smallexample
24819 @noindent
24820 There is no language rule to prefer one or the other, both are correct
24821 from an order of elaboration point of view. But the programmatic effects
24822 of the two orders are very different. In the first, the elaboration routine
24823 of @code{Calc} initializes @code{Z} to zero, and then the main program
24824 runs with this value of zero. But in the second order, the elaboration
24825 routine of @code{Calc} runs after the body of Init_Constants has set
24826 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24827 runs.
24829 One could perhaps by applying pretty clever non-artificial intelligence
24830 to the situation guess that it is more likely that the second order of
24831 elaboration is the one desired, but there is no formal linguistic reason
24832 to prefer one over the other. In fact in this particular case, GNAT will
24833 prefer the second order, because of the rule that bodies are elaborated
24834 as soon as possible, but it's just luck that this is what was wanted
24835 (if indeed the second order was preferred).
24837 If the program cares about the order of elaboration routines in a case like
24838 this, it is important to specify the order required. In this particular
24839 case, that could have been achieved by adding to the spec of Calc:
24841 @smallexample @c ada
24842 @b{pragma} Elaborate_All (Constants);
24843 @end smallexample
24845 @noindent
24846 which requires that the body (if any) and spec of @code{Constants},
24847 as well as the body and spec of any unit @code{with}'ed by
24848 @code{Constants} be elaborated before @code{Calc} is elaborated.
24850 Clearly no automatic method can always guess which alternative you require,
24851 and if you are working with legacy code that had constraints of this kind
24852 which were not properly specified by adding @code{Elaborate} or
24853 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24854 compilers can choose different orders.
24856 However, GNAT does attempt to diagnose the common situation where there
24857 are uninitialized variables in the visible part of a package spec, and the
24858 corresponding package body has an elaboration block that directly or
24859 indirectly initialized one or more of these variables. This is the situation
24860 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24861 a warning that suggests this addition if it detects this situation.
24863 The @code{gnatbind}
24864 @option{-p} switch may be useful in smoking
24865 out problems. This switch causes bodies to be elaborated as late as possible
24866 instead of as early as possible. In the example above, it would have forced
24867 the choice of the first elaboration order. If you get different results
24868 when using this switch, and particularly if one set of results is right,
24869 and one is wrong as far as you are concerned, it shows that you have some
24870 missing @code{Elaborate} pragmas. For the example above, we have the
24871 following output:
24873 @smallexample
24874 gnatmake -f -q main
24875 main
24877 gnatmake -f -q main -bargs -p
24878 main
24880 @end smallexample
24882 @noindent
24883 It is of course quite unlikely that both these results are correct, so
24884 it is up to you in a case like this to investigate the source of the
24885 difference, by looking at the two elaboration orders that are chosen,
24886 and figuring out which is correct, and then adding the necessary
24887 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24889 @node Determining the Chosen Elaboration Order
24890 @section Determining the Chosen Elaboration Order
24891 @noindent
24893 To see the elaboration order that the binder chooses, you can look at
24894 the last part of the b~xxx.adb binder output file. Here is an example:
24896 @smallexample @c ada
24897 System.Soft_Links'Elab_Body;
24898 E14 := True;
24899 System.Secondary_Stack'Elab_Body;
24900 E18 := True;
24901 System.Exception_Table'Elab_Body;
24902 E24 := True;
24903 Ada.Io_Exceptions'Elab_Spec;
24904 E67 := True;
24905 Ada.Tags'Elab_Spec;
24906 Ada.Streams'Elab_Spec;
24907 E43 := True;
24908 Interfaces.C'Elab_Spec;
24909 E69 := True;
24910 System.Finalization_Root'Elab_Spec;
24911 E60 := True;
24912 System.Os_Lib'Elab_Body;
24913 E71 := True;
24914 System.Finalization_Implementation'Elab_Spec;
24915 System.Finalization_Implementation'Elab_Body;
24916 E62 := True;
24917 Ada.Finalization'Elab_Spec;
24918 E58 := True;
24919 Ada.Finalization.List_Controller'Elab_Spec;
24920 E76 := True;
24921 System.File_Control_Block'Elab_Spec;
24922 E74 := True;
24923 System.File_Io'Elab_Body;
24924 E56 := True;
24925 Ada.Tags'Elab_Body;
24926 E45 := True;
24927 Ada.Text_Io'Elab_Spec;
24928 Ada.Text_Io'Elab_Body;
24929 E07 := True;
24930 @end smallexample
24932 @noindent
24933 Here Elab_Spec elaborates the spec
24934 and Elab_Body elaborates the body. The assignments to the Exx flags
24935 flag that the corresponding body is now elaborated.
24937 You can also ask the binder to generate a more
24938 readable list of the elaboration order using the
24939 @code{-l} switch when invoking the binder. Here is
24940 an example of the output generated by this switch:
24942 @smallexample
24943 ada (spec)
24944 interfaces (spec)
24945 system (spec)
24946 system.case_util (spec)
24947 system.case_util (body)
24948 system.concat_2 (spec)
24949 system.concat_2 (body)
24950 system.concat_3 (spec)
24951 system.concat_3 (body)
24952 system.htable (spec)
24953 system.parameters (spec)
24954 system.parameters (body)
24955 system.crtl (spec)
24956 interfaces.c_streams (spec)
24957 interfaces.c_streams (body)
24958 system.restrictions (spec)
24959 system.restrictions (body)
24960 system.standard_library (spec)
24961 system.exceptions (spec)
24962 system.exceptions (body)
24963 system.storage_elements (spec)
24964 system.storage_elements (body)
24965 system.secondary_stack (spec)
24966 system.stack_checking (spec)
24967 system.stack_checking (body)
24968 system.string_hash (spec)
24969 system.string_hash (body)
24970 system.htable (body)
24971 system.strings (spec)
24972 system.strings (body)
24973 system.traceback (spec)
24974 system.traceback (body)
24975 system.traceback_entries (spec)
24976 system.traceback_entries (body)
24977 ada.exceptions (spec)
24978 ada.exceptions.last_chance_handler (spec)
24979 system.soft_links (spec)
24980 system.soft_links (body)
24981 ada.exceptions.last_chance_handler (body)
24982 system.secondary_stack (body)
24983 system.exception_table (spec)
24984 system.exception_table (body)
24985 ada.io_exceptions (spec)
24986 ada.tags (spec)
24987 ada.streams (spec)
24988 interfaces.c (spec)
24989 interfaces.c (body)
24990 system.finalization_root (spec)
24991 system.finalization_root (body)
24992 system.memory (spec)
24993 system.memory (body)
24994 system.standard_library (body)
24995 system.os_lib (spec)
24996 system.os_lib (body)
24997 system.unsigned_types (spec)
24998 system.stream_attributes (spec)
24999 system.stream_attributes (body)
25000 system.finalization_implementation (spec)
25001 system.finalization_implementation (body)
25002 ada.finalization (spec)
25003 ada.finalization (body)
25004 ada.finalization.list_controller (spec)
25005 ada.finalization.list_controller (body)
25006 system.file_control_block (spec)
25007 system.file_io (spec)
25008 system.file_io (body)
25009 system.val_uns (spec)
25010 system.val_util (spec)
25011 system.val_util (body)
25012 system.val_uns (body)
25013 system.wch_con (spec)
25014 system.wch_con (body)
25015 system.wch_cnv (spec)
25016 system.wch_jis (spec)
25017 system.wch_jis (body)
25018 system.wch_cnv (body)
25019 system.wch_stw (spec)
25020 system.wch_stw (body)
25021 ada.tags (body)
25022 ada.exceptions (body)
25023 ada.text_io (spec)
25024 ada.text_io (body)
25025 text_io (spec)
25026 gdbstr (body)
25027 @end smallexample
25029 @c **********************************
25030 @node Overflow Check Handling in GNAT
25031 @appendix Overflow Check Handling in GNAT
25032 @cindex Overflow checks
25033 @cindex Checks (overflow)
25034 @c **********************************
25036 @menu
25037 * Background::
25038 * Overflow Checking Modes in GNAT::
25039 * Specifying the Desired Mode::
25040 * Default Settings::
25041 * Implementation Notes::
25042 @end menu
25045 @node Background
25046 @section Background
25048 @noindent
25049 Overflow checks are checks that the compiler may make to ensure
25050 that intermediate results are not out of range. For example:
25052 @smallexample @c ada
25053    A : Integer;
25054    ...
25055    A := A + 1;
25056 @end smallexample
25058 @noindent
25059 if @code{A} has the value @code{Integer'Last}, then the addition may cause
25060 overflow since the result is out of range of the type @code{Integer}.
25061 In this case @code{Constraint_Error} will be raised if checks are
25062 enabled.
25064 A trickier situation arises in examples like the following:
25066 @smallexample @c ada
25067   A, C : Integer;
25068   ...
25069   A := (A + 1) + C;
25070 @end smallexample
25072 @noindent
25073 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
25074 Now the final result of the expression on the right hand side is
25075 @code{Integer'Last} which is in range, but the question arises whether the
25076 intermediate addition of @code{(A + 1)} raises an overflow error.
25078 The (perhaps surprising) answer is that the Ada language
25079 definition does not answer this question. Instead it leaves
25080 it up to the implementation to do one of two things if overflow
25081 checks are enabled.
25083 @itemize @bullet
25084 @item
25085 raise an exception (@code{Constraint_Error}), or
25087 @item
25088 yield the correct mathematical result which is then used in
25089 subsequent operations.
25090 @end itemize
25092 @noindent
25093 If the compiler chooses the first approach, then the assignment of this
25094 example will indeed raise @code{Constraint_Error} if overflow checking is
25095 enabled, or result in erroneous execution if overflow checks are suppressed.
25097 But if the compiler
25098 chooses the second approach, then it can perform both additions yielding
25099 the correct mathematical result, which is in range, so no exception
25100 will be raised, and the right result is obtained, regardless of whether
25101 overflow checks are suppressed.
25103 Note that in the first example an
25104 exception will be raised in either case, since if the compiler
25105 gives the correct mathematical result for the addition, it will
25106 be out of range of the target type of the assignment, and thus
25107 fails the range check.
25109 This lack of specified behavior in the handling of overflow for
25110 intermediate results is a source of non-portability, and can thus
25111 be problematic when programs are ported. Most typically this arises
25112 in a situation where the original compiler did not raise an exception,
25113 and then the application is moved to a compiler where the check is
25114 performed on the intermediate result and an unexpected exception is
25115 raised.
25117 Furthermore, when using Ada 2012's preconditions and other
25118 assertion forms, another issue arises. Consider:
25120 @smallexample @c ada
25121      @b{procedure} P (A, B : Integer) @b{with}
25122        Pre => A + B <= Integer'Last;
25123 @end smallexample
25125 @noindent
25126 One often wants to regard arithmetic in a context like this from
25127 a mathematical point of view. So for example, if the two actual parameters
25128 for a call to @code{P} are both @code{Integer'Last}, then
25129 the precondition should be regarded as False. If we are executing
25130 in a mode with run-time checks enabled for preconditions, then we would
25131 like this precondition to fail, rather than raising an exception
25132 because of the intermediate overflow.
25134 However, the language definition leaves the specification of
25135 whether the above condition fails (raising @code{Assert_Error}) or
25136 causes an intermediate overflow (raising @code{Constraint_Error})
25137 up to the implementation.
25139 The situation is worse in a case such as the following:
25141 @smallexample @c ada
25142      @b{procedure} Q (A, B, C : Integer) @b{with}
25143        Pre => A + B + C <= Integer'Last;
25144 @end smallexample
25146 @noindent
25147 Consider the call
25149 @smallexample @c ada
25150      Q (A => Integer'Last, B => 1, C => -1);
25151 @end smallexample
25153 @noindent
25154 From a mathematical point of view the precondition
25155 is True, but at run time we may (but are not guaranteed to) get an
25156 exception raised because of the intermediate overflow (and we really
25157 would prefer this precondition to be considered True at run time).
25159 @node Overflow Checking Modes in GNAT
25160 @section Overflow Checking Modes in GNAT
25162 @noindent
25163 To deal with the portability issue, and with the problem of
25164 mathematical versus run-time interpretation of the expressions in
25165 assertions, GNAT provides comprehensive control over the handling
25166 of intermediate overflow. GNAT can operate in three modes, and
25167 furthemore, permits separate selection of operating modes for
25168 the expressions within assertions (here the term ``assertions''
25169 is used in the technical sense, which includes preconditions and so forth)
25170 and for expressions appearing outside assertions.
25172 The three modes are:
25174 @itemize @bullet
25175 @item   @i{Use base type for intermediate operations} (@code{STRICT})
25177      In this mode, all intermediate results for predefined arithmetic
25178      operators are computed using the base type, and the result must
25179      be in range of the base type. If this is not the
25180      case then either an exception is raised (if overflow checks are
25181      enabled) or the execution is erroneous (if overflow checks are suppressed).
25182      This is the normal default mode.
25184 @item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
25186      In this mode, the compiler attempts to avoid intermediate overflows by
25187      using a larger integer type, typically @code{Long_Long_Integer},
25188      as the type in which arithmetic is
25189      performed for predefined arithmetic operators. This may be slightly more
25190      expensive at
25191      run time (compared to suppressing intermediate overflow checks), though
25192      the cost is negligible on modern 64-bit machines. For the examples given
25193      earlier, no intermediate overflows would have resulted in exceptions,
25194      since the intermediate results are all in the range of
25195      @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
25196      of GNAT). In addition, if checks are enabled, this reduces the number of
25197      checks that must be made, so this choice may actually result in an
25198      improvement in space and time behavior.
25200      However, there are cases where @code{Long_Long_Integer} is not large
25201      enough, consider the following example:
25203 @smallexample @c ada
25204        @b{procedure} R (A, B, C, D : Integer) @b{with}
25205          Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
25206 @end smallexample
25208      where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
25209      Now the intermediate results are
25210      out of the range of @code{Long_Long_Integer} even though the final result
25211      is in range and the precondition is True (from a mathematical point
25212      of view). In such a case, operating in this mode, an overflow occurs
25213      for the intermediate computation (which is why this mode
25214      says @i{most} intermediate overflows are avoided). In this case,
25215      an exception is raised if overflow checks are enabled, and the
25216      execution is erroneous if overflow checks are suppressed.
25218 @item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
25220      In this mode, the compiler  avoids all intermediate overflows
25221      by using arbitrary precision arithmetic as required. In this
25222      mode, the above example with @code{A**2 * B**2} would
25223      not cause intermediate overflow, because the intermediate result
25224      would be evaluated using sufficient precision, and the result
25225      of evaluating the precondition would be True.
25227      This mode has the advantage of avoiding any intermediate
25228      overflows, but at the expense of significant run-time overhead,
25229      including the use of a library (included automatically in this
25230      mode) for multiple-precision arithmetic.
25232      This mode provides cleaner semantics for assertions, since now
25233      the run-time behavior emulates true arithmetic behavior for the
25234      predefined arithmetic operators, meaning that there is never a
25235      conflict between the mathematical view of the assertion, and its
25236      run-time behavior.
25238      Note that in this mode, the behavior is unaffected by whether or
25239      not overflow checks are suppressed, since overflow does not occur.
25240      It is possible for gigantic intermediate expressions to raise
25241      @code{Storage_Error} as a result of attempting to compute the
25242      results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
25243      but overflow is impossible.
25246 @end itemize
25248 @noindent
25249   Note that these modes apply only to the evaluation of predefined
25250   arithmetic, membership, and comparison operators for signed integer
25251   aritmetic.
25253   For fixed-point arithmetic, checks can be suppressed. But if checks
25254   are enabled
25255   then fixed-point values are always checked for overflow against the
25256   base type for intermediate expressions (that is such checks always
25257   operate in the equivalent of @code{STRICT} mode).
25259   For floating-point, on nearly all architectures, @code{Machine_Overflows}
25260   is False, and IEEE infinities are generated, so overflow exceptions
25261   are never raised. If you want to avoid infinities, and check that
25262   final results of expressions are in range, then you can declare a
25263   constrained floating-point type, and range checks will be carried
25264   out in the normal manner (with infinite values always failing all
25265   range checks).
25268 @c -------------------------
25269 @node Specifying the Desired Mode
25270 @section Specifying the Desired Mode
25272 @noindent
25273 The desired mode of for handling intermediate overflow can be specified using
25274 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
25275 The pragma has the form
25276 @cindex pragma @code{Overflow_Mode}
25278 @smallexample @c ada
25279     @b{pragma} Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
25280 @end smallexample
25282 @noindent
25283 where @code{MODE} is one of
25285 @itemize @bullet
25286 @item   @code{STRICT}:  intermediate overflows checked (using base type)
25287 @item   @code{MINIMIZED}: minimize intermediate overflows
25288 @item   @code{ELIMINATED}: eliminate intermediate overflows
25289 @end itemize
25291 @noindent
25292 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
25293 @code{minimized} all have the same effect.
25295 If only the @code{General} parameter is present, then the given @code{MODE}
25296 applies
25297 to expressions both within and outside assertions. If both arguments
25298 are present, then @code{General} applies to expressions outside assertions,
25299 and @code{Assertions} applies to expressions within assertions. For example:
25301 @smallexample @c ada
25302    @b{pragma} Overflow_Mode
25303      (General => Minimized, Assertions => Eliminated);
25304 @end smallexample
25306 @noindent
25307 specifies that general expressions outside assertions be evaluated
25308 in ``minimize intermediate overflows'' mode, and expressions within
25309 assertions be evaluated in ``eliminate intermediate overflows'' mode.
25310 This is often a reasonable choice, avoiding excessive overhead
25311 outside assertions, but assuring a high degree of portability
25312 when importing code from another compiler, while incurring
25313 the extra overhead for assertion expressions to ensure that
25314 the behavior at run time matches the expected mathematical
25315 behavior.
25317 The @code{Overflow_Mode} pragma has the same scoping and placement
25318 rules as pragma @code{Suppress}, so it can occur either as a
25319 configuration pragma, specifying a default for the whole
25320 program, or in a declarative scope, where it applies to the
25321 remaining declarations and statements in that scope.
25323 Note that pragma @code{Overflow_Mode} does not affect whether
25324 overflow checks are enabled or suppressed. It only controls the
25325 method used to compute intermediate values. To control whether
25326 overflow checking is enabled or suppressed, use pragma @code{Suppress}
25327 or @code{Unsuppress} in the usual manner
25329 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
25330 can be used to control the checking mode default (which can be subsequently
25331 overridden using pragmas).
25332 @cindex @option{-gnato?} (gcc)
25333 @cindex @option{-gnato??} (gcc)
25335 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
25337 @itemize @bullet
25338 @item   @code{1}:
25339 use base type for intermediate operations (@code{STRICT})
25340 @item   @code{2}:
25341 minimize intermediate overflows (@code{MINIMIZED})
25342 @item   @code{3}:
25343 eliminate intermediate overflows (@code{ELIMINATED})
25344 @end itemize
25346 @noindent
25347 As with the pragma, if only one digit appears then it applies to all
25348 cases; if two digits are given, then the first applies outside
25349 assertions, and the second within assertions. Thus the equivalent
25350 of the example pragma above would be
25351 @option{-gnato23}.
25353 If no digits follow the @option{-gnato}, then it is equivalent to
25354 @option{-gnato11},
25355 causing all intermediate operations to be computed using the base
25356 type (@code{STRICT} mode).
25358 In addition to setting the mode used for computation of intermediate
25359 results, the @code{-gnato} switch also enables overflow checking (which
25360 is suppressed by default). It thus combines the effect of using
25361 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
25364 @c -------------------------
25365 @node Default Settings
25366 @section Default Settings
25368 The default mode for overflow checks is
25370 @smallexample
25371    General => Strict
25372 @end smallexample
25374 @noindent
25375 which causes all computations both inside and outside assertions to use
25376 the base type. In addition overflow checks are suppressed.
25378 This retains compatibility with previous versions of
25379 GNAT which suppressed overflow checks by default and always
25380 used the base type for computation of intermediate results.
25382 The switch @option{-gnato} (with no digits following) is equivalent to
25383 @cindex @option{-gnato} (gcc)
25385 @smallexample
25386    General => Strict
25387 @end smallexample
25389 @noindent
25390 which causes overflow checking of all intermediate overflows
25391 both inside and outside assertions against the base type.
25392 This provides compatibility
25393 with this switch as implemented in previous versions of GNAT.
25395 The pragma @code{Suppress (Overflow_Check)} disables overflow
25396 checking, but it has no effect on the method used for computing
25397 intermediate results.
25399 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
25400 checking, but it has no effect on the method used for computing
25401 intermediate results.
25403 @c -------------------------
25404 @node Implementation Notes
25405 @section Implementation Notes
25407 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
25408 reasonably efficient, and can be generally used. It also helps
25409 to ensure compatibility with code imported from some other
25410 compiler to GNAT.
25412 Setting all intermediate overflows checking (@code{CHECKED} mode)
25413 makes sense if you want to
25414 make sure that your code is compatible with any other possible
25415 Ada implementation. This may be useful in ensuring portability
25416 for code that is to be exported to some other compiler than GNAT.
25419 The Ada standard allows the reassociation of expressions at
25420 the same precedence level if no parentheses are present. For
25421 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
25422 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
25423 introducing or eliminating an overflow exception. The GNAT
25424 compiler never takes advantage of this freedom, and the
25425 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
25426 If you need the other order, you can write the parentheses
25427 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
25429 The use of @code{ELIMINATED} mode will cause the compiler to
25430 automatically include an appropriate arbitrary precision
25431 integer arithmetic package. The compiler will make calls
25432 to this package, though only in cases where it cannot be
25433 sure that @code{Long_Long_Integer} is sufficient to guard against
25434 intermediate overflows. This package does not use dynamic
25435 alllocation, but it does use the secondary stack, so an
25436 appropriate secondary stack package must be present (this
25437 is always true for standard full Ada, but may require
25438 specific steps for restricted run times such as ZFP).
25440 Although @code{ELIMINATED} mode causes expressions to use arbitrary
25441 precision arithmetic, avoiding overflow, the final result
25442 must be in an appropriate range. This is true even if the
25443 final result is of type @code{[Long_[Long_]]Integer'Base}, which
25444 still has the same bounds as its associated constrained
25445 type at run-time.
25447 Currently, the @code{ELIMINATED} mode is only available on target
25448 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
25449 platforms).
25451 @c *******************************
25452 @node Conditional Compilation
25453 @appendix Conditional Compilation
25454 @c *******************************
25455 @cindex Conditional compilation
25457 @noindent
25458 It is often necessary to arrange for a single source program
25459 to serve multiple purposes, where it is compiled in different
25460 ways to achieve these different goals. Some examples of the
25461 need for this feature are
25463 @itemize @bullet
25464 @item  Adapting a program to a different hardware environment
25465 @item  Adapting a program to a different target architecture
25466 @item  Turning debugging features on and off
25467 @item  Arranging for a program to compile with different compilers
25468 @end itemize
25470 @noindent
25471 In C, or C++, the typical approach would be to use the preprocessor
25472 that is defined as part of the language. The Ada language does not
25473 contain such a feature. This is not an oversight, but rather a very
25474 deliberate design decision, based on the experience that overuse of
25475 the preprocessing features in C and C++ can result in programs that
25476 are extremely difficult to maintain. For example, if we have ten
25477 switches that can be on or off, this means that there are a thousand
25478 separate programs, any one of which might not even be syntactically
25479 correct, and even if syntactically correct, the resulting program
25480 might not work correctly. Testing all combinations can quickly become
25481 impossible.
25483 Nevertheless, the need to tailor programs certainly exists, and in
25484 this Appendix we will discuss how this can
25485 be achieved using Ada in general, and GNAT in particular.
25487 @menu
25488 * Use of Boolean Constants::
25489 * Debugging - A Special Case::
25490 * Conditionalizing Declarations::
25491 * Use of Alternative Implementations::
25492 * Preprocessing::
25493 @end menu
25495 @node Use of Boolean Constants
25496 @section Use of Boolean Constants
25498 @noindent
25499 In the case where the difference is simply which code
25500 sequence is executed, the cleanest solution is to use Boolean
25501 constants to control which code is executed.
25503 @smallexample @c ada
25504 @group
25505 FP_Initialize_Required : @b{constant} Boolean := True;
25506 @dots{}
25507 @b{if} FP_Initialize_Required @b{then}
25508 @dots{}
25509 @b{end} @b{if};
25510 @end group
25511 @end smallexample
25513 @noindent
25514 Not only will the code inside the @code{if} statement not be executed if
25515 the constant Boolean is @code{False}, but it will also be completely
25516 deleted from the program.
25517 However, the code is only deleted after the @code{if} statement
25518 has been checked for syntactic and semantic correctness.
25519 (In contrast, with preprocessors the code is deleted before the
25520 compiler ever gets to see it, so it is not checked until the switch
25521 is turned on.)
25522 @cindex Preprocessors (contrasted with conditional compilation)
25524 Typically the Boolean constants will be in a separate package,
25525 something like:
25527 @smallexample @c ada
25528 @group
25529 @b{package} Config @b{is}
25530    FP_Initialize_Required : @b{constant} Boolean := True;
25531    Reset_Available        : @b{constant} Boolean := False;
25532    @dots{}
25533 @b{end} Config;
25534 @end group
25535 @end smallexample
25537 @noindent
25538 The @code{Config} package exists in multiple forms for the various targets,
25539 with an appropriate script selecting the version of @code{Config} needed.
25540 Then any other unit requiring conditional compilation can do a @code{with}
25541 of @code{Config} to make the constants visible.
25544 @node Debugging - A Special Case
25545 @section Debugging - A Special Case
25547 @noindent
25548 A common use of conditional code is to execute statements (for example
25549 dynamic checks, or output of intermediate results) under control of a
25550 debug switch, so that the debugging behavior can be turned on and off.
25551 This can be done using a Boolean constant to control whether the code
25552 is active:
25554 @smallexample @c ada
25555 @group
25556 @b{if} Debugging @b{then}
25557    Put_Line ("got to the first stage!");
25558 @b{end} @b{if};
25559 @end group
25560 @end smallexample
25562 @noindent
25565 @smallexample @c ada
25566 @group
25567 @b{if} Debugging @b{and} @b{then} Temperature > 999.0 @b{then}
25568    @b{raise} Temperature_Crazy;
25569 @b{end} @b{if};
25570 @end group
25571 @end smallexample
25573 @noindent
25574 Since this is a common case, there are special features to deal with
25575 this in a convenient manner. For the case of tests, Ada 2005 has added
25576 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25577 @cindex pragma @code{Assert}
25578 on the @code{Assert} pragma that has always been available in GNAT, so this
25579 feature may be used with GNAT even if you are not using Ada 2005 features.
25580 The use of pragma @code{Assert} is described in
25581 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25582 example, the last test could be written:
25584 @smallexample @c ada
25585 @b{pragma} Assert (Temperature <= 999.0, "Temperature Crazy");
25586 @end smallexample
25588 @noindent
25589 or simply
25591 @smallexample @c ada
25592 @b{pragma} Assert (Temperature <= 999.0);
25593 @end smallexample
25595 @noindent
25596 In both cases, if assertions are active and the temperature is excessive,
25597 the exception @code{Assert_Failure} will be raised, with the given string in
25598 the first case or a string indicating the location of the pragma in the second
25599 case used as the exception message.
25601 You can turn assertions on and off by using the @code{Assertion_Policy}
25602 pragma.
25603 @cindex pragma @code{Assertion_Policy}
25604 This is an Ada 2005 pragma which is implemented in all modes by
25605 GNAT, but only in the latest versions of GNAT which include Ada 2005
25606 capability. Alternatively, you can use the @option{-gnata} switch
25607 @cindex @option{-gnata} switch
25608 to enable assertions from the command line (this is recognized by all versions
25609 of GNAT).
25611 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25612 @code{Debug} can be used:
25613 @cindex pragma @code{Debug}
25615 @smallexample @c ada
25616 @b{pragma} Debug (Put_Line ("got to the first stage!"));
25617 @end smallexample
25619 @noindent
25620 If debug pragmas are enabled, the argument, which must be of the form of
25621 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25622 Only one call can be present, but of course a special debugging procedure
25623 containing any code you like can be included in the program and then
25624 called in a pragma @code{Debug} argument as needed.
25626 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25627 construct is that pragma @code{Debug} can appear in declarative contexts,
25628 such as at the very beginning of a procedure, before local declarations have
25629 been elaborated.
25631 Debug pragmas are enabled using either the @option{-gnata} switch that also
25632 controls assertions, or with a separate Debug_Policy pragma.
25633 @cindex pragma @code{Debug_Policy}
25634 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25635 in Ada 95 and Ada 83 programs as well), and is analogous to
25636 pragma @code{Assertion_Policy} to control assertions.
25638 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25639 and thus they can appear in @file{gnat.adc} if you are not using a
25640 project file, or in the file designated to contain configuration pragmas
25641 in a project file.
25642 They then apply to all subsequent compilations. In practice the use of
25643 the @option{-gnata} switch is often the most convenient method of controlling
25644 the status of these pragmas.
25646 Note that a pragma is not a statement, so in contexts where a statement
25647 sequence is required, you can't just write a pragma on its own. You have
25648 to add a @code{null} statement.
25650 @smallexample @c ada
25651 @group
25652 @b{if} @dots{} @b{then}
25653    @dots{} -- some statements
25654 @b{else}
25655    @b{pragma} Assert (Num_Cases < 10);
25656    @b{null};
25657 @b{end} @b{if};
25658 @end group
25659 @end smallexample
25662 @node Conditionalizing Declarations
25663 @section Conditionalizing Declarations
25665 @noindent
25666 In some cases, it may be necessary to conditionalize declarations to meet
25667 different requirements. For example we might want a bit string whose length
25668 is set to meet some hardware message requirement.
25670 In some cases, it may be possible to do this using declare blocks controlled
25671 by conditional constants:
25673 @smallexample @c ada
25674 @group
25675 @b{if} Small_Machine @b{then}
25676    @b{declare}
25677       X : Bit_String (1 .. 10);
25678    @b{begin}
25679       @dots{}
25680    @b{end};
25681 @b{else}
25682    @b{declare}
25683       X : Large_Bit_String (1 .. 1000);
25684    @b{begin}
25685       @dots{}
25686    @b{end};
25687 @b{end} @b{if};
25688 @end group
25689 @end smallexample
25691 @noindent
25692 Note that in this approach, both declarations are analyzed by the
25693 compiler so this can only be used where both declarations are legal,
25694 even though one of them will not be used.
25696 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25697 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25698 that are parameterized by these constants. For example
25700 @smallexample @c ada
25701 @group
25702 @b{for} Rec @b{use}
25703   Field1 @b{at} 0 @b{range} Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25704 @b{end} @b{record};
25705 @end group
25706 @end smallexample
25708 @noindent
25709 If @code{Bits_Per_Word} is set to 32, this generates either
25711 @smallexample @c ada
25712 @group
25713 @b{for} Rec @b{use}
25714   Field1 @b{at} 0 @b{range} 0 .. 32;
25715 @b{end} @b{record};
25716 @end group
25717 @end smallexample
25719 @noindent
25720 for the big endian case, or
25722 @smallexample @c ada
25723 @group
25724 @b{for} Rec @b{use} @b{record}
25725   Field1 @b{at} 0 @b{range} 10 .. 32;
25726 @b{end} @b{record};
25727 @end group
25728 @end smallexample
25730 @noindent
25731 for the little endian case. Since a powerful subset of Ada expression
25732 notation is usable for creating static constants, clever use of this
25733 feature can often solve quite difficult problems in conditionalizing
25734 compilation (note incidentally that in Ada 95, the little endian
25735 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25736 need to define this one yourself).
25739 @node Use of Alternative Implementations
25740 @section Use of Alternative Implementations
25742 @noindent
25743 In some cases, none of the approaches described above are adequate. This
25744 can occur for example if the set of declarations required is radically
25745 different for two different configurations.
25747 In this situation, the official Ada way of dealing with conditionalizing
25748 such code is to write separate units for the different cases. As long as
25749 this does not result in excessive duplication of code, this can be done
25750 without creating maintenance problems. The approach is to share common
25751 code as far as possible, and then isolate the code and declarations
25752 that are different. Subunits are often a convenient method for breaking
25753 out a piece of a unit that is to be conditionalized, with separate files
25754 for different versions of the subunit for different targets, where the
25755 build script selects the right one to give to the compiler.
25756 @cindex Subunits (and conditional compilation)
25758 As an example, consider a situation where a new feature in Ada 2005
25759 allows something to be done in a really nice way. But your code must be able
25760 to compile with an Ada 95 compiler. Conceptually you want to say:
25762 @smallexample @c ada
25763 @group
25764 @b{if} Ada_2005 @b{then}
25765    @dots{} neat Ada 2005 code
25766 @b{else}
25767    @dots{} not quite as neat Ada 95 code
25768 @b{end} @b{if};
25769 @end group
25770 @end smallexample
25772 @noindent
25773 where @code{Ada_2005} is a Boolean constant.
25775 But this won't work when @code{Ada_2005} is set to @code{False},
25776 since the @code{then} clause will be illegal for an Ada 95 compiler.
25777 (Recall that although such unreachable code would eventually be deleted
25778 by the compiler, it still needs to be legal.  If it uses features
25779 introduced in Ada 2005, it will be illegal in Ada 95.)
25781 So instead we write
25783 @smallexample @c ada
25784 @b{procedure} Insert @b{is} @b{separate};
25785 @end smallexample
25787 @noindent
25788 Then we have two files for the subunit @code{Insert}, with the two sets of
25789 code.
25790 If the package containing this is called @code{File_Queries}, then we might
25791 have two files
25793 @itemize @bullet
25794 @item    @file{file_queries-insert-2005.adb}
25795 @item    @file{file_queries-insert-95.adb}
25796 @end itemize
25798 @noindent
25799 and the build script renames the appropriate file to
25801 @smallexample
25802 file_queries-insert.adb
25803 @end smallexample
25805 @noindent
25806 and then carries out the compilation.
25808 This can also be done with project files' naming schemes. For example:
25810 @smallexample @c project
25811 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25812 @end smallexample
25814 @noindent
25815 Note also that with project files it is desirable to use a different extension
25816 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25817 conflict may arise through another commonly used feature: to declare as part
25818 of the project a set of directories containing all the sources obeying the
25819 default naming scheme.
25821 The use of alternative units is certainly feasible in all situations,
25822 and for example the Ada part of the GNAT run-time is conditionalized
25823 based on the target architecture using this approach. As a specific example,
25824 consider the implementation of the AST feature in VMS. There is one
25825 spec:
25827 @smallexample
25828 s-asthan.ads
25829 @end smallexample
25831 @noindent
25832 which is the same for all architectures, and three bodies:
25834 @table @file
25835 @item    s-asthan.adb
25836 used for all non-VMS operating systems
25837 @item    s-asthan-vms-alpha.adb
25838 used for VMS on the Alpha
25839 @item    s-asthan-vms-ia64.adb
25840 used for VMS on the ia64
25841 @end table
25843 @noindent
25844 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25845 this operating system feature is not available, and the two remaining
25846 versions interface with the corresponding versions of VMS to provide
25847 VMS-compatible AST handling. The GNAT build script knows the architecture
25848 and operating system, and automatically selects the right version,
25849 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25851 Another style for arranging alternative implementations is through Ada's
25852 access-to-subprogram facility.
25853 In case some functionality is to be conditionally included,
25854 you can declare an access-to-procedure variable @code{Ref} that is initialized
25855 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25856 when appropriate.
25857 In some library package, set @code{Ref} to @code{Proc'Access} for some
25858 procedure @code{Proc} that performs the relevant processing.
25859 The initialization only occurs if the library package is included in the
25860 program.
25861 The same idea can also be implemented using tagged types and dispatching
25862 calls.
25865 @node Preprocessing
25866 @section Preprocessing
25867 @cindex Preprocessing
25869 @noindent
25870 Although it is quite possible to conditionalize code without the use of
25871 C-style preprocessing, as described earlier in this section, it is
25872 nevertheless convenient in some cases to use the C approach. Moreover,
25873 older Ada compilers have often provided some preprocessing capability,
25874 so legacy code may depend on this approach, even though it is not
25875 standard.
25877 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25878 extent on the various preprocessors that have been used
25879 with legacy code on other compilers, to enable easier transition).
25881 The preprocessor may be used in two separate modes. It can be used quite
25882 separately from the compiler, to generate a separate output source file
25883 that is then fed to the compiler as a separate step. This is the
25884 @code{gnatprep} utility, whose use is fully described in
25885 @ref{Preprocessing with gnatprep}.
25886 @cindex @code{gnatprep}
25888 The preprocessing language allows such constructs as
25890 @smallexample
25891 @group
25892 #if DEBUG or else (PRIORITY > 4) then
25893    bunch of declarations
25894 #else
25895    completely different bunch of declarations
25896 #end if;
25897 @end group
25898 @end smallexample
25900 @noindent
25901 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25902 defined either on the command line or in a separate file.
25904 The other way of running the preprocessor is even closer to the C style and
25905 often more convenient. In this approach the preprocessing is integrated into
25906 the compilation process. The compiler is fed the preprocessor input which
25907 includes @code{#if} lines etc, and then the compiler carries out the
25908 preprocessing internally and processes the resulting output.
25909 For more details on this approach, see @ref{Integrated Preprocessing}.
25912 @c *******************************
25913 @node Inline Assembler
25914 @appendix Inline Assembler
25915 @c *******************************
25917 @noindent
25918 If you need to write low-level software that interacts directly
25919 with the hardware, Ada provides two ways to incorporate assembly
25920 language code into your program.  First, you can import and invoke
25921 external routines written in assembly language, an Ada feature fully
25922 supported by GNAT@.  However, for small sections of code it may be simpler
25923 or more efficient to include assembly language statements directly
25924 in your Ada source program, using the facilities of the implementation-defined
25925 package @code{System.Machine_Code}, which incorporates the gcc
25926 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25927 including the following:
25929 @itemize @bullet
25930 @item No need to use non-Ada tools
25931 @item Consistent interface over different targets
25932 @item Automatic usage of the proper calling conventions
25933 @item Access to Ada constants and variables
25934 @item Definition of intrinsic routines
25935 @item Possibility of inlining a subprogram comprising assembler code
25936 @item Code optimizer can take Inline Assembler code into account
25937 @end itemize
25939 This chapter presents a series of examples to show you how to use
25940 the Inline Assembler.  Although it focuses on the Intel x86,
25941 the general approach applies also to other processors.
25942 It is assumed that you are familiar with Ada
25943 and with assembly language programming.
25945 @menu
25946 * Basic Assembler Syntax::
25947 * A Simple Example of Inline Assembler::
25948 * Output Variables in Inline Assembler::
25949 * Input Variables in Inline Assembler::
25950 * Inlining Inline Assembler Code::
25951 * Other Asm Functionality::
25952 @end menu
25954 @c ---------------------------------------------------------------------------
25955 @node Basic Assembler Syntax
25956 @section Basic Assembler Syntax
25958 @noindent
25959 The assembler used by GNAT and gcc is based not on the Intel assembly
25960 language, but rather on a language that descends from the AT&T Unix
25961 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25962 The following table summarizes the main features of @emph{as} syntax
25963 and points out the differences from the Intel conventions.
25964 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25965 pre-processor) documentation for further information.
25967 @table @asis
25968 @item Register names
25969 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25971 Intel: No extra punctuation; for example @code{eax}
25973 @item Immediate operand
25974 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25976 Intel: No extra punctuation; for example @code{4}
25978 @item Address
25979 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25981 Intel: No extra punctuation; for example @code{loc}
25983 @item Memory contents
25984 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25986 Intel: Square brackets; for example @code{[loc]}
25988 @item Register contents
25989 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25991 Intel: Square brackets; for example @code{[eax]}
25993 @item Hexadecimal numbers
25994 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25996 Intel: Trailing ``h''; for example @code{A0h}
25998 @item Operand size
25999 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
26000 a 16-bit word
26002 Intel: Implicit, deduced by assembler; for example @code{mov}
26004 @item Instruction repetition
26005 gcc / @emph{as}: Split into two lines; for example
26007 @code{rep}
26009 @code{stosl}
26011 Intel: Keep on one line; for example @code{rep stosl}
26013 @item Order of operands
26014 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
26016 Intel: Destination first; for example @code{mov eax, 4}
26017 @end table
26019 @c ---------------------------------------------------------------------------
26020 @node A Simple Example of Inline Assembler
26021 @section A Simple Example of Inline Assembler
26023 @noindent
26024 The following example will generate a single assembly language statement,
26025 @code{nop}, which does nothing.  Despite its lack of run-time effect,
26026 the example will be useful in illustrating the basics of
26027 the Inline Assembler facility.
26029 @smallexample @c ada
26030 @group
26031 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26032 @b{procedure} Nothing @b{is}
26033 @b{begin}
26034    Asm ("nop");
26035 @b{end} Nothing;
26036 @end group
26037 @end smallexample
26039 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
26040 here it takes one parameter, a @emph{template string} that must be a static
26041 expression and that will form the generated instruction.
26042 @code{Asm} may be regarded as a compile-time procedure that parses
26043 the template string and additional parameters (none here),
26044 from which it generates a sequence of assembly language instructions.
26046 The examples in this chapter will illustrate several of the forms
26047 for invoking @code{Asm}; a complete specification of the syntax
26048 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
26049 Manual}.
26051 Under the standard GNAT conventions, the @code{Nothing} procedure
26052 should be in a file named @file{nothing.adb}.
26053 You can build the executable in the usual way:
26054 @smallexample
26055 gnatmake nothing
26056 @end smallexample
26057 However, the interesting aspect of this example is not its run-time behavior
26058 but rather the generated assembly code.
26059 To see this output, invoke the compiler as follows:
26060 @smallexample
26061    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
26062 @end smallexample
26063 where the options are:
26065 @table @code
26066 @item -c
26067 compile only (no bind or link)
26068 @item -S
26069 generate assembler listing
26070 @item -fomit-frame-pointer
26071 do not set up separate stack frames
26072 @item -gnatp
26073 do not add runtime checks
26074 @end table
26076 This gives a human-readable assembler version of the code. The resulting
26077 file will have the same name as the Ada source file, but with a @code{.s}
26078 extension. In our example, the file @file{nothing.s} has the following
26079 contents:
26081 @smallexample
26082 @group
26083 .file "nothing.adb"
26084 gcc2_compiled.:
26085 ___gnu_compiled_ada:
26086 .text
26087    .align 4
26088 .globl __ada_nothing
26089 __ada_nothing:
26090 #APP
26091    nop
26092 #NO_APP
26093    jmp L1
26094    .align 2,0x90
26096    ret
26097 @end group
26098 @end smallexample
26100 The assembly code you included is clearly indicated by
26101 the compiler, between the @code{#APP} and @code{#NO_APP}
26102 delimiters. The character before the 'APP' and 'NOAPP'
26103 can differ on different targets. For example, GNU/Linux uses '#APP' while
26104 on NT you will see '/APP'.
26106 If you make a mistake in your assembler code (such as using the
26107 wrong size modifier, or using a wrong operand for the instruction) GNAT
26108 will report this error in a temporary file, which will be deleted when
26109 the compilation is finished.  Generating an assembler file will help
26110 in such cases, since you can assemble this file separately using the
26111 @emph{as} assembler that comes with gcc.
26113 Assembling the file using the command
26115 @smallexample
26116 as @file{nothing.s}
26117 @end smallexample
26118 @noindent
26119 will give you error messages whose lines correspond to the assembler
26120 input file, so you can easily find and correct any mistakes you made.
26121 If there are no errors, @emph{as} will generate an object file
26122 @file{nothing.out}.
26124 @c ---------------------------------------------------------------------------
26125 @node Output Variables in Inline Assembler
26126 @section Output Variables in Inline Assembler
26128 @noindent
26129 The examples in this section, showing how to access the processor flags,
26130 illustrate how to specify the destination operands for assembly language
26131 statements.
26133 @smallexample @c ada
26134 @group
26135 @b{with} Interfaces; @b{use} Interfaces;
26136 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26137 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26138 @b{procedure} Get_Flags @b{is}
26139    Flags : Unsigned_32;
26140    @b{use} ASCII;
26141 @b{begin}
26142    Asm ("pushfl"          & LF & HT & --@i{ push flags on stack}
26143         "popl %%eax"      & LF & HT & --@i{ load eax with flags}
26144         "movl %%eax, %0",             --@i{ store flags in variable}
26145         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26146    Put_Line ("Flags register:" & Flags'Img);
26147 @b{end} Get_Flags;
26148 @end group
26149 @end smallexample
26151 In order to have a nicely aligned assembly listing, we have separated
26152 multiple assembler statements in the Asm template string with linefeed
26153 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
26154 The resulting section of the assembly output file is:
26156 @smallexample
26157 @group
26158 #APP
26159    pushfl
26160    popl %eax
26161    movl %eax, -40(%ebp)
26162 #NO_APP
26163 @end group
26164 @end smallexample
26166 It would have been legal to write the Asm invocation as:
26168 @smallexample
26169 Asm ("pushfl popl %%eax movl %%eax, %0")
26170 @end smallexample
26172 but in the generated assembler file, this would come out as:
26174 @smallexample
26175 #APP
26176    pushfl popl %eax movl %eax, -40(%ebp)
26177 #NO_APP
26178 @end smallexample
26180 which is not so convenient for the human reader.
26182 We use Ada comments
26183 at the end of each line to explain what the assembler instructions
26184 actually do.  This is a useful convention.
26186 When writing Inline Assembler instructions, you need to precede each register
26187 and variable name with a percent sign.  Since the assembler already requires
26188 a percent sign at the beginning of a register name, you need two consecutive
26189 percent signs for such names in the Asm template string, thus @code{%%eax}.
26190 In the generated assembly code, one of the percent signs will be stripped off.
26192 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
26193 variables: operands you later define using @code{Input} or @code{Output}
26194 parameters to @code{Asm}.
26195 An output variable is illustrated in
26196 the third statement in the Asm template string:
26197 @smallexample
26198 movl %%eax, %0
26199 @end smallexample
26200 The intent is to store the contents of the eax register in a variable that can
26201 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
26202 necessarily work, since the compiler might optimize by using a register
26203 to hold Flags, and the expansion of the @code{movl} instruction would not be
26204 aware of this optimization.  The solution is not to store the result directly
26205 but rather to advise the compiler to choose the correct operand form;
26206 that is the purpose of the @code{%0} output variable.
26208 Information about the output variable is supplied in the @code{Outputs}
26209 parameter to @code{Asm}:
26210 @smallexample
26211 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26212 @end smallexample
26214 The output is defined by the @code{Asm_Output} attribute of the target type;
26215 the general format is
26216 @smallexample
26217 Type'Asm_Output (constraint_string, variable_name)
26218 @end smallexample
26220 The constraint string directs the compiler how
26221 to store/access the associated variable.  In the example
26222 @smallexample
26223 Unsigned_32'Asm_Output ("=m", Flags);
26224 @end smallexample
26225 the @code{"m"} (memory) constraint tells the compiler that the variable
26226 @code{Flags} should be stored in a memory variable, thus preventing
26227 the optimizer from keeping it in a register.  In contrast,
26228 @smallexample
26229 Unsigned_32'Asm_Output ("=r", Flags);
26230 @end smallexample
26231 uses the @code{"r"} (register) constraint, telling the compiler to
26232 store the variable in a register.
26234 If the constraint is preceded by the equal character (@strong{=}), it tells
26235 the compiler that the variable will be used to store data into it.
26237 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
26238 allowing the optimizer to choose whatever it deems best.
26240 There are a fairly large number of constraints, but the ones that are
26241 most useful (for the Intel x86 processor) are the following:
26243 @table @code
26244 @item =
26245 output constraint
26246 @item g
26247 global (i.e.@: can be stored anywhere)
26248 @item m
26249 in memory
26250 @item I
26251 a constant
26252 @item a
26253 use eax
26254 @item b
26255 use ebx
26256 @item c
26257 use ecx
26258 @item d
26259 use edx
26260 @item S
26261 use esi
26262 @item D
26263 use edi
26264 @item r
26265 use one of eax, ebx, ecx or edx
26266 @item q
26267 use one of eax, ebx, ecx, edx, esi or edi
26268 @end table
26270 The full set of constraints is described in the gcc and @emph{as}
26271 documentation; note that it is possible to combine certain constraints
26272 in one constraint string.
26274 You specify the association of an output variable with an assembler operand
26275 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
26276 integer.  Thus in
26277 @smallexample @c ada
26278 @group
26279 Asm ("pushfl"          & LF & HT & --@i{ push flags on stack}
26280      "popl %%eax"      & LF & HT & --@i{ load eax with flags}
26281      "movl %%eax, %0",             --@i{ store flags in variable}
26282      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26283 @end group
26284 @end smallexample
26285 @noindent
26286 @code{%0} will be replaced in the expanded code by the appropriate operand,
26287 whatever
26288 the compiler decided for the @code{Flags} variable.
26290 In general, you may have any number of output variables:
26291 @itemize @bullet
26292 @item
26293 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26294 @item
26295 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26296 of @code{Asm_Output} attributes
26297 @end itemize
26299 For example:
26300 @smallexample @c ada
26301 @group
26302 Asm ("movl %%eax, %0" & LF & HT &
26303      "movl %%ebx, %1" & LF & HT &
26304      "movl %%ecx, %2",
26305      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --@i{  %0 = Var_A}
26306                  Unsigned_32'Asm_Output ("=g", Var_B),   --@i{  %1 = Var_B}
26307                  Unsigned_32'Asm_Output ("=g", Var_C))); --@i{  %2 = Var_C}
26308 @end group
26309 @end smallexample
26310 @noindent
26311 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26312 in the Ada program.
26314 As a variation on the @code{Get_Flags} example, we can use the constraints
26315 string to direct the compiler to store the eax register into the @code{Flags}
26316 variable, instead of including the store instruction explicitly in the
26317 @code{Asm} template string:
26319 @smallexample @c ada
26320 @group
26321 @b{with} Interfaces; @b{use} Interfaces;
26322 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26323 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26324 @b{procedure} Get_Flags_2 @b{is}
26325    Flags : Unsigned_32;
26326    @b{use} ASCII;
26327 @b{begin}
26328    Asm ("pushfl"      & LF & HT & --@i{ push flags on stack}
26329         "popl %%eax",             --@i{ save flags in eax}
26330         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26331    Put_Line ("Flags register:" & Flags'Img);
26332 @b{end} Get_Flags_2;
26333 @end group
26334 @end smallexample
26336 @noindent
26337 The @code{"a"} constraint tells the compiler that the @code{Flags}
26338 variable will come from the eax register. Here is the resulting code:
26340 @smallexample
26341 @group
26342 #APP
26343    pushfl
26344    popl %eax
26345 #NO_APP
26346    movl %eax,-40(%ebp)
26347 @end group
26348 @end smallexample
26350 @noindent
26351 The compiler generated the store of eax into Flags after
26352 expanding the assembler code.
26354 Actually, there was no need to pop the flags into the eax register;
26355 more simply, we could just pop the flags directly into the program variable:
26357 @smallexample @c ada
26358 @group
26359 @b{with} Interfaces; @b{use} Interfaces;
26360 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26361 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26362 @b{procedure} Get_Flags_3 @b{is}
26363    Flags : Unsigned_32;
26364    @b{use} ASCII;
26365 @b{begin}
26366    Asm ("pushfl"  & LF & HT & --@i{ push flags on stack}
26367         "pop %0",             --@i{ save flags in Flags}
26368         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26369    Put_Line ("Flags register:" & Flags'Img);
26370 @b{end} Get_Flags_3;
26371 @end group
26372 @end smallexample
26374 @c ---------------------------------------------------------------------------
26375 @node Input Variables in Inline Assembler
26376 @section Input Variables in Inline Assembler
26378 @noindent
26379 The example in this section illustrates how to specify the source operands
26380 for assembly language statements.
26381 The program simply increments its input value by 1:
26383 @smallexample @c ada
26384 @group
26385 @b{with} Interfaces; @b{use} Interfaces;
26386 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26387 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26388 @b{procedure} Increment @b{is}
26390    @b{function} Incr (Value : Unsigned_32) @b{return} Unsigned_32 @b{is}
26391       Result : Unsigned_32;
26392    @b{begin}
26393       Asm ("incl %0",
26394            Outputs => Unsigned_32'Asm_Output ("=a", Result),
26395            Inputs  => Unsigned_32'Asm_Input ("a", Value));
26396       @b{return} Result;
26397    @b{end} Incr;
26399    Value : Unsigned_32;
26401 @b{begin}
26402    Value := 5;
26403    Put_Line ("Value before is" & Value'Img);
26404    Value := Incr (Value);
26405    Put_Line ("Value after is" & Value'Img);
26406 @b{end} Increment;
26407 @end group
26408 @end smallexample
26410 The @code{Outputs} parameter to @code{Asm} specifies
26411 that the result will be in the eax register and that it is to be stored
26412 in the @code{Result} variable.
26414 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26415 but with an @code{Asm_Input} attribute.
26416 The @code{"="} constraint, indicating an output value, is not present.
26418 You can have multiple input variables, in the same way that you can have more
26419 than one output variable.
26421 The parameter count (%0, %1) etc, still starts at the first output statement,
26422 and continues with the input statements.
26424 Just as the @code{Outputs} parameter causes the register to be stored into the
26425 target variable after execution of the assembler statements, so does the
26426 @code{Inputs} parameter cause its variable to be loaded into the register
26427 before execution of the assembler statements.
26429 Thus the effect of the @code{Asm} invocation is:
26430 @enumerate
26431 @item load the 32-bit value of @code{Value} into eax
26432 @item execute the @code{incl %eax} instruction
26433 @item store the contents of eax into the @code{Result} variable
26434 @end enumerate
26436 The resulting assembler file (with @option{-O2} optimization) contains:
26437 @smallexample
26438 @group
26439 _increment__incr.1:
26440    subl $4,%esp
26441    movl 8(%esp),%eax
26442 #APP
26443    incl %eax
26444 #NO_APP
26445    movl %eax,%edx
26446    movl %ecx,(%esp)
26447    addl $4,%esp
26448    ret
26449 @end group
26450 @end smallexample
26452 @c ---------------------------------------------------------------------------
26453 @node Inlining Inline Assembler Code
26454 @section Inlining Inline Assembler Code
26456 @noindent
26457 For a short subprogram such as the @code{Incr} function in the previous
26458 section, the overhead of the call and return (creating / deleting the stack
26459 frame) can be significant, compared to the amount of code in the subprogram
26460 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26461 which directs the compiler to expand invocations of the subprogram at the
26462 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26463 Here is the resulting program:
26465 @smallexample @c ada
26466 @group
26467 @b{with} Interfaces; @b{use} Interfaces;
26468 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26469 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26470 @b{procedure} Increment_2 @b{is}
26472    @b{function} Incr (Value : Unsigned_32) @b{return} Unsigned_32 @b{is}
26473       Result : Unsigned_32;
26474    @b{begin}
26475       Asm ("incl %0",
26476            Outputs => Unsigned_32'Asm_Output ("=a", Result),
26477            Inputs  => Unsigned_32'Asm_Input ("a", Value));
26478       @b{return} Result;
26479    @b{end} Incr;
26480    @b{pragma} Inline (Increment);
26482    Value : Unsigned_32;
26484 @b{begin}
26485    Value := 5;
26486    Put_Line ("Value before is" & Value'Img);
26487    Value := Increment (Value);
26488    Put_Line ("Value after is" & Value'Img);
26489 @b{end} Increment_2;
26490 @end group
26491 @end smallexample
26493 Compile the program with both optimization (@option{-O2}) and inlining
26494 (@option{-gnatn}) enabled.
26496 The @code{Incr} function is still compiled as usual, but at the
26497 point in @code{Increment} where our function used to be called:
26499 @smallexample
26500 @group
26501 pushl %edi
26502 call _increment__incr.1
26503 @end group
26504 @end smallexample
26506 @noindent
26507 the code for the function body directly appears:
26509 @smallexample
26510 @group
26511 movl %esi,%eax
26512 #APP
26513    incl %eax
26514 #NO_APP
26515    movl %eax,%edx
26516 @end group
26517 @end smallexample
26519 @noindent
26520 thus saving the overhead of stack frame setup and an out-of-line call.
26522 @c ---------------------------------------------------------------------------
26523 @node Other Asm Functionality
26524 @section Other @code{Asm} Functionality
26526 @noindent
26527 This section describes two important parameters to the @code{Asm}
26528 procedure: @code{Clobber}, which identifies register usage;
26529 and @code{Volatile}, which inhibits unwanted optimizations.
26531 @menu
26532 * The Clobber Parameter::
26533 * The Volatile Parameter::
26534 @end menu
26536 @c ---------------------------------------------------------------------------
26537 @node The Clobber Parameter
26538 @subsection The @code{Clobber} Parameter
26540 @noindent
26541 One of the dangers of intermixing assembly language and a compiled language
26542 such as Ada is that the compiler needs to be aware of which registers are
26543 being used by the assembly code.  In some cases, such as the earlier examples,
26544 the constraint string is sufficient to indicate register usage (e.g.,
26545 @code{"a"} for
26546 the eax register).  But more generally, the compiler needs an explicit
26547 identification of the registers that are used by the Inline Assembly
26548 statements.
26550 Using a register that the compiler doesn't know about
26551 could be a side effect of an instruction (like @code{mull}
26552 storing its result in both eax and edx).
26553 It can also arise from explicit register usage in your
26554 assembly code; for example:
26555 @smallexample
26556 @group
26557 Asm ("movl %0, %%ebx" & LF & HT &
26558      "movl %%ebx, %1",
26559      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26560      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
26561 @end group
26562 @end smallexample
26563 @noindent
26564 where the compiler (since it does not analyze the @code{Asm} template string)
26565 does not know you are using the ebx register.
26567 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26568 to identify the registers that will be used by your assembly code:
26570 @smallexample
26571 @group
26572 Asm ("movl %0, %%ebx" & LF & HT &
26573      "movl %%ebx, %1",
26574      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26575      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26576      Clobber => "ebx");
26577 @end group
26578 @end smallexample
26580 The Clobber parameter is a static string expression specifying the
26581 register(s) you are using.  Note that register names are @emph{not} prefixed
26582 by a percent sign. Also, if more than one register is used then their names
26583 are separated by commas; e.g., @code{"eax, ebx"}
26585 The @code{Clobber} parameter has several additional uses:
26586 @enumerate
26587 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26588 @item Use ``register'' name @code{memory} if you changed a memory location
26589 @end enumerate
26591 @c ---------------------------------------------------------------------------
26592 @node The Volatile Parameter
26593 @subsection The @code{Volatile} Parameter
26594 @cindex Volatile parameter
26596 @noindent
26597 Compiler optimizations in the presence of Inline Assembler may sometimes have
26598 unwanted effects.  For example, when an @code{Asm} invocation with an input
26599 variable is inside a loop, the compiler might move the loading of the input
26600 variable outside the loop, regarding it as a one-time initialization.
26602 If this effect is not desired, you can disable such optimizations by setting
26603 the @code{Volatile} parameter to @code{True}; for example:
26605 @smallexample @c ada
26606 @group
26607 Asm ("movl %0, %%ebx" & LF & HT &
26608      "movl %%ebx, %1",
26609      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26610      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26611      Clobber  => "ebx",
26612      Volatile => True);
26613 @end group
26614 @end smallexample
26616 By default, @code{Volatile} is set to @code{False} unless there is no
26617 @code{Outputs} parameter.
26619 Although setting @code{Volatile} to @code{True} prevents unwanted
26620 optimizations, it will also disable other optimizations that might be
26621 important for efficiency. In general, you should set @code{Volatile}
26622 to @code{True} only if the compiler's optimizations have created
26623 problems.
26624 @c END OF INLINE ASSEMBLER CHAPTER
26625 @c ===============================
26628 @c *****************************************
26629 @c Writing Portable Fixed-Point Declarations
26630 @c *****************************************
26631 @node Writing Portable Fixed-Point Declarations
26632 @appendix Writing Portable Fixed-Point Declarations
26633 @cindex Fixed-point types (writing portable declarations)
26635 @noindent
26636 The Ada Reference Manual gives an implementation freedom to choose bounds
26637 that are narrower by @code{Small} from the given bounds.
26638 For example, if we write
26640 @smallexample @c ada
26641    type F1 is delta 1.0 range -128.0 .. +128.0;
26642 @end smallexample
26644 @noindent
26645 then the implementation is allowed to choose -128.0 .. +127.0 if it
26646 likes, but is not required to do so.
26648 This leads to possible portability problems, so let's have a closer
26649 look at this, and figure out how to avoid these problems.
26651 First, why does this freedom exist, and why would an implementation
26652 take advantage of it? To answer this, take a closer look at the type
26653 declaration for @code{F1} above. If the compiler uses the given bounds,
26654 it would need 9 bits to hold the largest positive value (and typically
26655 that means 16 bits on all machines). But if the implementation chooses
26656 the +127.0 bound then it can fit values of the type in 8 bits.
26658 Why not make the user write +127.0 if that's what is wanted?
26659 The rationale is that if you are thinking of fixed point
26660 as a kind of ``poor man's floating-point'', then you don't want
26661 to be thinking about the scaled integers that are used in its
26662 representation. Let's take another example:
26664 @smallexample @c ada
26665    type F2 is delta 2.0**(-15) range -1.0 .. +1.0;
26666 @end smallexample
26668 @noindent
26669 Looking at this declaration, it seems casually as though
26670 it should fit in 16 bits, but again that extra positive value
26671 +1.0 has the scaled integer equivalent of 2**15 which is one too
26672 big for signed 16 bits. The implementation can treat this as:
26674 @smallexample @c ada
26675    type F2 is delta 2.0**(-15) range -1.0 .. +1.0-(2.0**(-15));
26676 @end smallexample
26678 @noindent
26679 and the Ada language design team felt that this was too annoying
26680 to require. We don't need to debate this decision at this point,
26681 since it is well established (the rule about narrowing the ranges
26682 dates to Ada 83).
26684 But the important point is that an implementation is not required
26685 to do this narrowing, so we have a potential portability problem.
26686 We could imagine three types of implementation:
26688 @enumerate a
26689 @item
26690 those that narrow the range automatically if they can figure
26691 out that the narrower range will allow storage in a smaller machine unit,
26693 @item
26694 those that will narrow only if forced to by a @code{'Size} clause, and
26696 @item
26697 those that will never narrow.
26698 @end enumerate
26700 @noindent
26701 Now if we are language theoreticians, we can imagine a fourth
26702 approach: is to narrow all the time, e.g. to treat
26704 @smallexample @c ada
26705    type F3 is delta 1.0 range -10.0 .. +23.0;
26706 @end smallexample
26708 @noindent
26709 as though it had been written:
26711 @smallexample @c ada
26712    type F3 is delta 1.0 range -9.0 .. +22.0;
26713 @end smallexample
26715 @noindent
26716 But although technically allowed, such a behavior would be hostile and silly,
26717 and no real compiler would do this. All real compilers will fall into one of
26718 the categories (a), (b) or (c) above.
26720 So, how do you get the compiler to do what you want? The answer is give the
26721 actual bounds you want, and then use a @code{'Small} clause and a
26722 @code{'Size} clause to absolutely pin down what the compiler does.
26723 E.g., for @code{F2} above, we will write:
26725 @smallexample @c ada
26726 @group
26727    My_Small : constant := 2.0**(-15);
26728    My_First : constant := -1.0;
26729    My_Last  : constant := +1.0 - My_Small;
26731    type F2 is delta My_Small range My_First .. My_Last;
26732 @end group
26733 @end smallexample
26735 @noindent
26736 and then add
26738 @smallexample @c ada
26739 @group
26740    for F2'Small use my_Small;
26741    for F2'Size  use 16;
26742 @end group
26743 @end smallexample
26745 @noindent
26746 In practice all compilers will do the same thing here and will give you
26747 what you want, so the above declarations are fully portable. If you really
26748 want to play language lawyer and guard against ludicrous behavior by the
26749 compiler you could add
26751 @smallexample @c ada
26752 @group
26753    Test1 : constant := 1 / Boolean'Pos (F2'First = My_First);
26754    Test2 : constant := 1 / Boolean'Pos (F2'Last  = My_Last);
26755 @end group
26756 @end smallexample
26758 @noindent
26759 One or other or both are allowed to be illegal if the compiler is
26760 behaving in a silly manner, but at least the silly compiler will not
26761 get away with silently messing with your (very clear) intentions.
26763 If you follow this scheme you will be guaranteed that your fixed-point
26764 types will be portable.
26767 @c ***********************************
26768 @c * Compatibility and Porting Guide *
26769 @c ***********************************
26770 @node Compatibility and Porting Guide
26771 @appendix Compatibility and Porting Guide
26773 @noindent
26774 This chapter describes the compatibility issues that may arise between
26775 GNAT and other Ada compilation systems (including those for Ada 83),
26776 and shows how GNAT can expedite porting
26777 applications developed in other Ada environments.
26779 @menu
26780 * Compatibility with Ada 83::
26781 * Compatibility between Ada 95 and Ada 2005::
26782 * Implementation-dependent characteristics::
26783 * Compatibility with Other Ada Systems::
26784 * Representation Clauses::
26785 @c Brief section is only in non-VMS version
26786 @c Full chapter is in VMS version
26787 * Compatibility with HP Ada 83::
26788 @end menu
26790 @node Compatibility with Ada 83
26791 @section Compatibility with Ada 83
26792 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26794 @noindent
26795 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
26796 particular, the design intention was that the difficulties associated
26797 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26798 that occur when moving from one Ada 83 system to another.
26800 However, there are a number of points at which there are minor
26801 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26802 full details of these issues,
26803 and should be consulted for a complete treatment.
26804 In practice the
26805 following subsections treat the most likely issues to be encountered.
26807 @menu
26808 * Legal Ada 83 programs that are illegal in Ada 95::
26809 * More deterministic semantics::
26810 * Changed semantics::
26811 * Other language compatibility issues::
26812 @end menu
26814 @node Legal Ada 83 programs that are illegal in Ada 95
26815 @subsection Legal Ada 83 programs that are illegal in Ada 95
26817 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26818 Ada 95 and thus also in Ada 2005:
26820 @table @emph
26821 @item Character literals
26822 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26823 @code{Wide_Character} as a new predefined character type, some uses of
26824 character literals that were legal in Ada 83 are illegal in Ada 95.
26825 For example:
26826 @smallexample @c ada
26827    @b{for} Char @b{in} 'A' .. 'Z' @b{loop} @dots{} @b{end} @b{loop};
26828 @end smallexample
26830 @noindent
26831 The problem is that @code{'A'} and @code{'Z'} could be from either
26832 @code{Character} or @code{Wide_Character}.  The simplest correction
26833 is to make the type explicit; e.g.:
26834 @smallexample @c ada
26835    @b{for} Char @b{in} Character @b{range} 'A' .. 'Z' @b{loop} @dots{} @b{end} @b{loop};
26836 @end smallexample
26838 @item New reserved words
26839 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26840 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26841 Existing Ada 83 code using any of these identifiers must be edited to
26842 use some alternative name.
26844 @item Freezing rules
26845 The rules in Ada 95 are slightly different with regard to the point at
26846 which entities are frozen, and representation pragmas and clauses are
26847 not permitted past the freeze point.  This shows up most typically in
26848 the form of an error message complaining that a representation item
26849 appears too late, and the appropriate corrective action is to move
26850 the item nearer to the declaration of the entity to which it refers.
26852 A particular case is that representation pragmas
26853 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26854 declaration must be introduced to which the pragma can be applied.
26856 @item Optional bodies for library packages
26857 In Ada 83, a package that did not require a package body was nevertheless
26858 allowed to have one.  This lead to certain surprises in compiling large
26859 systems (situations in which the body could be unexpectedly ignored by the
26860 binder).  In Ada 95, if a package does not require a body then it is not
26861 permitted to have a body.  To fix this problem, simply remove a redundant
26862 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26863 into the spec that makes the body required.  One approach is to add a private
26864 part to the package declaration (if necessary), and define a parameterless
26865 procedure called @code{Requires_Body}, which must then be given a dummy
26866 procedure body in the package body, which then becomes required.
26867 Another approach (assuming that this does not introduce elaboration
26868 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26869 since one effect of this pragma is to require the presence of a package body.
26871 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26872 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26873 @code{Constraint_Error}.
26874 This means that it is illegal to have separate exception handlers for
26875 the two exceptions.  The fix is simply to remove the handler for the
26876 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26877 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26879 @item Indefinite subtypes in generics
26880 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26881 as the actual for a generic formal private type, but then the instantiation
26882 would be illegal if there were any instances of declarations of variables
26883 of this type in the generic body.  In Ada 95, to avoid this clear violation
26884 of the methodological principle known as the ``contract model'',
26885 the generic declaration explicitly indicates whether
26886 or not such instantiations are permitted.  If a generic formal parameter
26887 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26888 subtype name, then it can be instantiated with indefinite types, but no
26889 stand-alone variables can be declared of this type.  Any attempt to declare
26890 such a variable will result in an illegality at the time the generic is
26891 declared.  If the @code{(<>)} notation is not used, then it is illegal
26892 to instantiate the generic with an indefinite type.
26893 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26894 It will show up as a compile time error, and
26895 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26896 @end table
26898 @node More deterministic semantics
26899 @subsection More deterministic semantics
26901 @table @emph
26902 @item Conversions
26903 Conversions from real types to integer types round away from 0.  In Ada 83
26904 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26905 implementation freedom was intended to support unbiased rounding in
26906 statistical applications, but in practice it interfered with portability.
26907 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26908 is required.  Numeric code may be affected by this change in semantics.
26909 Note, though, that this issue is no worse than already existed in Ada 83
26910 when porting code from one vendor to another.
26912 @item Tasking
26913 The Real-Time Annex introduces a set of policies that define the behavior of
26914 features that were implementation dependent in Ada 83, such as the order in
26915 which open select branches are executed.
26916 @end table
26918 @node Changed semantics
26919 @subsection Changed semantics
26921 @noindent
26922 The worst kind of incompatibility is one where a program that is legal in
26923 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26924 possible in Ada 83.  Fortunately this is extremely rare, but the one
26925 situation that you should be alert to is the change in the predefined type
26926 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26928 @table @emph
26929 @item Range of type @code{Character}
26930 The range of @code{Standard.Character} is now the full 256 characters
26931 of Latin-1, whereas in most Ada 83 implementations it was restricted
26932 to 128 characters. Although some of the effects of
26933 this change will be manifest in compile-time rejection of legal
26934 Ada 83 programs it is possible for a working Ada 83 program to have
26935 a different effect in Ada 95, one that was not permitted in Ada 83.
26936 As an example, the expression
26937 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26938 delivers @code{255} as its value.
26939 In general, you should look at the logic of any
26940 character-processing Ada 83 program and see whether it needs to be adapted
26941 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26942 character handling package that may be relevant if code needs to be adapted
26943 to account for the additional Latin-1 elements.
26944 The desirable fix is to
26945 modify the program to accommodate the full character set, but in some cases
26946 it may be convenient to define a subtype or derived type of Character that
26947 covers only the restricted range.
26948 @cindex Latin-1
26949 @end table
26951 @node Other language compatibility issues
26952 @subsection Other language compatibility issues
26954 @table @emph
26955 @item @option{-gnat83} switch
26956 All implementations of GNAT provide a switch that causes GNAT to operate
26957 in Ada 83 mode.  In this mode, some but not all compatibility problems
26958 of the type described above are handled automatically.  For example, the
26959 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26960 as identifiers as in Ada 83.
26961 However,
26962 in practice, it is usually advisable to make the necessary modifications
26963 to the program to remove the need for using this switch.
26964 See @ref{Compiling Different Versions of Ada}.
26966 @item Support for removed Ada 83 pragmas and attributes
26967 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26968 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26969 compilers are allowed, but not required, to implement these missing
26970 elements.  In contrast with some other compilers, GNAT implements all
26971 such pragmas and attributes, eliminating this compatibility concern.  These
26972 include @code{pragma Interface} and the floating point type attributes
26973 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26974 @end table
26977 @node Compatibility between Ada 95 and Ada 2005
26978 @section Compatibility between Ada 95 and Ada 2005
26979 @cindex Compatibility between Ada 95 and Ada 2005
26981 @noindent
26982 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26983 a number of incompatibilities. Several are enumerated below;
26984 for a complete description please see the
26985 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26986 @cite{Rationale for Ada 2005}.
26988 @table @emph
26989 @item New reserved words.
26990 The words @code{interface}, @code{overriding} and @code{synchronized} are
26991 reserved in Ada 2005.
26992 A pre-Ada 2005 program that uses any of these as an identifier will be
26993 illegal.
26995 @item New declarations in predefined packages.
26996 A number of packages in the predefined environment contain new declarations:
26997 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26998 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26999 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
27000 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
27001 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
27002 If an Ada 95 program does a @code{with} and @code{use} of any of these
27003 packages, the new declarations may cause name clashes.
27005 @item Access parameters.
27006 A nondispatching subprogram with an access parameter cannot be renamed
27007 as a dispatching operation.  This was permitted in Ada 95.
27009 @item Access types, discriminants, and constraints.
27010 Rule changes in this area have led to some incompatibilities; for example,
27011 constrained subtypes of some access types are not permitted in Ada 2005.
27013 @item Aggregates for limited types.
27014 The allowance of aggregates for limited types in Ada 2005 raises the
27015 possibility of ambiguities in legal Ada 95 programs, since additional types
27016 now need to be considered in expression resolution.
27018 @item Fixed-point multiplication and division.
27019 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
27020 were legal in Ada 95 and invoked the predefined versions of these operations,
27021 are now ambiguous.
27022 The ambiguity may be resolved either by applying a type conversion to the
27023 expression, or by explicitly invoking the operation from package
27024 @code{Standard}.
27026 @item Return-by-reference types.
27027 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
27028 can declare a function returning a value from an anonymous access type.
27029 @end table
27032 @node Implementation-dependent characteristics
27033 @section Implementation-dependent characteristics
27034 @noindent
27035 Although the Ada language defines the semantics of each construct as
27036 precisely as practical, in some situations (for example for reasons of
27037 efficiency, or where the effect is heavily dependent on the host or target
27038 platform) the implementation is allowed some freedom.  In porting Ada 83
27039 code to GNAT, you need to be aware of whether / how the existing code
27040 exercised such implementation dependencies.  Such characteristics fall into
27041 several categories, and GNAT offers specific support in assisting the
27042 transition from certain Ada 83 compilers.
27044 @menu
27045 * Implementation-defined pragmas::
27046 * Implementation-defined attributes::
27047 * Libraries::
27048 * Elaboration order::
27049 * Target-specific aspects::
27050 @end menu
27052 @node Implementation-defined pragmas
27053 @subsection Implementation-defined pragmas
27055 @noindent
27056 Ada compilers are allowed to supplement the language-defined pragmas, and
27057 these are a potential source of non-portability.  All GNAT-defined pragmas
27058 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
27059 Reference Manual}, and these include several that are specifically
27060 intended to correspond to other vendors' Ada 83 pragmas.
27061 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
27062 For compatibility with HP Ada 83, GNAT supplies the pragmas
27063 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
27064 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
27065 and @code{Volatile}.
27066 Other relevant pragmas include @code{External} and @code{Link_With}.
27067 Some vendor-specific
27068 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
27069 recognized, thus
27070 avoiding compiler rejection of units that contain such pragmas; they are not
27071 relevant in a GNAT context and hence are not otherwise implemented.
27073 @node Implementation-defined attributes
27074 @subsection Implementation-defined attributes
27076 Analogous to pragmas, the set of attributes may be extended by an
27077 implementation.  All GNAT-defined attributes are described in
27078 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
27079 Manual}, and these include several that are specifically intended
27080 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
27081 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
27082 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
27083 @code{Type_Class}.
27085 @node Libraries
27086 @subsection Libraries
27087 @noindent
27088 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
27089 code uses vendor-specific libraries then there are several ways to manage
27090 this in Ada 95 or Ada 2005:
27091 @enumerate
27092 @item
27093 If the source code for the libraries (specs and bodies) are
27094 available, then the libraries can be migrated in the same way as the
27095 application.
27096 @item
27097 If the source code for the specs but not the bodies are
27098 available, then you can reimplement the bodies.
27099 @item
27100 Some features introduced by Ada 95 obviate the need for library support.  For
27101 example most Ada 83 vendors supplied a package for unsigned integers.  The
27102 Ada 95 modular type feature is the preferred way to handle this need, so
27103 instead of migrating or reimplementing the unsigned integer package it may
27104 be preferable to retrofit the application using modular types.
27105 @end enumerate
27107 @node Elaboration order
27108 @subsection Elaboration order
27109 @noindent
27110 The implementation can choose any elaboration order consistent with the unit
27111 dependency relationship.  This freedom means that some orders can result in
27112 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
27113 to invoke a subprogram its body has been elaborated, or to instantiate a
27114 generic before the generic body has been elaborated.  By default GNAT
27115 attempts to choose a safe order (one that will not encounter access before
27116 elaboration problems) by implicitly inserting @code{Elaborate} or
27117 @code{Elaborate_All} pragmas where
27118 needed.  However, this can lead to the creation of elaboration circularities
27119 and a resulting rejection of the program by gnatbind.  This issue is
27120 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
27121 In brief, there are several
27122 ways to deal with this situation:
27124 @itemize @bullet
27125 @item
27126 Modify the program to eliminate the circularities, e.g.@: by moving
27127 elaboration-time code into explicitly-invoked procedures
27128 @item
27129 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
27130 @code{Elaborate} pragmas, and then inhibit the generation of implicit
27131 @code{Elaborate_All}
27132 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
27133 (by selectively suppressing elaboration checks via pragma
27134 @code{Suppress(Elaboration_Check)} when it is safe to do so).
27135 @end itemize
27137 @node Target-specific aspects
27138 @subsection Target-specific aspects
27139 @noindent
27140 Low-level applications need to deal with machine addresses, data
27141 representations, interfacing with assembler code, and similar issues.  If
27142 such an Ada 83 application is being ported to different target hardware (for
27143 example where the byte endianness has changed) then you will need to
27144 carefully examine the program logic; the porting effort will heavily depend
27145 on the robustness of the original design.  Moreover, Ada 95 (and thus
27146 Ada 2005) are sometimes
27147 incompatible with typical Ada 83 compiler practices regarding implicit
27148 packing, the meaning of the Size attribute, and the size of access values.
27149 GNAT's approach to these issues is described in @ref{Representation Clauses}.
27151 @node Compatibility with Other Ada Systems
27152 @section Compatibility with Other Ada Systems
27154 @noindent
27155 If programs avoid the use of implementation dependent and
27156 implementation defined features, as documented in the @cite{Ada
27157 Reference Manual}, there should be a high degree of portability between
27158 GNAT and other Ada systems.  The following are specific items which
27159 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
27160 compilers, but do not affect porting code to GNAT@.
27161 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
27162 the following issues may or may not arise for Ada 2005 programs
27163 when other compilers appear.)
27165 @table @emph
27166 @item Ada 83 Pragmas and Attributes
27167 Ada 95 compilers are allowed, but not required, to implement the missing
27168 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
27169 GNAT implements all such pragmas and attributes, eliminating this as
27170 a compatibility concern, but some other Ada 95 compilers reject these
27171 pragmas and attributes.
27173 @item Specialized Needs Annexes
27174 GNAT implements the full set of special needs annexes.  At the
27175 current time, it is the only Ada 95 compiler to do so.  This means that
27176 programs making use of these features may not be portable to other Ada
27177 95 compilation systems.
27179 @item Representation Clauses
27180 Some other Ada 95 compilers implement only the minimal set of
27181 representation clauses required by the Ada 95 reference manual.  GNAT goes
27182 far beyond this minimal set, as described in the next section.
27183 @end table
27185 @node Representation Clauses
27186 @section Representation Clauses
27188 @noindent
27189 The Ada 83 reference manual was quite vague in describing both the minimal
27190 required implementation of representation clauses, and also their precise
27191 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
27192 minimal set of capabilities required is still quite limited.
27194 GNAT implements the full required set of capabilities in
27195 Ada 95 and Ada 2005, but also goes much further, and in particular
27196 an effort has been made to be compatible with existing Ada 83 usage to the
27197 greatest extent possible.
27199 A few cases exist in which Ada 83 compiler behavior is incompatible with
27200 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
27201 intentional or accidental dependence on specific implementation dependent
27202 characteristics of these Ada 83 compilers.  The following is a list of
27203 the cases most likely to arise in existing Ada 83 code.
27205 @table @emph
27206 @item Implicit Packing
27207 Some Ada 83 compilers allowed a Size specification to cause implicit
27208 packing of an array or record.  This could cause expensive implicit
27209 conversions for change of representation in the presence of derived
27210 types, and the Ada design intends to avoid this possibility.
27211 Subsequent AI's were issued to make it clear that such implicit
27212 change of representation in response to a Size clause is inadvisable,
27213 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
27214 Reference Manuals as implementation advice that is followed by GNAT@.
27215 The problem will show up as an error
27216 message rejecting the size clause.  The fix is simply to provide
27217 the explicit pragma @code{Pack}, or for more fine tuned control, provide
27218 a Component_Size clause.
27220 @item Meaning of Size Attribute
27221 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
27222 the minimal number of bits required to hold values of the type.  For example,
27223 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
27224 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
27225 some 32 in this situation.  This problem will usually show up as a compile
27226 time error, but not always.  It is a good idea to check all uses of the
27227 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
27228 Object_Size can provide a useful way of duplicating the behavior of
27229 some Ada 83 compiler systems.
27231 @item Size of Access Types
27232 A common assumption in Ada 83 code is that an access type is in fact a pointer,
27233 and that therefore it will be the same size as a System.Address value.  This
27234 assumption is true for GNAT in most cases with one exception.  For the case of
27235 a pointer to an unconstrained array type (where the bounds may vary from one
27236 value of the access type to another), the default is to use a ``fat pointer'',
27237 which is represented as two separate pointers, one to the bounds, and one to
27238 the array.  This representation has a number of advantages, including improved
27239 efficiency.  However, it may cause some difficulties in porting existing Ada 83
27240 code which makes the assumption that, for example, pointers fit in 32 bits on
27241 a machine with 32-bit addressing.
27243 To get around this problem, GNAT also permits the use of ``thin pointers'' for
27244 access types in this case (where the designated type is an unconstrained array
27245 type).  These thin pointers are indeed the same size as a System.Address value.
27246 To specify a thin pointer, use a size clause for the type, for example:
27248 @smallexample @c ada
27249 @b{type} X @b{is} @b{access} @b{all} String;
27250 @b{for} X'Size @b{use} Standard'Address_Size;
27251 @end smallexample
27253 @noindent
27254 which will cause the type X to be represented using a single pointer.
27255 When using this representation, the bounds are right behind the array.
27256 This representation is slightly less efficient, and does not allow quite
27257 such flexibility in the use of foreign pointers or in using the
27258 Unrestricted_Access attribute to create pointers to non-aliased objects.
27259 But for any standard portable use of the access type it will work in
27260 a functionally correct manner and allow porting of existing code.
27261 Note that another way of forcing a thin pointer representation
27262 is to use a component size clause for the element size in an array,
27263 or a record representation clause for an access field in a record.
27265 See the documentation of Unrestricted_Access in the GNAT RM for a
27266 full discussion of possible problems using this attribute in conjunction
27267 with thin pointers.
27268 @end table
27270 @c This brief section is only in the non-VMS version
27271 @c The complete chapter on HP Ada is in the VMS version
27272 @node Compatibility with HP Ada 83
27273 @section Compatibility with HP Ada 83
27275 @noindent
27276 The VMS version of GNAT fully implements all the pragmas and attributes
27277 provided by HP Ada 83, as well as providing the standard HP Ada 83
27278 libraries, including Starlet.  In addition, data layouts and parameter
27279 passing conventions are highly compatible.  This means that porting
27280 existing HP Ada 83 code to GNAT in VMS systems should be easier than
27281 most other porting efforts.  The following are some of the most
27282 significant differences between GNAT and HP Ada 83.
27284 @table @emph
27285 @item Default floating-point representation
27286 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
27287 it is VMS format.  GNAT does implement the necessary pragmas
27288 (Long_Float, Float_Representation) for changing this default.
27290 @item System
27291 The package System in GNAT exactly corresponds to the definition in the
27292 Ada 95 reference manual, which means that it excludes many of the
27293 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
27294 that contains the additional definitions, and a special pragma,
27295 Extend_System allows this package to be treated transparently as an
27296 extension of package System.
27298 @item To_Address
27299 The definitions provided by Aux_DEC are exactly compatible with those
27300 in the HP Ada 83 version of System, with one exception.
27301 HP Ada provides the following declarations:
27303 @smallexample @c ada
27304 TO_ADDRESS (INTEGER)
27305 TO_ADDRESS (UNSIGNED_LONGWORD)
27306 TO_ADDRESS (@i{universal_integer})
27307 @end smallexample
27309 @noindent
27310 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
27311 an extension to Ada 83 not strictly compatible with the reference manual.
27312 In GNAT, we are constrained to be exactly compatible with the standard,
27313 and this means we cannot provide this capability.  In HP Ada 83, the
27314 point of this definition is to deal with a call like:
27316 @smallexample @c ada
27317 TO_ADDRESS (16#12777#);
27318 @end smallexample
27320 @noindent
27321 Normally, according to the Ada 83 standard, one would expect this to be
27322 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
27323 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
27324 definition using @i{universal_integer} takes precedence.
27326 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
27327 is not possible to be 100% compatible.  Since there are many programs using
27328 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
27329 to change the name of the function in the UNSIGNED_LONGWORD case, so the
27330 declarations provided in the GNAT version of AUX_Dec are:
27332 @smallexample @c ada
27333 @b{function} To_Address (X : Integer) @b{return} Address;
27334 @b{pragma} Pure_Function (To_Address);
27336 @b{function} To_Address_Long (X : Unsigned_Longword)
27337  @b{return} Address;
27338 @b{pragma} Pure_Function (To_Address_Long);
27339 @end smallexample
27341 @noindent
27342 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
27343 change the name to TO_ADDRESS_LONG@.
27345 @item Task_Id values
27346 The Task_Id values assigned will be different in the two systems, and GNAT
27347 does not provide a specified value for the Task_Id of the environment task,
27348 which in GNAT is treated like any other declared task.
27349 @end table
27351 @noindent
27352 For full details on these and other less significant compatibility issues,
27353 see appendix E of the HP publication entitled @cite{HP Ada, Technical
27354 Overview and Comparison on HP Platforms}.
27356 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
27357 attributes are recognized, although only a subset of them can sensibly
27358 be implemented.  The description of pragmas in @ref{Implementation
27359 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
27360 indicates whether or not they are applicable to non-VMS systems.
27363 @c ************************************************
27364 @node Microsoft Windows Topics
27365 @appendix Microsoft Windows Topics
27366 @cindex Windows NT
27367 @cindex Windows 95
27368 @cindex Windows 98
27370 @noindent
27371 This chapter describes topics that are specific to the Microsoft Windows
27372 platforms (NT, 2000, and XP Professional).
27374 @menu
27375 @ifclear FSFEDITION
27376 * Installing from the Command Line::
27377 @end ifclear
27378 * Using GNAT on Windows::
27379 * Using a network installation of GNAT::
27380 * CONSOLE and WINDOWS subsystems::
27381 * Temporary Files::
27382 * Mixed-Language Programming on Windows::
27383 * Windows Calling Conventions::
27384 * Introduction to Dynamic Link Libraries (DLLs)::
27385 * Using DLLs with GNAT::
27386 * Building DLLs with GNAT Project files::
27387 * Building DLLs with GNAT::
27388 * Building DLLs with gnatdll::
27389 * GNAT and Windows Resources::
27390 * Debugging a DLL::
27391 * Setting Stack Size from gnatlink::
27392 * Setting Heap Size from gnatlink::
27393 @end menu
27395 @ifclear FSFEDITION
27396 @node Installing from the Command Line
27397 @section Installing from the Command Line
27398 @cindex Batch installation
27399 @cindex Silent installation
27400 @cindex Unassisted installation
27402 @noindent
27403 By default the @value{EDITION} installers display a GUI that prompts the user
27404 to enter installation path and similar information, and guide him through the
27405 installation process. It is also possible to perform silent installations
27406 using the command-line interface.
27408 In order to install one of the @value{EDITION} installers from the command
27409 line you should pass parameter @code{/S} (and, optionally,
27410 @code{/D=<directory>}) as command-line arguments.
27412 @ifset PROEDITION
27413 For example, for an unattended installation of
27414 @value{EDITION} 7.0.2 into the default directory
27415 @code{C:\GNATPRO\7.0.2} you would run:
27417 @smallexample
27418 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
27419 @end smallexample
27421 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
27423 @smallexample
27424 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
27425 @end smallexample
27426 @end ifset
27428 @ifset GPLEDITION
27429 For example, for an unattended installation of
27430 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
27432 @smallexample
27433 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
27434 @end smallexample
27435 @end ifset
27437 You can use the same syntax for all installers.
27439 Note that unattended installations don't modify system path, nor create file
27440 associations, so such activities need to be done by hand.
27441 @end ifclear
27443 @node Using GNAT on Windows
27444 @section Using GNAT on Windows
27446 @noindent
27447 One of the strengths of the GNAT technology is that its tool set
27448 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27449 @code{gdb} debugger, etc.) is used in the same way regardless of the
27450 platform.
27452 On Windows this tool set is complemented by a number of Microsoft-specific
27453 tools that have been provided to facilitate interoperability with Windows
27454 when this is required. With these tools:
27456 @itemize @bullet
27458 @item
27459 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27460 subsystems.
27462 @item
27463 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27464 relocatable and non-relocatable DLLs are supported).
27466 @item
27467 You can build Ada DLLs for use in other applications. These applications
27468 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27469 relocatable and non-relocatable Ada DLLs are supported.
27471 @item
27472 You can include Windows resources in your Ada application.
27474 @item
27475 You can use or create COM/DCOM objects.
27476 @end itemize
27478 @noindent
27479 Immediately below are listed all known general GNAT-for-Windows restrictions.
27480 Other restrictions about specific features like Windows Resources and DLLs
27481 are listed in separate sections below.
27483 @itemize @bullet
27485 @item
27486 It is not possible to use @code{GetLastError} and @code{SetLastError}
27487 when tasking, protected records, or exceptions are used. In these
27488 cases, in order to implement Ada semantics, the GNAT run-time system
27489 calls certain Win32 routines that set the last error variable to 0 upon
27490 success. It should be possible to use @code{GetLastError} and
27491 @code{SetLastError} when tasking, protected record, and exception
27492 features are not used, but it is not guaranteed to work.
27494 @item
27495 It is not possible to link against Microsoft C++ libraries except for
27496 import libraries. Interfacing must be done by the mean of DLLs.
27498 @item
27499 It is possible to link against Microsoft C libraries. Yet the preferred
27500 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
27501 doesn't require having two different development environments and makes the
27502 inter-language debugging experience smoother.
27504 @item
27505 When the compilation environment is located on FAT32 drives, users may
27506 experience recompilations of the source files that have not changed if
27507 Daylight Saving Time (DST) state has changed since the last time files
27508 were compiled. NTFS drives do not have this problem.
27510 @item
27511 No components of the GNAT toolset use any entries in the Windows
27512 registry. The only entries that can be created are file associations and
27513 PATH settings, provided the user has chosen to create them at installation
27514 time, as well as some minimal book-keeping information needed to correctly
27515 uninstall or integrate different GNAT products.
27516 @end itemize
27518 @node Using a network installation of GNAT
27519 @section Using a network installation of GNAT
27521 @noindent
27522 Make sure the system on which GNAT is installed is accessible from the
27523 current machine, i.e., the install location is shared over the network.
27524 Shared resources are accessed on Windows by means of UNC paths, which
27525 have the format @code{\\server\sharename\path}
27527 In order to use such a network installation, simply add the UNC path of the
27528 @file{bin} directory of your GNAT installation in front of your PATH. For
27529 example, if GNAT is installed in @file{\GNAT} directory of a share location
27530 called @file{c-drive} on a machine @file{LOKI}, the following command will
27531 make it available:
27533 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27535 Be aware that every compilation using the network installation results in the
27536 transfer of large amounts of data across the network and will likely cause
27537 serious performance penalty.
27539 @node CONSOLE and WINDOWS subsystems
27540 @section CONSOLE and WINDOWS subsystems
27541 @cindex CONSOLE Subsystem
27542 @cindex WINDOWS Subsystem
27543 @cindex -mwindows
27545 @noindent
27546 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27547 (which is the default subsystem) will always create a console when
27548 launching the application. This is not something desirable when the
27549 application has a Windows GUI. To get rid of this console the
27550 application must be using the @code{WINDOWS} subsystem. To do so
27551 the @option{-mwindows} linker option must be specified.
27553 @smallexample
27554 $ gnatmake winprog -largs -mwindows
27555 @end smallexample
27557 @node Temporary Files
27558 @section Temporary Files
27559 @cindex Temporary files
27561 @noindent
27562 It is possible to control where temporary files gets created by setting
27563 the @env{TMP} environment variable. The file will be created:
27565 @itemize
27566 @item Under the directory pointed to by the @env{TMP} environment variable if
27567 this directory exists.
27569 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27570 set (or not pointing to a directory) and if this directory exists.
27572 @item Under the current working directory otherwise.
27573 @end itemize
27575 @noindent
27576 This allows you to determine exactly where the temporary
27577 file will be created. This is particularly useful in networked
27578 environments where you may not have write access to some
27579 directories.
27581 @node Mixed-Language Programming on Windows
27582 @section Mixed-Language Programming on Windows
27584 @noindent
27585 Developing pure Ada applications on Windows is no different than on
27586 other GNAT-supported platforms. However, when developing or porting an
27587 application that contains a mix of Ada and C/C++, the choice of your
27588 Windows C/C++ development environment conditions your overall
27589 interoperability strategy.
27591 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
27592 your application, there are no Windows-specific restrictions that
27593 affect the overall interoperability with your Ada code. If you do want
27594 to use the Microsoft tools for your C++ code, you have two choices:
27596 @enumerate
27597 @item
27598 Encapsulate your C++ code in a DLL to be linked with your Ada
27599 application. In this case, use the Microsoft or whatever environment to
27600 build the DLL and use GNAT to build your executable
27601 (@pxref{Using DLLs with GNAT}).
27603 @item
27604 Or you can encapsulate your Ada code in a DLL to be linked with the
27605 other part of your application. In this case, use GNAT to build the DLL
27606 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27607 or whatever environment to build your executable.
27608 @end enumerate
27610 In addition to the description about C main in
27611 @pxref{Mixed Language Programming} section, if the C main uses a
27612 stand-alone library it is required on x86-windows to
27613 setup the SEH context. For this the C main must looks like this:
27615 @smallexample
27616 /* main.c */
27617 extern void adainit (void);
27618 extern void adafinal (void);
27619 extern void __gnat_initialize(void*);
27620 extern void call_to_ada (void);
27622 int main (int argc, char *argv[])
27624   int SEH [2];
27626   /* Initialize the SEH context */
27627   __gnat_initialize (&SEH);
27629   adainit();
27631   /* Then call Ada services in the stand-alone library */
27633   call_to_ada();
27635   adafinal();
27637 @end smallexample
27639 Note that this is not needed on x86_64-windows where the Windows
27640 native SEH support is used.
27642 @node Windows Calling Conventions
27643 @section Windows Calling Conventions
27644 @findex Stdcall
27645 @findex APIENTRY
27647 This section pertain only to Win32. On Win64 there is a single native
27648 calling convention. All convention specifiers are ignored on this
27649 platform.
27651 @menu
27652 * C Calling Convention::
27653 * Stdcall Calling Convention::
27654 * Win32 Calling Convention::
27655 * DLL Calling Convention::
27656 @end menu
27658 @noindent
27659 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27660 (callee), there are several ways to push @code{G}'s parameters on the
27661 stack and there are several possible scenarios to clean up the stack
27662 upon @code{G}'s return. A calling convention is an agreed upon software
27663 protocol whereby the responsibilities between the caller (@code{F}) and
27664 the callee (@code{G}) are clearly defined. Several calling conventions
27665 are available for Windows:
27667 @itemize @bullet
27668 @item
27669 @code{C} (Microsoft defined)
27671 @item
27672 @code{Stdcall} (Microsoft defined)
27674 @item
27675 @code{Win32} (GNAT specific)
27677 @item
27678 @code{DLL} (GNAT specific)
27679 @end itemize
27681 @node C Calling Convention
27682 @subsection @code{C} Calling Convention
27684 @noindent
27685 This is the default calling convention used when interfacing to C/C++
27686 routines compiled with either @command{gcc} or Microsoft Visual C++.
27688 In the @code{C} calling convention subprogram parameters are pushed on the
27689 stack by the caller from right to left. The caller itself is in charge of
27690 cleaning up the stack after the call. In addition, the name of a routine
27691 with @code{C} calling convention is mangled by adding a leading underscore.
27693 The name to use on the Ada side when importing (or exporting) a routine
27694 with @code{C} calling convention is the name of the routine. For
27695 instance the C function:
27697 @smallexample
27698 int get_val (long);
27699 @end smallexample
27701 @noindent
27702 should be imported from Ada as follows:
27704 @smallexample @c ada
27705 @group
27706 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27707 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
27708 @end group
27709 @end smallexample
27711 @noindent
27712 Note that in this particular case the @code{External_Name} parameter could
27713 have been omitted since, when missing, this parameter is taken to be the
27714 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27715 is missing, as in the above example, this parameter is set to be the
27716 @code{External_Name} with a leading underscore.
27718 When importing a variable defined in C, you should always use the @code{C}
27719 calling convention unless the object containing the variable is part of a
27720 DLL (in which case you should use the @code{Stdcall} calling
27721 convention, @pxref{Stdcall Calling Convention}).
27723 @node Stdcall Calling Convention
27724 @subsection @code{Stdcall} Calling Convention
27726 @noindent
27727 This convention, which was the calling convention used for Pascal
27728 programs, is used by Microsoft for all the routines in the Win32 API for
27729 efficiency reasons. It must be used to import any routine for which this
27730 convention was specified.
27732 In the @code{Stdcall} calling convention subprogram parameters are pushed
27733 on the stack by the caller from right to left. The callee (and not the
27734 caller) is in charge of cleaning the stack on routine exit. In addition,
27735 the name of a routine with @code{Stdcall} calling convention is mangled by
27736 adding a leading underscore (as for the @code{C} calling convention) and a
27737 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27738 bytes) of the parameters passed to the routine.
27740 The name to use on the Ada side when importing a C routine with a
27741 @code{Stdcall} calling convention is the name of the C routine. The leading
27742 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27743 the compiler. For instance the Win32 function:
27745 @smallexample
27746 @b{APIENTRY} int get_val (long);
27747 @end smallexample
27749 @noindent
27750 should be imported from Ada as follows:
27752 @smallexample @c ada
27753 @group
27754 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27755 @b{pragma} Import (Stdcall, Get_Val);
27756 --@i{  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"}
27757 @end group
27758 @end smallexample
27760 @noindent
27761 As for the @code{C} calling convention, when the @code{External_Name}
27762 parameter is missing, it is taken to be the name of the Ada entity in lower
27763 case. If instead of writing the above import pragma you write:
27765 @smallexample @c ada
27766 @group
27767 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27768 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27769 @end group
27770 @end smallexample
27772 @noindent
27773 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27774 of specifying the @code{External_Name} parameter you specify the
27775 @code{Link_Name} as in the following example:
27777 @smallexample @c ada
27778 @group
27779 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27780 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27781 @end group
27782 @end smallexample
27784 @noindent
27785 then the imported routine is @code{retrieve_val}, that is, there is no
27786 decoration at all. No leading underscore and no Stdcall suffix
27787 @code{@@}@code{@var{nn}}.
27789 @noindent
27790 This is especially important as in some special cases a DLL's entry
27791 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27792 name generated for a call has it.
27794 @noindent
27795 It is also possible to import variables defined in a DLL by using an
27796 import pragma for a variable. As an example, if a DLL contains a
27797 variable defined as:
27799 @smallexample
27800 int my_var;
27801 @end smallexample
27803 @noindent
27804 then, to access this variable from Ada you should write:
27806 @smallexample @c ada
27807 @group
27808 My_Var : Interfaces.C.int;
27809 @b{pragma} Import (Stdcall, My_Var);
27810 @end group
27811 @end smallexample
27813 @noindent
27814 Note that to ease building cross-platform bindings this convention
27815 will be handled as a @code{C} calling convention on non-Windows platforms.
27817 @node Win32 Calling Convention
27818 @subsection @code{Win32} Calling Convention
27820 @noindent
27821 This convention, which is GNAT-specific is fully equivalent to the
27822 @code{Stdcall} calling convention described above.
27824 @node DLL Calling Convention
27825 @subsection @code{DLL} Calling Convention
27827 @noindent
27828 This convention, which is GNAT-specific is fully equivalent to the
27829 @code{Stdcall} calling convention described above.
27831 @node Introduction to Dynamic Link Libraries (DLLs)
27832 @section Introduction to Dynamic Link Libraries (DLLs)
27833 @findex DLL
27835 @noindent
27836 A Dynamically Linked Library (DLL) is a library that can be shared by
27837 several applications running under Windows. A DLL can contain any number of
27838 routines and variables.
27840 One advantage of DLLs is that you can change and enhance them without
27841 forcing all the applications that depend on them to be relinked or
27842 recompiled. However, you should be aware than all calls to DLL routines are
27843 slower since, as you will understand below, such calls are indirect.
27845 To illustrate the remainder of this section, suppose that an application
27846 wants to use the services of a DLL @file{API.dll}. To use the services
27847 provided by @file{API.dll} you must statically link against the DLL or
27848 an import library which contains a jump table with an entry for each
27849 routine and variable exported by the DLL. In the Microsoft world this
27850 import library is called @file{API.lib}. When using GNAT this import
27851 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27852 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27854 After you have linked your application with the DLL or the import library
27855 and you run your application, here is what happens:
27857 @enumerate
27858 @item
27859 Your application is loaded into memory.
27861 @item
27862 The DLL @file{API.dll} is mapped into the address space of your
27863 application. This means that:
27865 @itemize @bullet
27866 @item
27867 The DLL will use the stack of the calling thread.
27869 @item
27870 The DLL will use the virtual address space of the calling process.
27872 @item
27873 The DLL will allocate memory from the virtual address space of the calling
27874 process.
27876 @item
27877 Handles (pointers) can be safely exchanged between routines in the DLL
27878 routines and routines in the application using the DLL.
27879 @end itemize
27881 @item
27882 The entries in the jump table (from the import library @file{libAPI.dll.a}
27883 or @file{API.lib} or automatically created when linking against a DLL)
27884 which is part of your application are initialized with the addresses
27885 of the routines and variables in @file{API.dll}.
27887 @item
27888 If present in @file{API.dll}, routines @code{DllMain} or
27889 @code{DllMainCRTStartup} are invoked. These routines typically contain
27890 the initialization code needed for the well-being of the routines and
27891 variables exported by the DLL.
27892 @end enumerate
27894 @noindent
27895 There is an additional point which is worth mentioning. In the Windows
27896 world there are two kind of DLLs: relocatable and non-relocatable
27897 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27898 in the target application address space. If the addresses of two
27899 non-relocatable DLLs overlap and these happen to be used by the same
27900 application, a conflict will occur and the application will run
27901 incorrectly. Hence, when possible, it is always preferable to use and
27902 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27903 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27904 User's Guide) removes the debugging symbols from the DLL but the DLL can
27905 still be relocated.
27907 As a side note, an interesting difference between Microsoft DLLs and
27908 Unix shared libraries, is the fact that on most Unix systems all public
27909 routines are exported by default in a Unix shared library, while under
27910 Windows it is possible (but not required) to list exported routines in
27911 a definition file (@pxref{The Definition File}).
27913 @node Using DLLs with GNAT
27914 @section Using DLLs with GNAT
27916 @menu
27917 * Creating an Ada Spec for the DLL Services::
27918 * Creating an Import Library::
27919 @end menu
27921 @noindent
27922 To use the services of a DLL, say @file{API.dll}, in your Ada application
27923 you must have:
27925 @enumerate
27926 @item
27927 The Ada spec for the routines and/or variables you want to access in
27928 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27929 header files provided with the DLL.
27931 @item
27932 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27933 mentioned an import library is a statically linked library containing the
27934 import table which will be filled at load time to point to the actual
27935 @file{API.dll} routines. Sometimes you don't have an import library for the
27936 DLL you want to use. The following sections will explain how to build
27937 one. Note that this is optional.
27939 @item
27940 The actual DLL, @file{API.dll}.
27941 @end enumerate
27943 @noindent
27944 Once you have all the above, to compile an Ada application that uses the
27945 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27946 you simply issue the command
27948 @smallexample
27949 $ gnatmake my_ada_app -largs -lAPI
27950 @end smallexample
27952 @noindent
27953 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27954 tells the GNAT linker to look for an import library. The linker will
27955 look for a library name in this specific order:
27957 @enumerate
27958 @item @file{libAPI.dll.a}
27959 @item @file{API.dll.a}
27960 @item @file{libAPI.a}
27961 @item @file{API.lib}
27962 @item @file{libAPI.dll}
27963 @item @file{API.dll}
27964 @end enumerate
27966 The first three are the GNU style import libraries. The third is the
27967 Microsoft style import libraries. The last two are the actual DLL names.
27969 Note that if the Ada package spec for @file{API.dll} contains the
27970 following pragma
27972 @smallexample @c ada
27973 @b{pragma} Linker_Options ("-lAPI");
27974 @end smallexample
27976 @noindent
27977 you do not have to add @option{-largs -lAPI} at the end of the
27978 @command{gnatmake} command.
27980 If any one of the items above is missing you will have to create it
27981 yourself. The following sections explain how to do so using as an
27982 example a fictitious DLL called @file{API.dll}.
27984 @node Creating an Ada Spec for the DLL Services
27985 @subsection Creating an Ada Spec for the DLL Services
27987 @noindent
27988 A DLL typically comes with a C/C++ header file which provides the
27989 definitions of the routines and variables exported by the DLL. The Ada
27990 equivalent of this header file is a package spec that contains definitions
27991 for the imported entities. If the DLL you intend to use does not come with
27992 an Ada spec you have to generate one such spec yourself. For example if
27993 the header file of @file{API.dll} is a file @file{api.h} containing the
27994 following two definitions:
27996 @smallexample
27997 @group
27998 @cartouche
27999 int some_var;
28000 int get (char *);
28001 @end cartouche
28002 @end group
28003 @end smallexample
28005 @noindent
28006 then the equivalent Ada spec could be:
28008 @smallexample @c ada
28009 @group
28010 @cartouche
28011 @b{with} Interfaces.C.Strings;
28012 @b{package} API @b{is}
28013    @b{use} Interfaces;
28015    Some_Var : C.int;
28016    @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
28018 @b{private}
28019    @b{pragma} Import (C, Get);
28020    @b{pragma} Import (DLL, Some_Var);
28021 @b{end} API;
28022 @end cartouche
28023 @end group
28024 @end smallexample
28026 @node Creating an Import Library
28027 @subsection Creating an Import Library
28028 @cindex Import library
28030 @menu
28031 * The Definition File::
28032 * GNAT-Style Import Library::
28033 * Microsoft-Style Import Library::
28034 @end menu
28036 @noindent
28037 If a Microsoft-style import library @file{API.lib} or a GNAT-style
28038 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
28039 with @file{API.dll} you can skip this section. You can also skip this
28040 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
28041 as in this case it is possible to link directly against the
28042 DLL. Otherwise read on.
28044 @node The Definition File
28045 @subsubsection The Definition File
28046 @cindex Definition file
28047 @findex .def
28049 @noindent
28050 As previously mentioned, and unlike Unix systems, the list of symbols
28051 that are exported from a DLL must be provided explicitly in Windows.
28052 The main goal of a definition file is precisely that: list the symbols
28053 exported by a DLL. A definition file (usually a file with a @code{.def}
28054 suffix) has the following structure:
28056 @smallexample
28057 @group
28058 @cartouche
28059 @r{[}LIBRARY @var{name}@r{]}
28060 @r{[}DESCRIPTION @var{string}@r{]}
28061 EXPORTS
28062    @var{symbol1}
28063    @var{symbol2}
28064    @dots{}
28065 @end cartouche
28066 @end group
28067 @end smallexample
28069 @table @code
28070 @item LIBRARY @var{name}
28071 This section, which is optional, gives the name of the DLL.
28073 @item DESCRIPTION @var{string}
28074 This section, which is optional, gives a description string that will be
28075 embedded in the import library.
28077 @item EXPORTS
28078 This section gives the list of exported symbols (procedures, functions or
28079 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
28080 section of @file{API.def} looks like:
28082 @smallexample
28083 @group
28084 @cartouche
28085 EXPORTS
28086    some_var
28087    get
28088 @end cartouche
28089 @end group
28090 @end smallexample
28091 @end table
28093 @noindent
28094 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
28095 (@pxref{Windows Calling Conventions}) for a Stdcall
28096 calling convention function in the exported symbols list.
28098 @noindent
28099 There can actually be other sections in a definition file, but these
28100 sections are not relevant to the discussion at hand.
28102 @node GNAT-Style Import Library
28103 @subsubsection GNAT-Style Import Library
28105 @noindent
28106 To create a static import library from @file{API.dll} with the GNAT tools
28107 you should proceed as follows:
28109 @enumerate
28110 @item
28111 Create the definition file @file{API.def} (@pxref{The Definition File}).
28112 For that use the @code{dll2def} tool as follows:
28114 @smallexample
28115 $ dll2def API.dll > API.def
28116 @end smallexample
28118 @noindent
28119 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
28120 to standard output the list of entry points in the DLL. Note that if
28121 some routines in the DLL have the @code{Stdcall} convention
28122 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
28123 suffix then you'll have to edit @file{api.def} to add it, and specify
28124 @option{-k} to @command{gnatdll} when creating the import library.
28126 @noindent
28127 Here are some hints to find the right @code{@@}@var{nn} suffix.
28129 @enumerate
28130 @item
28131 If you have the Microsoft import library (.lib), it is possible to get
28132 the right symbols by using Microsoft @code{dumpbin} tool (see the
28133 corresponding Microsoft documentation for further details).
28135 @smallexample
28136 $ dumpbin /exports api.lib
28137 @end smallexample
28139 @item
28140 If you have a message about a missing symbol at link time the compiler
28141 tells you what symbol is expected. You just have to go back to the
28142 definition file and add the right suffix.
28143 @end enumerate
28145 @item
28146 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28147 (@pxref{Using gnatdll}) as follows:
28149 @smallexample
28150 $ gnatdll -e API.def -d API.dll
28151 @end smallexample
28153 @noindent
28154 @code{gnatdll} takes as input a definition file @file{API.def} and the
28155 name of the DLL containing the services listed in the definition file
28156 @file{API.dll}. The name of the static import library generated is
28157 computed from the name of the definition file as follows: if the
28158 definition file name is @var{xyz}@code{.def}, the import library name will
28159 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
28160 @option{-e} could have been removed because the name of the definition
28161 file (before the ``@code{.def}'' suffix) is the same as the name of the
28162 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
28163 @end enumerate
28165 @node Microsoft-Style Import Library
28166 @subsubsection Microsoft-Style Import Library
28168 @noindent
28169 With GNAT you can either use a GNAT-style or Microsoft-style import
28170 library. A Microsoft import library is needed only if you plan to make an
28171 Ada DLL available to applications developed with Microsoft
28172 tools (@pxref{Mixed-Language Programming on Windows}).
28174 To create a Microsoft-style import library for @file{API.dll} you
28175 should proceed as follows:
28177 @enumerate
28178 @item
28179 Create the definition file @file{API.def} from the DLL. For this use either
28180 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
28181 tool (see the corresponding Microsoft documentation for further details).
28183 @item
28184 Build the actual import library using Microsoft's @code{lib} utility:
28186 @smallexample
28187 $ lib -machine:IX86 -def:API.def -out:API.lib
28188 @end smallexample
28190 @noindent
28191 If you use the above command the definition file @file{API.def} must
28192 contain a line giving the name of the DLL:
28194 @smallexample
28195 LIBRARY      "API"
28196 @end smallexample
28198 @noindent
28199 See the Microsoft documentation for further details about the usage of
28200 @code{lib}.
28201 @end enumerate
28203 @node Building DLLs with GNAT Project files
28204 @section Building DLLs with GNAT Project files
28205 @cindex DLLs, building
28207 @noindent
28208 There is nothing specific to Windows in the build process.
28209 @pxref{Library Projects}.
28211 @noindent
28212 Due to a system limitation, it is not possible under Windows to create threads
28213 when inside the @code{DllMain} routine which is used for auto-initialization
28214 of shared libraries, so it is not possible to have library level tasks in SALs.
28216 @node Building DLLs with GNAT
28217 @section Building DLLs with GNAT
28218 @cindex DLLs, building
28220 @noindent
28221 This section explain how to build DLLs using the GNAT built-in DLL
28222 support. With the following procedure it is straight forward to build
28223 and use DLLs with GNAT.
28225 @enumerate
28227 @item building object files
28229 The first step is to build all objects files that are to be included
28230 into the DLL. This is done by using the standard @command{gnatmake} tool.
28232 @item building the DLL
28234 To build the DLL you must use @command{gcc}'s @option{-shared} and
28235 @option{-shared-libgcc} options. It is quite simple to use this method:
28237 @smallexample
28238 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
28239 @end smallexample
28241 It is important to note that in this case all symbols found in the
28242 object files are automatically exported. It is possible to restrict
28243 the set of symbols to export by passing to @command{gcc} a definition
28244 file, @pxref{The Definition File}. For example:
28246 @smallexample
28247 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
28248 @end smallexample
28250 If you use a definition file you must export the elaboration procedures
28251 for every package that required one. Elaboration procedures are named
28252 using the package name followed by "_E".
28254 @item preparing DLL to be used
28256 For the DLL to be used by client programs the bodies must be hidden
28257 from it and the .ali set with read-only attribute. This is very important
28258 otherwise GNAT will recompile all packages and will not actually use
28259 the code in the DLL. For example:
28261 @smallexample
28262 $ mkdir apilib
28263 $ copy *.ads *.ali api.dll apilib
28264 $ attrib +R apilib\*.ali
28265 @end smallexample
28267 @end enumerate
28269 At this point it is possible to use the DLL by directly linking
28270 against it. Note that you must use the GNAT shared runtime when using
28271 GNAT shared libraries. This is achieved by using @option{-shared} binder's
28272 option.
28274 @smallexample
28275 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28276 @end smallexample
28278 @node Building DLLs with gnatdll
28279 @section Building DLLs with gnatdll
28280 @cindex DLLs, building
28282 @menu
28283 * Limitations When Using Ada DLLs from Ada::
28284 * Exporting Ada Entities::
28285 * Ada DLLs and Elaboration::
28286 * Ada DLLs and Finalization::
28287 * Creating a Spec for Ada DLLs::
28288 * Creating the Definition File::
28289 * Using gnatdll::
28290 @end menu
28292 @noindent
28293 Note that it is preferred to use GNAT Project files
28294 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28295 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28297 This section explains how to build DLLs containing Ada code using
28298 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28299 remainder of this section.
28301 The steps required to build an Ada DLL that is to be used by Ada as well as
28302 non-Ada applications are as follows:
28304 @enumerate
28305 @item
28306 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28307 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28308 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28309 skip this step if you plan to use the Ada DLL only from Ada applications.
28311 @item
28312 Your Ada code must export an initialization routine which calls the routine
28313 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28314 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28315 routine exported by the Ada DLL must be invoked by the clients of the DLL
28316 to initialize the DLL.
28318 @item
28319 When useful, the DLL should also export a finalization routine which calls
28320 routine @code{adafinal} generated by @command{gnatbind} to perform the
28321 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28322 The finalization routine exported by the Ada DLL must be invoked by the
28323 clients of the DLL when the DLL services are no further needed.
28325 @item
28326 You must provide a spec for the services exported by the Ada DLL in each
28327 of the programming languages to which you plan to make the DLL available.
28329 @item
28330 You must provide a definition file listing the exported entities
28331 (@pxref{The Definition File}).
28333 @item
28334 Finally you must use @code{gnatdll} to produce the DLL and the import
28335 library (@pxref{Using gnatdll}).
28336 @end enumerate
28338 @noindent
28339 Note that a relocatable DLL stripped using the @code{strip}
28340 binutils tool will not be relocatable anymore. To build a DLL without
28341 debug information pass @code{-largs -s} to @code{gnatdll}. This
28342 restriction does not apply to a DLL built using a Library Project.
28343 @pxref{Library Projects}.
28345 @node Limitations When Using Ada DLLs from Ada
28346 @subsection Limitations When Using Ada DLLs from Ada
28348 @noindent
28349 When using Ada DLLs from Ada applications there is a limitation users
28350 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28351 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28352 each Ada DLL includes the services of the GNAT run time that are necessary
28353 to the Ada code inside the DLL. As a result, when an Ada program uses an
28354 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28355 one in the main program.
28357 It is therefore not possible to exchange GNAT run-time objects between the
28358 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28359 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
28360 types, etc.
28362 It is completely safe to exchange plain elementary, array or record types,
28363 Windows object handles, etc.
28365 @node Exporting Ada Entities
28366 @subsection Exporting Ada Entities
28367 @cindex Export table
28369 @noindent
28370 Building a DLL is a way to encapsulate a set of services usable from any
28371 application. As a result, the Ada entities exported by a DLL should be
28372 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28373 any Ada name mangling. As an example here is an Ada package
28374 @code{API}, spec and body, exporting two procedures, a function, and a
28375 variable:
28377 @smallexample @c ada
28378 @group
28379 @cartouche
28380 @b{with} Interfaces.C; @b{use} Interfaces;
28381 @b{package} API @b{is}
28382    Count : C.int := 0;
28383    @b{function} Factorial (Val : C.int) @b{return} C.int;
28385    @b{procedure} Initialize_API;
28386    @b{procedure} Finalize_API;
28387    --@i{  Initialization & Finalization routines. More in the next section.}
28388 @b{private}
28389    @b{pragma} Export (C, Initialize_API);
28390    @b{pragma} Export (C, Finalize_API);
28391    @b{pragma} Export (C, Count);
28392    @b{pragma} Export (C, Factorial);
28393 @b{end} API;
28394 @end cartouche
28395 @end group
28396 @end smallexample
28398 @smallexample @c ada
28399 @group
28400 @cartouche
28401 @b{package} @b{body} API @b{is}
28402    @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
28403       Fact : C.int := 1;
28404    @b{begin}
28405       Count := Count + 1;
28406       @b{for} K @b{in} 1 .. Val @b{loop}
28407          Fact := Fact * K;
28408       @b{end} @b{loop};
28409       @b{return} Fact;
28410    @b{end} Factorial;
28412    @b{procedure} Initialize_API @b{is}
28413       @b{procedure} Adainit;
28414       @b{pragma} Import (C, Adainit);
28415    @b{begin}
28416       Adainit;
28417    @b{end} Initialize_API;
28419    @b{procedure} Finalize_API @b{is}
28420       @b{procedure} Adafinal;
28421       @b{pragma} Import (C, Adafinal);
28422    @b{begin}
28423       Adafinal;
28424    @b{end} Finalize_API;
28425 @b{end} API;
28426 @end cartouche
28427 @end group
28428 @end smallexample
28430 @noindent
28431 If the Ada DLL you are building will only be used by Ada applications
28432 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28433 convention. As an example, the previous package could be written as
28434 follows:
28436 @smallexample @c ada
28437 @group
28438 @cartouche
28439 @b{package} API @b{is}
28440    Count : Integer := 0;
28441    @b{function} Factorial (Val : Integer) @b{return} Integer;
28443    @b{procedure} Initialize_API;
28444    @b{procedure} Finalize_API;
28445    --@i{  Initialization and Finalization routines.}
28446 @b{end} API;
28447 @end cartouche
28448 @end group
28449 @end smallexample
28451 @smallexample @c ada
28452 @group
28453 @cartouche
28454 @b{package} @b{body} API @b{is}
28455    @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
28456       Fact : Integer := 1;
28457    @b{begin}
28458       Count := Count + 1;
28459       @b{for} K @b{in} 1 .. Val @b{loop}
28460          Fact := Fact * K;
28461       @b{end} @b{loop};
28462       @b{return} Fact;
28463    @b{end} Factorial;
28465    @dots{}
28466    --@i{  The remainder of this package body is unchanged.}
28467 @b{end} API;
28468 @end cartouche
28469 @end group
28470 @end smallexample
28472 @noindent
28473 Note that if you do not export the Ada entities with a @code{C} or
28474 @code{Stdcall} convention you will have to provide the mangled Ada names
28475 in the definition file of the Ada DLL
28476 (@pxref{Creating the Definition File}).
28478 @node Ada DLLs and Elaboration
28479 @subsection Ada DLLs and Elaboration
28480 @cindex DLLs and elaboration
28482 @noindent
28483 The DLL that you are building contains your Ada code as well as all the
28484 routines in the Ada library that are needed by it. The first thing a
28485 user of your DLL must do is elaborate the Ada code
28486 (@pxref{Elaboration Order Handling in GNAT}).
28488 To achieve this you must export an initialization routine
28489 (@code{Initialize_API} in the previous example), which must be invoked
28490 before using any of the DLL services. This elaboration routine must call
28491 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28492 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28493 @code{Initialize_Api} for an example. Note that the GNAT binder is
28494 automatically invoked during the DLL build process by the @code{gnatdll}
28495 tool (@pxref{Using gnatdll}).
28497 When a DLL is loaded, Windows systematically invokes a routine called
28498 @code{DllMain}. It would therefore be possible to call @code{adainit}
28499 directly from @code{DllMain} without having to provide an explicit
28500 initialization routine. Unfortunately, it is not possible to call
28501 @code{adainit} from the @code{DllMain} if your program has library level
28502 tasks because access to the @code{DllMain} entry point is serialized by
28503 the system (that is, only a single thread can execute ``through'' it at a
28504 time), which means that the GNAT run time will deadlock waiting for the
28505 newly created task to complete its initialization.
28507 @node Ada DLLs and Finalization
28508 @subsection Ada DLLs and Finalization
28509 @cindex DLLs and finalization
28511 @noindent
28512 When the services of an Ada DLL are no longer needed, the client code should
28513 invoke the DLL finalization routine, if available. The DLL finalization
28514 routine is in charge of releasing all resources acquired by the DLL. In the
28515 case of the Ada code contained in the DLL, this is achieved by calling
28516 routine @code{adafinal} generated by the GNAT binder
28517 (@pxref{Binding with Non-Ada Main Programs}).
28518 See the body of @code{Finalize_Api} for an
28519 example. As already pointed out the GNAT binder is automatically invoked
28520 during the DLL build process by the @code{gnatdll} tool
28521 (@pxref{Using gnatdll}).
28523 @node Creating a Spec for Ada DLLs
28524 @subsection Creating a Spec for Ada DLLs
28526 @noindent
28527 To use the services exported by the Ada DLL from another programming
28528 language (e.g.@: C), you have to translate the specs of the exported Ada
28529 entities in that language. For instance in the case of @code{API.dll},
28530 the corresponding C header file could look like:
28532 @smallexample
28533 @group
28534 @cartouche
28535 extern int *_imp__count;
28536 #define count (*_imp__count)
28537 int factorial (int);
28538 @end cartouche
28539 @end group
28540 @end smallexample
28542 @noindent
28543 It is important to understand that when building an Ada DLL to be used by
28544 other Ada applications, you need two different specs for the packages
28545 contained in the DLL: one for building the DLL and the other for using
28546 the DLL. This is because the @code{DLL} calling convention is needed to
28547 use a variable defined in a DLL, but when building the DLL, the variable
28548 must have either the @code{Ada} or @code{C} calling convention. As an
28549 example consider a DLL comprising the following package @code{API}:
28551 @smallexample @c ada
28552 @group
28553 @cartouche
28554 @b{package} API @b{is}
28555    Count : Integer := 0;
28556    @dots{}
28557    --@i{  Remainder of the package omitted.}
28558 @b{end} API;
28559 @end cartouche
28560 @end group
28561 @end smallexample
28563 @noindent
28564 After producing a DLL containing package @code{API}, the spec that
28565 must be used to import @code{API.Count} from Ada code outside of the
28566 DLL is:
28568 @smallexample @c ada
28569 @group
28570 @cartouche
28571 @b{package} API @b{is}
28572    Count : Integer;
28573    @b{pragma} Import (DLL, Count);
28574 @b{end} API;
28575 @end cartouche
28576 @end group
28577 @end smallexample
28579 @node Creating the Definition File
28580 @subsection Creating the Definition File
28582 @noindent
28583 The definition file is the last file needed to build the DLL. It lists
28584 the exported symbols. As an example, the definition file for a DLL
28585 containing only package @code{API} (where all the entities are exported
28586 with a @code{C} calling convention) is:
28588 @smallexample
28589 @group
28590 @cartouche
28591 EXPORTS
28592     count
28593     factorial
28594     finalize_api
28595     initialize_api
28596 @end cartouche
28597 @end group
28598 @end smallexample
28600 @noindent
28601 If the @code{C} calling convention is missing from package @code{API},
28602 then the definition file contains the mangled Ada names of the above
28603 entities, which in this case are:
28605 @smallexample
28606 @group
28607 @cartouche
28608 EXPORTS
28609     api__count
28610     api__factorial
28611     api__finalize_api
28612     api__initialize_api
28613 @end cartouche
28614 @end group
28615 @end smallexample
28617 @node Using gnatdll
28618 @subsection Using @code{gnatdll}
28619 @findex gnatdll
28621 @menu
28622 * gnatdll Example::
28623 * gnatdll behind the Scenes::
28624 * Using dlltool::
28625 @end menu
28627 @noindent
28628 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28629 and non-Ada sources that make up your DLL have been compiled.
28630 @code{gnatdll} is actually in charge of two distinct tasks: build the
28631 static import library for the DLL and the actual DLL. The form of the
28632 @code{gnatdll} command is
28634 @smallexample
28635 @cartouche
28636 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28637 @c Expanding @ovar macro inline (explanation in macro def comments)
28638 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28639 @end cartouche
28640 @end smallexample
28642 @noindent
28643 where @var{list-of-files} is a list of ALI and object files. The object
28644 file list must be the exact list of objects corresponding to the non-Ada
28645 sources whose services are to be included in the DLL. The ALI file list
28646 must be the exact list of ALI files for the corresponding Ada sources
28647 whose services are to be included in the DLL. If @var{list-of-files} is
28648 missing, only the static import library is generated.
28650 @noindent
28651 You may specify any of the following switches to @code{gnatdll}:
28653 @table @code
28654 @c @item -a@ovar{address}
28655 @c Expanding @ovar macro inline (explanation in macro def comments)
28656 @item -a@r{[}@var{address}@r{]}
28657 @cindex @option{-a} (@code{gnatdll})
28658 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28659 specified the default address @var{0x11000000} will be used. By default,
28660 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28661 advise the reader to build relocatable DLL.
28663 @item -b @var{address}
28664 @cindex @option{-b} (@code{gnatdll})
28665 Set the relocatable DLL base address. By default the address is
28666 @code{0x11000000}.
28668 @item -bargs @var{opts}
28669 @cindex @option{-bargs} (@code{gnatdll})
28670 Binder options. Pass @var{opts} to the binder.
28672 @item -d @var{dllfile}
28673 @cindex @option{-d} (@code{gnatdll})
28674 @var{dllfile} is the name of the DLL. This switch must be present for
28675 @code{gnatdll} to do anything. The name of the generated import library is
28676 obtained algorithmically from @var{dllfile} as shown in the following
28677 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28678 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28679 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28680 as shown in the following example:
28681 if @var{dllfile} is @code{xyz.dll}, the definition
28682 file used is @code{xyz.def}.
28684 @item -e @var{deffile}
28685 @cindex @option{-e} (@code{gnatdll})
28686 @var{deffile} is the name of the definition file.
28688 @item -g
28689 @cindex @option{-g} (@code{gnatdll})
28690 Generate debugging information. This information is stored in the object
28691 file and copied from there to the final DLL file by the linker,
28692 where it can be read by the debugger. You must use the
28693 @option{-g} switch if you plan on using the debugger or the symbolic
28694 stack traceback.
28696 @item -h
28697 @cindex @option{-h} (@code{gnatdll})
28698 Help mode. Displays @code{gnatdll} switch usage information.
28700 @item -Idir
28701 @cindex @option{-I} (@code{gnatdll})
28702 Direct @code{gnatdll} to search the @var{dir} directory for source and
28703 object files needed to build the DLL.
28704 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28706 @item -k
28707 @cindex @option{-k} (@code{gnatdll})
28708 Removes the @code{@@}@var{nn} suffix from the import library's exported
28709 names, but keeps them for the link names. You must specify this
28710 option if you want to use a @code{Stdcall} function in a DLL for which
28711 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28712 of the Windows NT DLL for example. This option has no effect when
28713 @option{-n} option is specified.
28715 @item -l @var{file}
28716 @cindex @option{-l} (@code{gnatdll})
28717 The list of ALI and object files used to build the DLL are listed in
28718 @var{file}, instead of being given in the command line. Each line in
28719 @var{file} contains the name of an ALI or object file.
28721 @item -n
28722 @cindex @option{-n} (@code{gnatdll})
28723 No Import. Do not create the import library.
28725 @item -q
28726 @cindex @option{-q} (@code{gnatdll})
28727 Quiet mode. Do not display unnecessary messages.
28729 @item -v
28730 @cindex @option{-v} (@code{gnatdll})
28731 Verbose mode. Display extra information.
28733 @item -largs @var{opts}
28734 @cindex @option{-largs} (@code{gnatdll})
28735 Linker options. Pass @var{opts} to the linker.
28736 @end table
28738 @node gnatdll Example
28739 @subsubsection @code{gnatdll} Example
28741 @noindent
28742 As an example the command to build a relocatable DLL from @file{api.adb}
28743 once @file{api.adb} has been compiled and @file{api.def} created is
28745 @smallexample
28746 $ gnatdll -d api.dll api.ali
28747 @end smallexample
28749 @noindent
28750 The above command creates two files: @file{libapi.dll.a} (the import
28751 library) and @file{api.dll} (the actual DLL). If you want to create
28752 only the DLL, just type:
28754 @smallexample
28755 $ gnatdll -d api.dll -n api.ali
28756 @end smallexample
28758 @noindent
28759 Alternatively if you want to create just the import library, type:
28761 @smallexample
28762 $ gnatdll -d api.dll
28763 @end smallexample
28765 @node gnatdll behind the Scenes
28766 @subsubsection @code{gnatdll} behind the Scenes
28768 @noindent
28769 This section details the steps involved in creating a DLL. @code{gnatdll}
28770 does these steps for you. Unless you are interested in understanding what
28771 goes on behind the scenes, you should skip this section.
28773 We use the previous example of a DLL containing the Ada package @code{API},
28774 to illustrate the steps necessary to build a DLL. The starting point is a
28775 set of objects that will make up the DLL and the corresponding ALI
28776 files. In the case of this example this means that @file{api.o} and
28777 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28778 the following:
28780 @enumerate
28781 @item
28782 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28783 the information necessary to generate relocation information for the
28784 DLL.
28786 @smallexample
28787 @group
28788 $ gnatbind -n api
28789 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28790 @end group
28791 @end smallexample
28793 @noindent
28794 In addition to the base file, the @command{gnatlink} command generates an
28795 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28796 asks @command{gnatlink} to generate the routines @code{DllMain} and
28797 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28798 is loaded into memory.
28800 @item
28801 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28802 export table (@file{api.exp}). The export table contains the relocation
28803 information in a form which can be used during the final link to ensure
28804 that the Windows loader is able to place the DLL anywhere in memory.
28806 @smallexample
28807 @group
28808 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28809           --output-exp api.exp
28810 @end group
28811 @end smallexample
28813 @item
28814 @code{gnatdll} builds the base file using the new export table. Note that
28815 @command{gnatbind} must be called once again since the binder generated file
28816 has been deleted during the previous call to @command{gnatlink}.
28818 @smallexample
28819 @group
28820 $ gnatbind -n api
28821 $ gnatlink api -o api.jnk api.exp -mdll
28822       -Wl,--base-file,api.base
28823 @end group
28824 @end smallexample
28826 @item
28827 @code{gnatdll} builds the new export table using the new base file and
28828 generates the DLL import library @file{libAPI.dll.a}.
28830 @smallexample
28831 @group
28832 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28833           --output-exp api.exp --output-lib libAPI.a
28834 @end group
28835 @end smallexample
28837 @item
28838 Finally @code{gnatdll} builds the relocatable DLL using the final export
28839 table.
28841 @smallexample
28842 @group
28843 $ gnatbind -n api
28844 $ gnatlink api api.exp -o api.dll -mdll
28845 @end group
28846 @end smallexample
28847 @end enumerate
28849 @node Using dlltool
28850 @subsubsection Using @code{dlltool}
28852 @noindent
28853 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28854 DLLs and static import libraries. This section summarizes the most
28855 common @code{dlltool} switches. The form of the @code{dlltool} command
28858 @smallexample
28859 @c $ dlltool @ovar{switches}
28860 @c Expanding @ovar macro inline (explanation in macro def comments)
28861 $ dlltool @r{[}@var{switches}@r{]}
28862 @end smallexample
28864 @noindent
28865 @code{dlltool} switches include:
28867 @table @option
28868 @item --base-file @var{basefile}
28869 @cindex @option{--base-file} (@command{dlltool})
28870 Read the base file @var{basefile} generated by the linker. This switch
28871 is used to create a relocatable DLL.
28873 @item --def @var{deffile}
28874 @cindex @option{--def} (@command{dlltool})
28875 Read the definition file.
28877 @item --dllname @var{name}
28878 @cindex @option{--dllname} (@command{dlltool})
28879 Gives the name of the DLL. This switch is used to embed the name of the
28880 DLL in the static import library generated by @code{dlltool} with switch
28881 @option{--output-lib}.
28883 @item -k
28884 @cindex @option{-k} (@command{dlltool})
28885 Kill @code{@@}@var{nn} from exported names
28886 (@pxref{Windows Calling Conventions}
28887 for a discussion about @code{Stdcall}-style symbols.
28889 @item --help
28890 @cindex @option{--help} (@command{dlltool})
28891 Prints the @code{dlltool} switches with a concise description.
28893 @item --output-exp @var{exportfile}
28894 @cindex @option{--output-exp} (@command{dlltool})
28895 Generate an export file @var{exportfile}. The export file contains the
28896 export table (list of symbols in the DLL) and is used to create the DLL.
28898 @item --output-lib @var{libfile}
28899 @cindex @option{--output-lib} (@command{dlltool})
28900 Generate a static import library @var{libfile}.
28902 @item -v
28903 @cindex @option{-v} (@command{dlltool})
28904 Verbose mode.
28906 @item --as @var{assembler-name}
28907 @cindex @option{--as} (@command{dlltool})
28908 Use @var{assembler-name} as the assembler. The default is @code{as}.
28909 @end table
28911 @node GNAT and Windows Resources
28912 @section GNAT and Windows Resources
28913 @cindex Resources, windows
28915 @menu
28916 * Building Resources::
28917 * Compiling Resources::
28918 * Using Resources::
28919 @end menu
28921 @noindent
28922 Resources are an easy way to add Windows specific objects to your
28923 application. The objects that can be added as resources include:
28925 @itemize @bullet
28926 @item menus
28928 @item accelerators
28930 @item dialog boxes
28932 @item string tables
28934 @item bitmaps
28936 @item cursors
28938 @item icons
28940 @item fonts
28942 @item version information
28943 @end itemize
28945 For example, a version information resource can be defined as follow and
28946 embedded into an executable or DLL:
28948 A version information resource can be used to embed information into an
28949 executable or a DLL. These information can be viewed using the file properties
28950 from the Windows Explorer. Here is an example of a version information
28951 resource:
28953 @smallexample
28954 @group
28955 1 VERSIONINFO
28956 FILEVERSION     1,0,0,0
28957 PRODUCTVERSION  1,0,0,0
28958 BEGIN
28959   BLOCK "StringFileInfo"
28960   BEGIN
28961     BLOCK "080904E4"
28962     BEGIN
28963       VALUE "CompanyName", "My Company Name"
28964       VALUE "FileDescription", "My application"
28965       VALUE "FileVersion", "1.0"
28966       VALUE "InternalName", "my_app"
28967       VALUE "LegalCopyright", "My Name"
28968       VALUE "OriginalFilename", "my_app.exe"
28969       VALUE "ProductName", "My App"
28970       VALUE "ProductVersion", "1.0"
28971     END
28972   END
28974   BLOCK "VarFileInfo"
28975   BEGIN
28976     VALUE "Translation", 0x809, 1252
28977   END
28979 @end group
28980 @end smallexample
28982 The value @code{0809} (langID) is for the U.K English language and
28983 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28984 multilingual.
28986 @noindent
28987 This section explains how to build, compile and use resources. Note that this
28988 section does not cover all resource objects, for a complete description see
28989 the corresponding Microsoft documentation.
28991 @node Building Resources
28992 @subsection Building Resources
28993 @cindex Resources, building
28995 @noindent
28996 A resource file is an ASCII file. By convention resource files have an
28997 @file{.rc} extension.
28998 The easiest way to build a resource file is to use Microsoft tools
28999 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
29000 @code{dlgedit.exe} to build dialogs.
29001 It is always possible to build an @file{.rc} file yourself by writing a
29002 resource script.
29004 It is not our objective to explain how to write a resource file. A
29005 complete description of the resource script language can be found in the
29006 Microsoft documentation.
29008 @node Compiling Resources
29009 @subsection Compiling Resources
29010 @findex rc
29011 @findex windres
29012 @cindex Resources, compiling
29014 @noindent
29015 This section describes how to build a GNAT-compatible (COFF) object file
29016 containing the resources. This is done using the Resource Compiler
29017 @code{windres} as follows:
29019 @smallexample
29020 $ windres -i myres.rc -o myres.o
29021 @end smallexample
29023 @noindent
29024 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
29025 file. You can specify an alternate preprocessor (usually named
29026 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
29027 parameter. A list of all possible options may be obtained by entering
29028 the command @code{windres} @option{--help}.
29030 It is also possible to use the Microsoft resource compiler @code{rc.exe}
29031 to produce a @file{.res} file (binary resource file). See the
29032 corresponding Microsoft documentation for further details. In this case
29033 you need to use @code{windres} to translate the @file{.res} file to a
29034 GNAT-compatible object file as follows:
29036 @smallexample
29037 $ windres -i myres.res -o myres.o
29038 @end smallexample
29040 @node Using Resources
29041 @subsection Using Resources
29042 @cindex Resources, using
29044 @noindent
29045 To include the resource file in your program just add the
29046 GNAT-compatible object file for the resource(s) to the linker
29047 arguments. With @command{gnatmake} this is done by using the @option{-largs}
29048 option:
29050 @smallexample
29051 $ gnatmake myprog -largs myres.o
29052 @end smallexample
29054 @node Debugging a DLL
29055 @section Debugging a DLL
29056 @cindex DLL debugging
29058 @menu
29059 * Program and DLL Both Built with GCC/GNAT::
29060 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
29061 @end menu
29063 @noindent
29064 Debugging a DLL is similar to debugging a standard program. But
29065 we have to deal with two different executable parts: the DLL and the
29066 program that uses it. We have the following four possibilities:
29068 @enumerate 1
29069 @item
29070 The program and the DLL are built with @code{GCC/GNAT}.
29071 @item
29072 The program is built with foreign tools and the DLL is built with
29073 @code{GCC/GNAT}.
29074 @item
29075 The program is built with @code{GCC/GNAT} and the DLL is built with
29076 foreign tools.
29077 @end enumerate
29079 @noindent
29080 In this section we address only cases one and two above.
29081 There is no point in trying to debug
29082 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
29083 information in it. To do so you must use a debugger compatible with the
29084 tools suite used to build the DLL.
29086 @node Program and DLL Both Built with GCC/GNAT
29087 @subsection Program and DLL Both Built with GCC/GNAT
29089 @noindent
29090 This is the simplest case. Both the DLL and the program have @code{GDB}
29091 compatible debugging information. It is then possible to break anywhere in
29092 the process. Let's suppose here that the main procedure is named
29093 @code{ada_main} and that in the DLL there is an entry point named
29094 @code{ada_dll}.
29096 @noindent
29097 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
29098 program must have been built with the debugging information (see GNAT -g
29099 switch). Here are the step-by-step instructions for debugging it:
29101 @enumerate 1
29102 @item Launch @code{GDB} on the main program.
29104 @smallexample
29105 $ gdb -nw ada_main
29106 @end smallexample
29108 @item Start the program and stop at the beginning of the main procedure
29110 @smallexample
29111 (gdb) start
29112 @end smallexample
29114 @noindent
29115 This step is required to be able to set a breakpoint inside the DLL. As long
29116 as the program is not run, the DLL is not loaded. This has the
29117 consequence that the DLL debugging information is also not loaded, so it is not
29118 possible to set a breakpoint in the DLL.
29120 @item Set a breakpoint inside the DLL
29122 @smallexample
29123 (gdb) break ada_dll
29124 (gdb) cont
29125 @end smallexample
29127 @end enumerate
29129 @noindent
29130 At this stage a breakpoint is set inside the DLL. From there on
29131 you can use the standard approach to debug the whole program
29132 (@pxref{Running and Debugging Ada Programs}).
29134 @ignore
29135 @c This used to work, probably because the DLLs were non-relocatable
29136 @c keep this section around until the problem is sorted out.
29138 To break on the @code{DllMain} routine it is not possible to follow
29139 the procedure above. At the time the program stop on @code{ada_main}
29140 the @code{DllMain} routine as already been called. Either you can use
29141 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
29143 @enumerate 1
29144 @item Launch @code{GDB} on the main program.
29146 @smallexample
29147 $ gdb ada_main
29148 @end smallexample
29150 @item Load DLL symbols
29152 @smallexample
29153 (gdb) add-sym api.dll
29154 @end smallexample
29156 @item Set a breakpoint inside the DLL
29158 @smallexample
29159 (gdb) break ada_dll.adb:45
29160 @end smallexample
29162 Note that at this point it is not possible to break using the routine symbol
29163 directly as the program is not yet running. The solution is to break
29164 on the proper line (break in @file{ada_dll.adb} line 45).
29166 @item Start the program
29168 @smallexample
29169 (gdb) run
29170 @end smallexample
29172 @end enumerate
29173 @end ignore
29175 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
29176 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
29178 @menu
29179 * Debugging the DLL Directly::
29180 * Attaching to a Running Process::
29181 @end menu
29183 @noindent
29184 In this case things are slightly more complex because it is not possible to
29185 start the main program and then break at the beginning to load the DLL and the
29186 associated DLL debugging information. It is not possible to break at the
29187 beginning of the program because there is no @code{GDB} debugging information,
29188 and therefore there is no direct way of getting initial control. This
29189 section addresses this issue by describing some methods that can be used
29190 to break somewhere in the DLL to debug it.
29192 @noindent
29193 First suppose that the main procedure is named @code{main} (this is for
29194 example some C code built with Microsoft Visual C) and that there is a
29195 DLL named @code{test.dll} containing an Ada entry point named
29196 @code{ada_dll}.
29198 @noindent
29199 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
29200 been built with debugging information (see GNAT -g option).
29202 @node Debugging the DLL Directly
29203 @subsubsection Debugging the DLL Directly
29205 @enumerate 1
29206 @item
29207 Find out the executable starting address
29209 @smallexample
29210 $ objdump --file-header main.exe
29211 @end smallexample
29213 The starting address is reported on the last line. For example:
29215 @smallexample
29216 main.exe:     file format pei-i386
29217 architecture: i386, flags 0x0000010a:
29218 EXEC_P, HAS_DEBUG, D_PAGED
29219 start address 0x00401010
29220 @end smallexample
29222 @item
29223 Launch the debugger on the executable.
29225 @smallexample
29226 $ gdb main.exe
29227 @end smallexample
29229 @item
29230 Set a breakpoint at the starting address, and launch the program.
29232 @smallexample
29233 $ (gdb) break *0x00401010
29234 $ (gdb) run
29235 @end smallexample
29237 The program will stop at the given address.
29239 @item
29240 Set a breakpoint on a DLL subroutine.
29242 @smallexample
29243 (gdb) break ada_dll.adb:45
29244 @end smallexample
29246 Or if you want to break using a symbol on the DLL, you need first to
29247 select the Ada language (language used by the DLL).
29249 @smallexample
29250 (gdb) set language ada
29251 (gdb) break ada_dll
29252 @end smallexample
29254 @item
29255 Continue the program.
29257 @smallexample
29258 (gdb) cont
29259 @end smallexample
29261 @noindent
29262 This will run the program until it reaches the breakpoint that has been
29263 set. From that point you can use the standard way to debug a program
29264 as described in (@pxref{Running and Debugging Ada Programs}).
29266 @end enumerate
29268 @noindent
29269 It is also possible to debug the DLL by attaching to a running process.
29271 @node Attaching to a Running Process
29272 @subsubsection Attaching to a Running Process
29273 @cindex DLL debugging, attach to process
29275 @noindent
29276 With @code{GDB} it is always possible to debug a running process by
29277 attaching to it. It is possible to debug a DLL this way. The limitation
29278 of this approach is that the DLL must run long enough to perform the
29279 attach operation. It may be useful for instance to insert a time wasting
29280 loop in the code of the DLL to meet this criterion.
29282 @enumerate 1
29284 @item Launch the main program @file{main.exe}.
29286 @smallexample
29287 $ main
29288 @end smallexample
29290 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29291 that the process PID for @file{main.exe} is 208.
29293 @item Launch gdb.
29295 @smallexample
29296 $ gdb
29297 @end smallexample
29299 @item Attach to the running process to be debugged.
29301 @smallexample
29302 (gdb) attach 208
29303 @end smallexample
29305 @item Load the process debugging information.
29307 @smallexample
29308 (gdb) symbol-file main.exe
29309 @end smallexample
29311 @item Break somewhere in the DLL.
29313 @smallexample
29314 (gdb) break ada_dll
29315 @end smallexample
29317 @item Continue process execution.
29319 @smallexample
29320 (gdb) cont
29321 @end smallexample
29323 @end enumerate
29325 @noindent
29326 This last step will resume the process execution, and stop at
29327 the breakpoint we have set. From there you can use the standard
29328 approach to debug a program as described in
29329 (@pxref{Running and Debugging Ada Programs}).
29331 @node Setting Stack Size from gnatlink
29332 @section Setting Stack Size from @command{gnatlink}
29334 @noindent
29335 It is possible to specify the program stack size at link time. On modern
29336 versions of Windows, starting with XP, this is mostly useful to set the size of
29337 the main stack (environment task). The other task stacks are set with pragma
29338 Storage_Size or with the @command{gnatbind -d} command.
29340 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
29341 reserve size of individual tasks, the link-time stack size applies to all
29342 tasks, and pragma Storage_Size has no effect.
29343 In particular, Stack Overflow checks are made against this
29344 link-time specified size.
29346 This setting can be done with
29347 @command{gnatlink} using either:
29349 @itemize @bullet
29351 @item using @option{-Xlinker} linker option
29353 @smallexample
29354 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29355 @end smallexample
29357 This sets the stack reserve size to 0x10000 bytes and the stack commit
29358 size to 0x1000 bytes.
29360 @item using @option{-Wl} linker option
29362 @smallexample
29363 $ gnatlink hello -Wl,--stack=0x1000000
29364 @end smallexample
29366 This sets the stack reserve size to 0x1000000 bytes. Note that with
29367 @option{-Wl} option it is not possible to set the stack commit size
29368 because the coma is a separator for this option.
29370 @end itemize
29372 @node Setting Heap Size from gnatlink
29373 @section Setting Heap Size from @command{gnatlink}
29375 @noindent
29376 Under Windows systems, it is possible to specify the program heap size from
29377 @command{gnatlink} using either:
29379 @itemize @bullet
29381 @item using @option{-Xlinker} linker option
29383 @smallexample
29384 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29385 @end smallexample
29387 This sets the heap reserve size to 0x10000 bytes and the heap commit
29388 size to 0x1000 bytes.
29390 @item using @option{-Wl} linker option
29392 @smallexample
29393 $ gnatlink hello -Wl,--heap=0x1000000
29394 @end smallexample
29396 This sets the heap reserve size to 0x1000000 bytes. Note that with
29397 @option{-Wl} option it is not possible to set the heap commit size
29398 because the coma is a separator for this option.
29400 @end itemize
29402 @node Mac OS Topics
29403 @appendix Mac OS Topics
29404 @cindex OS X
29406 @noindent
29407 This chapter describes topics that are specific to Apple's OS X
29408 platform.
29410 @menu
29411 * Codesigning the Debugger::
29412 @end menu
29414 @node Codesigning the Debugger
29415 @section Codesigning the Debugger
29417 @noindent
29418 The Darwin Kernel requires the debugger to have special permissions
29419 before it is allowed to control other processes. These permissions
29420 are granted by codesigning the GDB executable. Without these
29421 permissions, the debugger will report error messages such as:
29423 @smallexample
29424 Starting program: /x/y/foo
29425 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
29426  (please check gdb is codesigned - see taskgated(8))
29427 @end smallexample
29429 Codesigning requires a certificate.  The following procedure explains
29430 how to create one:
29432 @itemize @bullet
29433 @item Start the Keychain Access application (in
29434 /Applications/Utilities/Keychain Access.app)
29436 @item Select the Keychain Access -> Certificate Assistant ->
29437 Create a Certificate... menu
29439 @item Then:
29441 @itemize @bullet
29442 @item Choose a name for the new certificate (this procedure will use
29443 "gdb-cert" as an example)
29445 @item Set "Identity Type" to "Self Signed Root"
29447 @item Set "Certificate Type" to "Code Signing"
29449 @item Activate the "Let me override defaults" option
29451 @end itemize
29453 @item Click several times on "Continue" until the "Specify a Location
29454 For The Certificate" screen appears, then set "Keychain" to "System"
29456 @item Click on "Continue" until the certificate is created
29458 @item Finally, in the view, double-click on the new certificate,
29459 and set "When using this certificate" to "Always Trust"
29461 @item Exit the Keychain Access application and restart the computer
29462 (this is unfortunately required)
29464 @end itemize
29466 Once a certificate has been created, the debugger can be codesigned
29467 as follow. In a Terminal, run the following command...
29469 @smallexample
29470 codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
29471 @end smallexample
29473 ... where "gdb-cert" should be replaced by the actual certificate
29474 name chosen above, and <gnat_install_prefix> should be replaced by
29475 the location where you installed GNAT.  Also, be sure that users are
29476 in the Unix group @samp{_developer}.
29478 @c **********************************
29479 @c * GNU Free Documentation License *
29480 @c **********************************
29481 @include fdl.texi
29482 @c GNU Free Documentation License
29484 @node Index
29485 @unnumbered Index
29487 @printindex cp
29489 @contents
29490 @c Put table of contents at end, otherwise it precedes the "title page" in
29491 @c the .txt version
29492 @c Edit the pdf file to move the contents to the beginning, after the title
29493 @c page
29495 @bye