2014-09-15 Andreas Krebbel <Andreas.Krebbel@de.ibm.com>
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob913330d7370b1af10949a4fb3ee8f65d93d24d6d
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) and two public
2964 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  @b{private}:
2972    int Age_Count;
2974 @end smallexample
2976 Abstract interface types are defined in C++ by means of classes with pure
2977 virtual functions and no data members. In our example we will use two
2978 interfaces that provide support for the common management of @code{Carnivore}
2979 and @code{Domestic} animals:
2981 @smallexample
2982 @b{class} Carnivore @{
2983 @b{public}:
2984    @b{virtual} int Number_Of_Teeth () = 0;
2987 @b{class} Domestic @{
2988 @b{public}:
2989    @b{virtual void} Set_Owner (char* Name) = 0;
2991 @end smallexample
2993 Using these declarations, we can now say that a @code{Dog} is an animal that is
2994 both Carnivore and Domestic, that is:
2996 @smallexample
2997 @b{class} Dog : Animal, Carnivore, Domestic @{
2998  @b{public}:
2999    @b{virtual} int  Number_Of_Teeth ();
3000    @b{virtual} void Set_Owner (char* Name);
3002    Dog(); // Constructor
3003  @b{private}:
3004    int  Tooth_Count;
3005    char *Owner;
3007 @end smallexample
3009 In the following examples we will assume that the previous declarations are
3010 located in a file named @code{animals.h}. The following package demonstrates
3011 how to import these C++ declarations from the Ada side:
3013 @smallexample @c ada
3014 @b{with} Interfaces.C.Strings; @b{use} Interfaces.C.Strings;
3015 @b{package} Animals @b{is}
3016   @b{type} Carnivore @b{is} interface;
3017   @b{pragma} Convention (C_Plus_Plus, Carnivore);
3018   @b{function} Number_Of_Teeth (X : Carnivore)
3019      @b{return} Natural @b{is} @b{abstract};
3021   @b{type} Domestic @b{is} interface;
3022   @b{pragma} Convention (C_Plus_Plus, Set_Owner);
3023   @b{procedure} Set_Owner
3024     (X    : @b{in} @b{out} Domestic;
3025      Name : Chars_Ptr) @b{is} @b{abstract};
3027   @b{type} Animal @b{is} @b{tagged} @b{record}
3028     Age : Natural := 0;
3029   @b{end} @b{record};
3030   @b{pragma} Import (C_Plus_Plus, Animal);
3032   @b{procedure} Set_Age (X : @b{in} @b{out} Animal; Age : Integer);
3033   @b{pragma} Import (C_Plus_Plus, Set_Age);
3035   @b{function} Age (X : Animal) @b{return} Integer;
3036   @b{pragma} Import (C_Plus_Plus, Age);
3038   @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
3039     Tooth_Count : Natural;
3040     Owner       : String (1 .. 30);
3041   @b{end} @b{record};
3042   @b{pragma} Import (C_Plus_Plus, Dog);
3044   @b{function} Number_Of_Teeth (A : Dog) @b{return} Integer;
3045   @b{pragma} Import (C_Plus_Plus, Number_Of_Teeth);
3047   @b{procedure} Set_Owner (A : @b{in} @b{out} Dog; Name : Chars_Ptr);
3048   @b{pragma} Import (C_Plus_Plus, Set_Owner);
3050   @b{function} New_Dog @b{return} Dog;
3051   @b{pragma} CPP_Constructor (New_Dog);
3052   @b{pragma} Import (CPP, New_Dog, "_ZN3DogC2Ev");
3053 @b{end} Animals;
3054 @end smallexample
3056 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3057 interfacing with these C++ classes is easy. The only requirement is that all
3058 the primitives and components must be declared exactly in the same order in
3059 the two languages.
3061 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3062 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3063 the arguments to the called primitives will be the same as for C++. For the
3064 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3065 to indicate that they have been defined on the C++ side; this is required
3066 because the dispatch table associated with these tagged types will be built
3067 in the C++ side and therefore will not contain the predefined Ada primitives
3068 which Ada would otherwise expect.
3070 As the reader can see there is no need to indicate the C++ mangled names
3071 associated with each subprogram because it is assumed that all the calls to
3072 these primitives will be dispatching calls. The only exception is the
3073 constructor, which must be registered with the compiler by means of
3074 @code{pragma CPP_Constructor} and needs to provide its associated C++
3075 mangled name because the Ada compiler generates direct calls to it.
3077 With the above packages we can now declare objects of type Dog on the Ada side
3078 and dispatch calls to the corresponding subprograms on the C++ side. We can
3079 also extend the tagged type Dog with further fields and primitives, and
3080 override some of its C++ primitives on the Ada side. For example, here we have
3081 a type derivation defined on the Ada side that inherits all the dispatching
3082 primitives of the ancestor from the C++ side.
3084 @smallexample
3085 @b{with} Animals; @b{use} Animals;
3086 @b{package} Vaccinated_Animals @b{is}
3087   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3088   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3089 @b{end} Vaccinated_Animals;
3090 @end smallexample
3092 It is important to note that, because of the ABI compatibility, the programmer
3093 does not need to add any further information to indicate either the object
3094 layout or the dispatch table entry associated with each dispatching operation.
3096 Now let us define all the types and constructors on the Ada side and export
3097 them to C++, using the same hierarchy of our previous example:
3099 @smallexample @c ada
3100 @b{with} Interfaces.C.Strings;
3101 @b{use} Interfaces.C.Strings;
3102 @b{package} Animals @b{is}
3103   @b{type} Carnivore @b{is} interface;
3104   @b{pragma} Convention (C_Plus_Plus, Carnivore);
3105   @b{function} Number_Of_Teeth (X : Carnivore)
3106      @b{return} Natural @b{is} @b{abstract};
3108   @b{type} Domestic @b{is} interface;
3109   @b{pragma} Convention (C_Plus_Plus, Set_Owner);
3110   @b{procedure} Set_Owner
3111     (X    : @b{in} @b{out} Domestic;
3112      Name : Chars_Ptr) @b{is} @b{abstract};
3114   @b{type} Animal @b{is} @b{tagged} @b{record}
3115     Age : Natural := 0;
3116   @b{end} @b{record};
3117   @b{pragma} Convention (C_Plus_Plus, Animal);
3119   @b{procedure} Set_Age (X : @b{in} @b{out} Animal; Age : Integer);
3120   @b{pragma} Export (C_Plus_Plus, Set_Age);
3122   @b{function} Age (X : Animal) @b{return} Integer;
3123   @b{pragma} Export (C_Plus_Plus, Age);
3125   @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
3126     Tooth_Count : Natural;
3127     Owner       : String (1 .. 30);
3128   @b{end} @b{record};
3129   @b{pragma} Convention (C_Plus_Plus, Dog);
3131   @b{function} Number_Of_Teeth (A : Dog) @b{return} Integer;
3132   @b{pragma} Export (C_Plus_Plus, Number_Of_Teeth);
3134   @b{procedure} Set_Owner (A : @b{in} @b{out} Dog; Name : Chars_Ptr);
3135   @b{pragma} Export (C_Plus_Plus, Set_Owner);
3137   @b{function} New_Dog @b{return} Dog'Class;
3138   @b{pragma} Export (C_Plus_Plus, New_Dog);
3139 @b{end} Animals;
3140 @end smallexample
3142 Compared with our previous example the only difference is the use of
3143 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3144 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3145 nothing else to be done; as explained above, the only requirement is that all
3146 the primitives and components are declared in exactly the same order.
3148 For completeness, let us see a brief C++ main program that uses the
3149 declarations available in @code{animals.h} (presented in our first example) to
3150 import and use the declarations from the Ada side, properly initializing and
3151 finalizing the Ada run-time system along the way:
3153 @smallexample
3154 @b{#include} "animals.h"
3155 @b{#include} <iostream>
3156 @b{using namespace} std;
3158 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3159 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3160 void Check_Animal (Animal *obj)       @{@dots{}@}
3161 void Check_Dog (Dog *obj)             @{@dots{}@}
3163 @b{extern} "C" @{
3164   void adainit (void);
3165   void adafinal (void);
3166   Dog* new_dog ();
3169 void test ()
3171   Dog *obj = new_dog();  // Ada constructor
3172   Check_Carnivore (obj); // Check secondary DT
3173   Check_Domestic (obj);  // Check secondary DT
3174   Check_Animal (obj);    // Check primary DT
3175   Check_Dog (obj);       // Check primary DT
3178 int main ()
3180   adainit ();  test();  adafinal ();
3181   return 0;
3183 @end smallexample
3185 @node Comparison between GNAT and C/C++ Compilation Models
3186 @section Comparison between GNAT and C/C++ Compilation Models
3188 @noindent
3189 The GNAT model of compilation is close to the C and C++ models. You can
3190 think of Ada specs as corresponding to header files in C. As in C, you
3191 don't need to compile specs; they are compiled when they are used. The
3192 Ada @code{with} is similar in effect to the @code{#include} of a C
3193 header.
3195 One notable difference is that, in Ada, you may compile specs separately
3196 to check them for semantic and syntactic accuracy. This is not always
3197 possible with C headers because they are fragments of programs that have
3198 less specific syntactic or semantic rules.
3200 The other major difference is the requirement for running the binder,
3201 which performs two important functions. First, it checks for
3202 consistency. In C or C++, the only defense against assembling
3203 inconsistent programs lies outside the compiler, in a makefile, for
3204 example. The binder satisfies the Ada requirement that it be impossible
3205 to construct an inconsistent program when the compiler is used in normal
3206 mode.
3208 @cindex Elaboration order control
3209 The other important function of the binder is to deal with elaboration
3210 issues. There are also elaboration issues in C++ that are handled
3211 automatically. This automatic handling has the advantage of being
3212 simpler to use, but the C++ programmer has no control over elaboration.
3213 Where @code{gnatbind} might complain there was no valid order of
3214 elaboration, a C++ compiler would simply construct a program that
3215 malfunctioned at run time.
3217 @node Comparison between GNAT and Conventional Ada Library Models
3218 @section Comparison between GNAT and Conventional Ada Library Models
3220 @noindent
3221 This section is intended for Ada programmers who have
3222 used an Ada compiler implementing the traditional Ada library
3223 model, as described in the Ada Reference Manual.
3225 @cindex GNAT library
3226 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3227 source files themselves acts as the library. Compiling Ada programs does
3228 not generate any centralized information, but rather an object file and
3229 a ALI file, which are of interest only to the binder and linker.
3230 In a traditional system, the compiler reads information not only from
3231 the source file being compiled, but also from the centralized library.
3232 This means that the effect of a compilation depends on what has been
3233 previously compiled. In particular:
3235 @itemize @bullet
3236 @item
3237 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3238 to the version of the unit most recently compiled into the library.
3240 @item
3241 Inlining is effective only if the necessary body has already been
3242 compiled into the library.
3244 @item
3245 Compiling a unit may obsolete other units in the library.
3246 @end itemize
3248 @noindent
3249 In GNAT, compiling one unit never affects the compilation of any other
3250 units because the compiler reads only source files. Only changes to source
3251 files can affect the results of a compilation. In particular:
3253 @itemize @bullet
3254 @item
3255 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3256 to the source version of the unit that is currently accessible to the
3257 compiler.
3259 @item
3260 @cindex Inlining
3261 Inlining requires the appropriate source files for the package or
3262 subprogram bodies to be available to the compiler. Inlining is always
3263 effective, independent of the order in which units are complied.
3265 @item
3266 Compiling a unit never affects any other compilations. The editing of
3267 sources may cause previous compilations to be out of date if they
3268 depended on the source file being modified.
3269 @end itemize
3271 @noindent
3272 The most important result of these differences is that order of compilation
3273 is never significant in GNAT. There is no situation in which one is
3274 required to do one compilation before another. What shows up as order of
3275 compilation requirements in the traditional Ada library becomes, in
3276 GNAT, simple source dependencies; in other words, there is only a set
3277 of rules saying what source files must be present when a file is
3278 compiled.
3281 @c *************************
3282 @node Compiling with gcc
3283 @chapter Compiling with @command{gcc}
3285 @noindent
3286 This chapter discusses how to compile Ada programs using the @command{gcc}
3287 command. It also describes the set of switches
3288 that can be used to control the behavior of the compiler.
3289 @menu
3290 * Compiling Programs::
3291 * Switches for gcc::
3292 * Search Paths and the Run-Time Library (RTL)::
3293 * Order of Compilation Issues::
3294 * Examples::
3295 @end menu
3297 @node Compiling Programs
3298 @section Compiling Programs
3300 @noindent
3301 The first step in creating an executable program is to compile the units
3302 of the program using the @command{gcc} command. You must compile the
3303 following files:
3305 @itemize @bullet
3306 @item
3307 the body file (@file{.adb}) for a library level subprogram or generic
3308 subprogram
3310 @item
3311 the spec file (@file{.ads}) for a library level package or generic
3312 package that has no body
3314 @item
3315 the body file (@file{.adb}) for a library level package
3316 or generic package that has a body
3318 @end itemize
3320 @noindent
3321 You need @emph{not} compile the following files
3323 @itemize @bullet
3325 @item
3326 the spec of a library unit which has a body
3328 @item
3329 subunits
3330 @end itemize
3332 @noindent
3333 because they are compiled as part of compiling related units. GNAT
3334 package specs
3335 when the corresponding body is compiled, and subunits when the parent is
3336 compiled.
3338 @cindex cannot generate code
3339 If you attempt to compile any of these files, you will get one of the
3340 following error messages (where @var{fff} is the name of the file you
3341 compiled):
3343 @smallexample
3344 cannot generate code for file @var{fff} (package spec)
3345 to check package spec, use -gnatc
3347 cannot generate code for file @var{fff} (missing subunits)
3348 to check parent unit, use -gnatc
3350 cannot generate code for file @var{fff} (subprogram spec)
3351 to check subprogram spec, use -gnatc
3353 cannot generate code for file @var{fff} (subunit)
3354 to check subunit, use -gnatc
3355 @end smallexample
3357 @noindent
3358 As indicated by the above error messages, if you want to submit
3359 one of these files to the compiler to check for correct semantics
3360 without generating code, then use the @option{-gnatc} switch.
3362 The basic command for compiling a file containing an Ada unit is
3364 @smallexample
3365 @c $ gcc -c @ovar{switches} @file{file name}
3366 @c Expanding @ovar macro inline (explanation in macro def comments)
3367 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3368 @end smallexample
3370 @noindent
3371 where @var{file name} is the name of the Ada file (usually
3372 having an extension
3373 @file{.ads} for a spec or @file{.adb} for a body).
3374 You specify the
3375 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3376 The result of a successful compilation is an object file, which has the
3377 same name as the source file but an extension of @file{.o} and an Ada
3378 Library Information (ALI) file, which also has the same name as the
3379 source file, but with @file{.ali} as the extension. GNAT creates these
3380 two output files in the current directory, but you may specify a source
3381 file in any directory using an absolute or relative path specification
3382 containing the directory information.
3384 @findex gnat1
3385 @command{gcc} is actually a driver program that looks at the extensions of
3386 the file arguments and loads the appropriate compiler. For example, the
3387 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3388 These programs are in directories known to the driver program (in some
3389 configurations via environment variables you set), but need not be in
3390 your path. The @command{gcc} driver also calls the assembler and any other
3391 utilities needed to complete the generation of the required object
3392 files.
3394 It is possible to supply several file names on the same @command{gcc}
3395 command. This causes @command{gcc} to call the appropriate compiler for
3396 each file. For example, the following command lists two separate
3397 files to be compiled:
3399 @smallexample
3400 $ gcc -c x.adb y.adb
3401 @end smallexample
3403 @noindent
3404 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3405 @file{y.adb}.
3406 The compiler generates two object files @file{x.o} and @file{y.o}
3407 and the two ALI files @file{x.ali} and @file{y.ali}.
3408 Any switches apply to all the files listed,
3410 @node Switches for gcc
3411 @section Switches for @command{gcc}
3413 @noindent
3414 The @command{gcc} command accepts switches that control the
3415 compilation process. These switches are fully described in this section.
3416 First we briefly list all the switches, in alphabetical order, then we
3417 describe the switches in more detail in functionally grouped sections.
3419 More switches exist for GCC than those documented here, especially
3420 for specific targets. However, their use is not recommended as
3421 they may change code generation in ways that are incompatible with
3422 the Ada run-time library, or can cause inconsistencies between
3423 compilation units.
3425 @menu
3426 * Output and Error Message Control::
3427 * Warning Message Control::
3428 * Debugging and Assertion Control::
3429 * Validity Checking::
3430 * Style Checking::
3431 * Run-Time Checks::
3432 * Using gcc for Syntax Checking::
3433 * Using gcc for Semantic Checking::
3434 * Compiling Different Versions of Ada::
3435 * Character Set Control::
3436 * File Naming Control::
3437 * Subprogram Inlining Control::
3438 * Auxiliary Output Control::
3439 * Debugging Control::
3440 * Exception Handling Control::
3441 * Units to Sources Mapping Files::
3442 * Integrated Preprocessing::
3443 * Code Generation Control::
3444 @end menu
3446 @table @option
3447 @c !sort!
3448 @cindex @option{-b} (@command{gcc})
3449 @item -b @var{target}
3450 Compile your program to run on @var{target}, which is the name of a
3451 system configuration. You must have a GNAT cross-compiler built if
3452 @var{target} is not the same as your host system.
3454 @item -B@var{dir}
3455 @cindex @option{-B} (@command{gcc})
3456 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3457 from @var{dir} instead of the default location. Only use this switch
3458 when multiple versions of the GNAT compiler are available.
3459 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3460 GNU Compiler Collection (GCC)}, for further details. You would normally
3461 use the @option{-b} or @option{-V} switch instead.
3463 @item -c
3464 @cindex @option{-c} (@command{gcc})
3465 Compile. Always use this switch when compiling Ada programs.
3467 Note: for some other languages when using @command{gcc}, notably in
3468 the case of C and C++, it is possible to use
3469 use @command{gcc} without a @option{-c} switch to
3470 compile and link in one step. In the case of GNAT, you
3471 cannot use this approach, because the binder must be run
3472 and @command{gcc} cannot be used to run the GNAT binder.
3474 @item -fcallgraph-info@r{[}=su,da@r{]}
3475 @cindex @option{-fcallgraph-info} (@command{gcc})
3476 Makes the compiler output callgraph information for the program, on a
3477 per-file basis. The information is generated in the VCG format.  It can
3478 be decorated with additional, per-node and/or per-edge information, if a
3479 list of comma-separated markers is additionally specified. When the
3480 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3481 marker is specified, the callgraph is decorated with information about
3482 dynamically allocated objects.
3484 @item -fdump-scos
3485 @cindex @option{-fdump-scos} (@command{gcc})
3486 Generates SCO (Source Coverage Obligation) information in the ALI file.
3487 This information is used by advanced coverage tools. See unit @file{SCOs}
3488 in the compiler sources for details in files @file{scos.ads} and
3489 @file{scos.adb}.
3491 @item -fdump-xref
3492 @cindex @option{-fdump-xref} (@command{gcc})
3493 Generates cross reference information in GLI files for C and C++ sources.
3494 The GLI files have the same syntax as the ALI files for Ada, and can be used
3495 for source navigation in IDEs and on the command line using e.g. gnatxref
3496 and the @option{--ext=gli} switch.
3498 @item -flto@r{[}=n@r{]}
3499 @cindex @option{-flto} (@command{gcc})
3500 Enables Link Time Optimization. This switch must be used in conjunction
3501 with the traditional @option{-Ox} switches and instructs the compiler to
3502 defer most optimizations until the link stage. The advantage of this
3503 approach is that the compiler can do a whole-program analysis and choose
3504 the best interprocedural optimization strategy based on a complete view
3505 of the program, instead of a fragmentary view with the usual approach.
3506 This can also speed up the compilation of huge programs and reduce the
3507 size of the final executable, compared with a per-unit compilation with
3508 full inlining across modules enabled with the @option{-gnatn2} switch.
3509 The drawback of this approach is that it may require much more memory.
3510 The switch, as well as the accompanying @option{-Ox} switches, must be
3511 specified both for the compilation and the link phases.
3512 If the @var{n} parameter is specified, the optimization and final code
3513 generation at link time are executed using @var{n} parallel jobs by
3514 means of an installed @command{make} program.
3516 @item -fno-inline
3517 @cindex @option{-fno-inline} (@command{gcc})
3518 Suppresses all inlining, even if other optimization or inlining
3519 switches are set.  This includes suppression of inlining that
3520 results from the use of the pragma @code{Inline_Always}.
3521 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3522 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3523 effects if this switch is present.  Note that inlining can also
3524 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3526 @item -fno-inline-functions
3527 @cindex @option{-fno-inline-functions} (@command{gcc})
3528 Suppresses automatic inlining of subprograms, which is enabled
3529 if @option{-O3} is used.
3531 @item -fno-inline-small-functions
3532 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3533 Suppresses automatic inlining of small subprograms, which is enabled
3534 if @option{-O2} is used.
3536 @item -fno-inline-functions-called-once
3537 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3538 Suppresses inlining of subprograms local to the unit and called once
3539 from within it, which is enabled if @option{-O1} is used.
3541 @item -fno-ivopts
3542 @cindex @option{-fno-ivopts} (@command{gcc})
3543 Suppresses high-level loop induction variable optimizations, which are
3544 enabled if @option{-O1} is used. These optimizations are generally
3545 profitable but, for some specific cases of loops with numerous uses
3546 of the iteration variable that follow a common pattern, they may end
3547 up destroying the regularity that could be exploited at a lower level
3548 and thus producing inferior code.
3550 @item -fno-strict-aliasing
3551 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3552 Causes the compiler to avoid assumptions regarding non-aliasing
3553 of objects of different types. See
3554 @ref{Optimization and Strict Aliasing} for details.
3556 @item -fstack-check
3557 @cindex @option{-fstack-check} (@command{gcc})
3558 Activates stack checking.
3559 See @ref{Stack Overflow Checking} for details.
3561 @item -fstack-usage
3562 @cindex @option{-fstack-usage} (@command{gcc})
3563 Makes the compiler output stack usage information for the program, on a
3564 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3566 @item -g
3567 @cindex @option{-g} (@command{gcc})
3568 Generate debugging information. This information is stored in the object
3569 file and copied from there to the final executable file by the linker,
3570 where it can be read by the debugger. You must use the
3571 @option{-g} switch if you plan on using the debugger.
3573 @item -gnat83
3574 @cindex @option{-gnat83} (@command{gcc})
3575 Enforce Ada 83 restrictions.
3577 @item -gnat95
3578 @cindex @option{-gnat95} (@command{gcc})
3579 Enforce Ada 95 restrictions.
3581 @item -gnat05
3582 @cindex @option{-gnat05} (@command{gcc})
3583 Allow full Ada 2005 features.
3585 @item -gnat2005
3586 @cindex @option{-gnat2005} (@command{gcc})
3587 Allow full Ada 2005 features (same as @option{-gnat05})
3589 @item -gnat12
3590 @cindex @option{-gnat12} (@command{gcc})
3592 @item -gnat2012
3593 @cindex @option{-gnat2012} (@command{gcc})
3594 Allow full Ada 2012 features (same as @option{-gnat12})
3596 @item -gnata
3597 @cindex @option{-gnata} (@command{gcc})
3598 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3599 activated. Note that these pragmas can also be controlled using the
3600 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3601 It also activates pragmas @code{Check}, @code{Precondition}, and
3602 @code{Postcondition}. Note that these pragmas can also be controlled
3603 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3604 also activates all assertions defined in the RM as aspects: preconditions,
3605 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3606 corresponding pragmas for type invariants and (sub)type predicates are
3607 also activated. The default is that all these assertions are disabled,
3608 and have no effect, other than being checked for syntactic validity, and
3609 in the case of subtype predicates, constructions such as membership tests
3610 still test predicates even if assertions are turned off.
3612 @item -gnatA
3613 @cindex @option{-gnatA} (@command{gcc})
3614 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3615 it will be ignored.
3617 @item -gnatb
3618 @cindex @option{-gnatb} (@command{gcc})
3619 Generate brief messages to @file{stderr} even if verbose mode set.
3621 @item -gnatB
3622 @cindex @option{-gnatB} (@command{gcc})
3623 Assume no invalid (bad) values except for 'Valid attribute use
3624 (@pxref{Validity Checking}).
3626 @item -gnatc
3627 @cindex @option{-gnatc} (@command{gcc})
3628 Check syntax and semantics only (no code generation attempted). When the
3629 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3630 only given to the compiler (after @option{-cargs} or in package Compiler of
3631 the project file, @command{gnatmake} will fail because it will not find the
3632 object file after compilation. If @command{gnatmake} is called with
3633 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3634 Builder of the project file) then @command{gnatmake} will not fail because
3635 it will not look for the object files after compilation, and it will not try
3636 to build and link. This switch may not be given if a previous @code{-gnatR}
3637 switch has been given, since @code{-gnatR} requires that the code generator
3638 be called to complete determination of representation information.
3640 @item -gnatC
3641 @cindex @option{-gnatC} (@command{gcc})
3642 Generate CodePeer intermediate format (no code generation attempted).
3643 This switch will generate an intermediate representation suitable for
3644 use by CodePeer (@file{.scil} files). This switch is not compatible with
3645 code generation (it will, among other things, disable some switches such
3646 as -gnatn, and enable others such as -gnata).
3648 @item -gnatd
3649 @cindex @option{-gnatd} (@command{gcc})
3650 Specify debug options for the compiler. The string of characters after
3651 the @option{-gnatd} specify the specific debug options. The possible
3652 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3653 compiler source file @file{debug.adb} for details of the implemented
3654 debug options. Certain debug options are relevant to applications
3655 programmers, and these are documented at appropriate points in this
3656 users guide.
3658 @item -gnatD
3659 @cindex @option{-gnatD[nn]} (@command{gcc})
3660 Create expanded source files for source level debugging. This switch
3661 also suppress generation of cross-reference information
3662 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3663 -gnatR switch has been given, since these two switches are not compatible.
3665 @item -gnateA
3666 @cindex @option{-gnateA} (@command{gcc})
3667 Check that the actual parameters of a subprogram call are not aliases of one
3668 another. To qualify as aliasing, the actuals must denote objects of a composite
3669 type, their memory locations must be identical or overlapping, and at least one
3670 of the corresponding formal parameters must be of mode OUT or IN OUT.
3672 @smallexample
3673 type Rec_Typ is record
3674    Data : Integer := 0;
3675 end record;
3677 function Self (Val : Rec_Typ) return Rec_Typ is
3678 begin
3679    return Val;
3680 end Self;
3682 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
3683 begin
3684    null;
3685 end Detect_Aliasing;
3687 Obj : Rec_Typ;
3689 Detect_Aliasing (Obj, Obj);
3690 Detect_Aliasing (Obj, Self (Obj));
3691 @end smallexample
3693 In the example above, the first call to @code{Detect_Aliasing} fails with a
3694 @code{Program_Error} at runtime because the actuals for @code{Val_1} and
3695 @code{Val_2} denote the same object. The second call executes without raising
3696 an exception because @code{Self(Obj)} produces an anonymous object which does
3697 not share the memory location of @code{Obj}.
3699 @item -gnatec=@var{path}
3700 @cindex @option{-gnatec} (@command{gcc})
3701 Specify a configuration pragma file
3702 (the equal sign is optional)
3703 (@pxref{The Configuration Pragmas Files}).
3705 @item -gnateC
3706 @cindex @option{-gnateC} (@command{gcc})
3707 Generate CodePeer messages in a compiler-like format. This switch is only
3708 effective if @option{-gnatcC} is also specified and requires an installation
3709 of CodePeer.
3711 @item -gnated
3712 @cindex @option{-gnated} (@command{gcc})
3713 Disable atomic synchronization
3715 @item -gnateDsymbol@r{[}=@var{value}@r{]}
3716 @cindex @option{-gnateD} (@command{gcc})
3717 Defines a symbol, associated with @var{value}, for preprocessing.
3718 (@pxref{Integrated Preprocessing}).
3720 @item -gnateE
3721 @cindex @option{-gnateE} (@command{gcc})
3722 Generate extra information in exception messages. In particular, display
3723 extra column information and the value and range associated with index and
3724 range check failures, and extra column information for access checks.
3725 In cases where the compiler is able to determine at compile time that
3726 a check will fail, it gives a warning, and the extra information is not
3727 produced at run time.
3729 @item -gnatef
3730 @cindex @option{-gnatef} (@command{gcc})
3731 Display full source path name in brief error messages.
3733 @item -gnateF
3734 @cindex @option{-gnateF} (@command{gcc})
3735 Check for overflow on all floating-point operations, including those
3736 for unconstrained predefined types. See description of pragma
3737 @code{Check_Float_Overflow} in GNAT RM.
3739 @item -gnateG
3740 @cindex @option{-gnateG} (@command{gcc})
3741 Save result of preprocessing in a text file.
3743 @item -gnatei@var{nnn}
3744 @cindex @option{-gnatei} (@command{gcc})
3745 Set maximum number of instantiations during compilation of a single unit to
3746 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3747 the rare case when a single unit legitimately exceeds this limit.
3749 @item -gnateI@var{nnn}
3750 @cindex @option{-gnateI} (@command{gcc})
3751 Indicates that the source is a multi-unit source and that the index of the
3752 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3753 to be a valid index in the multi-unit source.
3755 @item -gnatel
3756 @cindex @option{-gnatel} (@command{gcc})
3757 This switch can be used with the static elaboration model to issue info
3758 messages showing
3759 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
3760 are generated. This is useful in diagnosing elaboration circularities
3761 caused by these implicit pragmas when using the static elaboration
3762 model. See See the section in this guide on elaboration checking for
3763 further details. These messages are not generated by default, and are
3764 intended only for temporary use when debugging circularity problems.
3766 @item -gnateL
3767 @cindex @option{-gnatel} (@command{gcc})
3768 This switch turns off the info messages about implicit elaboration pragmas.
3770 @item -gnatem=@var{path}
3771 @cindex @option{-gnatem} (@command{gcc})
3772 Specify a mapping file
3773 (the equal sign is optional)
3774 (@pxref{Units to Sources Mapping Files}).
3776 @item -gnatep=@var{file}
3777 @cindex @option{-gnatep} (@command{gcc})
3778 Specify a preprocessing data file
3779 (the equal sign is optional)
3780 (@pxref{Integrated Preprocessing}).
3782 @item -gnateP
3783 @cindex @option{-gnateP} (@command{gcc})
3784 Turn categorization dependency errors into warnings.
3785 Ada requires that units that WITH one another have compatible categories, for
3786 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3787 these errors become warnings (which can be ignored, or suppressed in the usual
3788 manner). This can be useful in some specialized circumstances such as the
3789 temporary use of special test software.
3791 @item -gnateS
3792 @cindex @option{-gnateS} (@command{gcc})
3793 Synonym of @option{-fdump-scos}, kept for backwards compatibility.
3795 @item -gnatet=@var{path}
3796 @cindex @option{-gnatet=file} (@command{gcc})
3797 Generate target dependent information. The format of the output file is
3798 described in the section about switch @option{-gnateT}.
3800 @item -gnateT=@var{path}
3801 @cindex @option{-gnateT} (@command{gcc})
3802 Read target dependent information, such as endianness or sizes and alignments
3803 of base type. If this switch is passed, the default target dependent
3804 information of the compiler is replaced by the one read from the input file.
3805 This is used by tools other than the compiler, e.g. to do
3806 semantic analysis of programs that will run on some other target than
3807 the machine on which the tool is run.
3809 The following target dependent values should be defined,
3810 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3811 positive integer value, and fields marked with a question mark are
3812 boolean fields, where a value of 0 is False, and a value of 1 is True:
3814 @smallexample
3815 Bits_BE                    : Nat; -- Bits stored big-endian?
3816 Bits_Per_Unit              : Pos; -- Bits in a storage unit
3817 Bits_Per_Word              : Pos; -- Bits in a word
3818 Bytes_BE                   : Nat; -- Bytes stored big-endian?
3819 Char_Size                  : Pos; -- Standard.Character'Size
3820 Double_Float_Alignment     : Nat; -- Alignment of double float
3821 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
3822 Double_Size                : Pos; -- Standard.Long_Float'Size
3823 Float_Size                 : Pos; -- Standard.Float'Size
3824 Float_Words_BE             : Nat; -- Float words stored big-endian?
3825 Int_Size                   : Pos; -- Standard.Integer'Size
3826 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
3827 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
3828 Long_Size                  : Pos; -- Standard.Long_Integer'Size
3829 Maximum_Alignment          : Pos; -- Maximum permitted alignment
3830 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
3831 Pointer_Size               : Pos; -- System.Address'Size
3832 Short_Enums                : Nat; -- Short foreign convention enums?
3833 Short_Size                 : Pos; -- Standard.Short_Integer'Size
3834 Strict_Alignment           : Nat; -- Strict alignment?
3835 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3836 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
3837 Words_BE                   : Nat; -- Words stored big-endian?
3838 @end smallexample
3840 The format of the input file is as follows. First come the values of
3841 the variables defined above, with one line per value:
3843 @smallexample
3844 name  value
3845 @end smallexample
3847 where @code{name} is the name of the parameter, spelled out in full,
3848 and cased as in the above list, and @code{value} is an unsigned decimal
3849 integer. Two or more blanks separates the name from the value.
3851 All the variables must be present, in alphabetical order (i.e. the
3852 same order as the list above).
3854 Then there is a blank line to separate the two parts of the file. Then
3855 come the lines showing the floating-point types to be registered, with
3856 one line per registered mode:
3858 @smallexample
3859 name  digs float_rep size alignment
3860 @end smallexample
3862 where @code{name} is the string name of the type (which can have
3863 single spaces embedded in the name (e.g. long double), @code{digs} is
3864 the number of digits for the floating-point type, @code{float_rep} is
3865 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3866 AAMP), @code{size} is the size in bits, @code{alignment} is the
3867 alignment in bits. The name is followed by at least two blanks, fields
3868 are separated by at least one blank, and a LF character immediately
3869 follows the alignment field.
3871 Here is an example of a target parameterization file:
3873 @smallexample
3874 Bits_BE                       0
3875 Bits_Per_Unit                 8
3876 Bits_Per_Word                64
3877 Bytes_BE                      0
3878 Char_Size                     8
3879 Double_Float_Alignment        0
3880 Double_Scalar_Alignment       0
3881 Double_Size                  64
3882 Float_Size                   32
3883 Float_Words_BE                0
3884 Int_Size                     64
3885 Long_Double_Size            128
3886 Long_Long_Size               64
3887 Long_Size                    64
3888 Maximum_Alignment            16
3889 Max_Unaligned_Field          64
3890 Pointer_Size                 64
3891 Short_Size                   16
3892 Strict_Alignment              0
3893 System_Allocator_Alignment   16
3894 Wchar_T_Size                 32
3895 Words_BE                      0
3897 float         15  I  64  64
3898 double        15  I  64  64
3899 long double   18  I  80 128
3900 TF            33  I 128 128
3901 @end smallexample
3903 @item -gnateu
3904 @cindex @option{-gnateu} (@command{gcc})
3905 Ignore unrecognized validity, warning, and style switches that
3906 appear after this switch is given. This may be useful when
3907 compiling sources developed on a later version of the compiler
3908 with an earlier version. Of course the earlier version must
3909 support this switch.
3911 @item -gnateV
3912 @cindex @option{-gnateV} (@command{gcc})
3913 Check that all actual parameters of a subprogram call are valid according to
3914 the rules of validity checking (@pxref{Validity Checking}).
3916 @item -gnateY
3917 @cindex @option{-gnateY} (@command{gcc})
3918 Ignore all STYLE_CHECKS pragmas. Full legality checks
3919 are still carried out, but the pragmas have no effect
3920 on what style checks are active. This allows all style
3921 checking options to be controlled from the command line.
3923 @item -gnatE
3924 @cindex @option{-gnatE} (@command{gcc})
3925 Full dynamic elaboration checks.
3927 @item -gnatf
3928 @cindex @option{-gnatf} (@command{gcc})
3929 Full errors. Multiple errors per line, all undefined references, do not
3930 attempt to suppress cascaded errors.
3932 @item -gnatF
3933 @cindex @option{-gnatF} (@command{gcc})
3934 Externals names are folded to all uppercase.
3936 @item -gnatg
3937 @cindex @option{-gnatg} (@command{gcc})
3938 Internal GNAT implementation mode. This should not be used for
3939 applications programs, it is intended only for use by the compiler
3940 and its run-time library. For documentation, see the GNAT sources.
3941 Note that @option{-gnatg} implies
3942 @option{-gnatw.ge} and
3943 @option{-gnatyg}
3944 so that all standard warnings and all standard style options are turned on.
3945 All warnings and style messages are treated as errors.
3947 @item -gnatG=nn
3948 @cindex @option{-gnatG[nn]} (@command{gcc})
3949 List generated expanded code in source form.
3951 @item -gnath
3952 @cindex @option{-gnath} (@command{gcc})
3953 Output usage information. The output is written to @file{stdout}.
3955 @item -gnati@var{c}
3956 @cindex @option{-gnati} (@command{gcc})
3957 Identifier character set
3958 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3959 For details of the possible selections for @var{c},
3960 see @ref{Character Set Control}.
3962 @item -gnatI
3963 @cindex @option{-gnatI} (@command{gcc})
3964 Ignore representation clauses. When this switch is used,
3965 representation clauses are treated as comments. This is useful
3966 when initially porting code where you want to ignore rep clause
3967 problems, and also for compiling foreign code (particularly
3968 for use with ASIS). The representation clauses that are ignored
3969 are: enumeration_representation_clause, record_representation_clause,
3970 and attribute_definition_clause for the following attributes:
3971 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
3972 Object_Size, Size, Small, Stream_Size, and Value_Size.
3973 Note that this option should be used only for compiling -- the
3974 code is likely to malfunction at run time.
3976 Note that when @code{-gnatct} is used to generate trees for input
3977 into @code{ASIS} tools, these representation clauses are removed
3978 from the tree and ignored. This means that the tool will not see them.
3980 @item -gnatjnn
3981 @cindex @option{-gnatjnn} (@command{gcc})
3982 Reformat error messages to fit on nn character lines
3984 @item -gnatk=@var{n}
3985 @cindex @option{-gnatk} (@command{gcc})
3986 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
3988 @item -gnatl
3989 @cindex @option{-gnatl} (@command{gcc})
3990 Output full source listing with embedded error messages.
3992 @item -gnatL
3993 @cindex @option{-gnatL} (@command{gcc})
3994 Used in conjunction with -gnatG or -gnatD to intersperse original
3995 source lines (as comment lines with line numbers) in the expanded
3996 source output.
3998 @item -gnatm=@var{n}
3999 @cindex @option{-gnatm} (@command{gcc})
4000 Limit number of detected error or warning messages to @var{n}
4001 where @var{n} is in the range 1..999999. The default setting if
4002 no switch is given is 9999. If the number of warnings reaches this
4003 limit, then a message is output and further warnings are suppressed,
4004 but the compilation is continued. If the number of error messages
4005 reaches this limit, then a message is output and the compilation
4006 is abandoned. The equal sign here is optional. A value of zero
4007 means that no limit applies.
4009 @item -gnatn[12]
4010 @cindex @option{-gnatn} (@command{gcc})
4011 Activate inlining for subprograms for which pragma @code{Inline} is
4012 specified. This inlining is performed by the GCC back-end. An optional
4013 digit sets the inlining level: 1 for moderate inlining across modules
4014 or 2 for full inlining across modules. If no inlining level is specified,
4015 the compiler will pick it based on the optimization level.
4017 @item -gnatN
4018 @cindex @option{-gnatN} (@command{gcc})
4019 Activate front end inlining for subprograms for which
4020 pragma @code{Inline} is specified. This inlining is performed
4021 by the front end and will be visible in the
4022 @option{-gnatG} output.
4024 When using a gcc-based back end (in practice this means using any version
4025 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4026 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4027 Historically front end inlining was more extensive than the gcc back end
4028 inlining, but that is no longer the case.
4030 @item -gnato0
4031 @cindex @option{-gnato0} (@command{gcc})
4032 Suppresses overflow checking. This causes the behavior of the compiler to
4033 match the default for older versions where overflow checking was suppressed
4034 by default. This is equivalent to having
4035 @code{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
4037 @item -gnato??
4038 @cindex @option{-gnato??} (@command{gcc})
4039 Set default mode for handling generation of code to avoid intermediate
4040 arithmetic overflow. Here `@code{??}' is two digits, a
4041 single digit, or nothing. Each digit is one of the digits `@code{1}'
4042 through `@code{3}':
4044 @itemize @bullet
4045 @item   @code{1}:
4046 all intermediate overflows checked against base type (@code{STRICT})
4047 @item   @code{2}:
4048 minimize intermediate overflows (@code{MINIMIZED})
4049 @item   @code{3}:
4050 eliminate intermediate overflows (@code{ELIMINATED})
4051 @end itemize
4053 If only one digit appears then it applies to all
4054 cases; if two digits are given, then the first applies outside
4055 assertions, and the second within assertions.
4057 If no digits follow the @option{-gnato}, then it is equivalent to
4058 @option{-gnato11},
4059 causing all intermediate overflows to be handled in strict mode.
4061 This switch also causes arithmetic overflow checking to be performed
4062 (as though @code{pragma Unsuppress (Overflow_Mode)} had been specified.
4064 The default if no option @option{-gnato} is given is that overflow handling
4065 is in @code{STRICT} mode (computations done using the base type), and that
4066 overflow checking is enabled.
4068 Note that division by zero is a separate check that is not
4069 controlled by this switch (division by zero checking is on by default).
4071 See also @ref{Specifying the Desired Mode}.
4073 @item -gnatp
4074 @cindex @option{-gnatp} (@command{gcc})
4075 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4076 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4078 @item -gnat-p
4079 @cindex @option{-gnat-p} (@command{gcc})
4080 Cancel effect of previous @option{-gnatp} switch.
4082 @item -gnatP
4083 @cindex @option{-gnatP} (@command{gcc})
4084 Enable polling. This is required on some systems (notably Windows NT) to
4085 obtain asynchronous abort and asynchronous transfer of control capability.
4086 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4087 details.
4089 @item -gnatq
4090 @cindex @option{-gnatq} (@command{gcc})
4091 Don't quit. Try semantics, even if parse errors.
4093 @item -gnatQ
4094 @cindex @option{-gnatQ} (@command{gcc})
4095 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4096 Note that code generation is still suppressed in the presence of any
4097 errors, so even with @option{-gnatQ} no object file is generated.
4099 @item -gnatr
4100 @cindex @option{-gnatr} (@command{gcc})
4101 Treat pragma Restrictions as Restriction_Warnings.
4103 @item -gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}
4104 @cindex @option{-gnatR} (@command{gcc})
4105 Output representation information for declared types and objects.
4106 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4107 been given, since these two switches are not compatible.
4109 @item -gnatRm[s]
4110 Output convention and parameter passing mechanisms for all subprograms.
4112 @item -gnats
4113 @cindex @option{-gnats} (@command{gcc})
4114 Syntax check only.
4116 @item -gnatS
4117 @cindex @option{-gnatS} (@command{gcc})
4118 Print package Standard.
4120 @item -gnatt
4121 @cindex @option{-gnatt} (@command{gcc})
4122 Generate tree output file.
4124 @item -gnatT@var{nnn}
4125 @cindex @option{-gnatT} (@command{gcc})
4126 All compiler tables start at @var{nnn} times usual starting size.
4128 @item -gnatu
4129 @cindex @option{-gnatu} (@command{gcc})
4130 List units for this compilation.
4132 @item -gnatU
4133 @cindex @option{-gnatU} (@command{gcc})
4134 Tag all error messages with the unique string ``error:''
4136 @item -gnatv
4137 @cindex @option{-gnatv} (@command{gcc})
4138 Verbose mode. Full error output with source lines to @file{stdout}.
4140 @item -gnatV
4141 @cindex @option{-gnatV} (@command{gcc})
4142 Control level of validity checking (@pxref{Validity Checking}).
4144 @item -gnatw@var{xxx}
4145 @cindex @option{-gnatw} (@command{gcc})
4146 Warning mode where
4147 @var{xxx} is a string of option letters that denotes
4148 the exact warnings that
4149 are enabled or disabled (@pxref{Warning Message Control}).
4151 @item -gnatW@var{e}
4152 @cindex @option{-gnatW} (@command{gcc})
4153 Wide character encoding method
4154 (@var{e}=n/h/u/s/e/8).
4156 @item -gnatx
4157 @cindex @option{-gnatx} (@command{gcc})
4158 Suppress generation of cross-reference information.
4160 @item -gnatX
4161 @cindex @option{-gnatX} (@command{gcc})
4162 Enable GNAT implementation extensions and latest Ada version.
4164 @item -gnaty
4165 @cindex @option{-gnaty} (@command{gcc})
4166 Enable built-in style checks (@pxref{Style Checking}).
4168 @item -gnatz@var{m}
4169 @cindex @option{-gnatz} (@command{gcc})
4170 Distribution stub generation and compilation
4171 (@var{m}=r/c for receiver/caller stubs).
4173 @item -I@var{dir}
4174 @cindex @option{-I} (@command{gcc})
4175 @cindex RTL
4176 Direct GNAT to search the @var{dir} directory for source files needed by
4177 the current compilation
4178 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4180 @item -I-
4181 @cindex @option{-I-} (@command{gcc})
4182 @cindex RTL
4183 Except for the source file named in the command line, do not look for source
4184 files in the directory containing the source file named in the command line
4185 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4187 @item -mbig-switch
4188 @cindex @option{-mbig-switch} (@command{gcc})
4189 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4190 This standard gcc switch causes the compiler to use larger offsets in its
4191 jump table representation for @code{case} statements.
4192 This may result in less efficient code, but is sometimes necessary
4193 (for example on HP-UX targets)
4194 @cindex HP-UX and @option{-mbig-switch} option
4195 in order to compile large and/or nested @code{case} statements.
4197 @item -o @var{file}
4198 @cindex @option{-o} (@command{gcc})
4199 This switch is used in @command{gcc} to redirect the generated object file
4200 and its associated ALI file. Beware of this switch with GNAT, because it may
4201 cause the object file and ALI file to have different names which in turn
4202 may confuse the binder and the linker.
4204 @item -nostdinc
4205 @cindex @option{-nostdinc} (@command{gcc})
4206 Inhibit the search of the default location for the GNAT Run Time
4207 Library (RTL) source files.
4209 @item -nostdlib
4210 @cindex @option{-nostdlib} (@command{gcc})
4211 Inhibit the search of the default location for the GNAT Run Time
4212 Library (RTL) ALI files.
4214 @c @item -O@ovar{n}
4215 @c Expanding @ovar macro inline (explanation in macro def comments)
4216 @item -O@r{[}@var{n}@r{]}
4217 @cindex @option{-O} (@command{gcc})
4218 @var{n} controls the optimization level.
4220 @table @asis
4221 @item n = 0
4222 No optimization, the default setting if no @option{-O} appears
4224 @item n = 1
4225 Normal optimization, the default if you specify @option{-O} without
4226 an operand. A good compromise between code quality and compilation
4227 time.
4229 @item n = 2
4230 Extensive optimization, may improve execution time, possibly at the cost of
4231 substantially increased compilation time.
4233 @item n = 3
4234 Same as @option{-O2}, and also includes inline expansion for small subprograms
4235 in the same unit.
4237 @item n = s
4238 Optimize space usage
4239 @end table
4241 @noindent
4242 See also @ref{Optimization Levels}.
4245 @item -pass-exit-codes
4246 @cindex @option{-pass-exit-codes} (@command{gcc})
4247 Catch exit codes from the compiler and use the most meaningful as
4248 exit status.
4250 @item --RTS=@var{rts-path}
4251 @cindex @option{--RTS} (@command{gcc})
4252 Specifies the default location of the runtime library. Same meaning as the
4253 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4255 @item -S
4256 @cindex @option{-S} (@command{gcc})
4257 Used in place of @option{-c} to
4258 cause the assembler source file to be
4259 generated, using @file{.s} as the extension,
4260 instead of the object file.
4261 This may be useful if you need to examine the generated assembly code.
4263 @item -fverbose-asm
4264 @cindex @option{-fverbose-asm} (@command{gcc})
4265 Used in conjunction with @option{-S}
4266 to cause the generated assembly code file to be annotated with variable
4267 names, making it significantly easier to follow.
4269 @item -v
4270 @cindex @option{-v} (@command{gcc})
4271 Show commands generated by the @command{gcc} driver. Normally used only for
4272 debugging purposes or if you need to be sure what version of the
4273 compiler you are executing.
4275 @item -V @var{ver}
4276 @cindex @option{-V} (@command{gcc})
4277 Execute @var{ver} version of the compiler. This is the @command{gcc}
4278 version, not the GNAT version.
4280 @item -w
4281 @cindex @option{-w} (@command{gcc})
4282 Turn off warnings generated by the back end of the compiler. Use of
4283 this switch also causes the default for front end warnings to be set
4284 to suppress (as though @option{-gnatws} had appeared at the start of
4285 the options).
4287 @end table
4289 @c Combining qualifiers does not work on VMS
4290 You may combine a sequence of GNAT switches into a single switch. For
4291 example, the combined switch
4293 @cindex Combining GNAT switches
4294 @smallexample
4295 -gnatofi3
4296 @end smallexample
4298 @noindent
4299 is equivalent to specifying the following sequence of switches:
4301 @smallexample
4302 -gnato -gnatf -gnati3
4303 @end smallexample
4305 @noindent
4306 The following restrictions apply to the combination of switches
4307 in this manner:
4309 @itemize @bullet
4310 @item
4311 The switch @option{-gnatc} if combined with other switches must come
4312 first in the string.
4314 @item
4315 The switch @option{-gnats} if combined with other switches must come
4316 first in the string.
4318 @item
4319 The switches
4321 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4322 switches, and only one of them may appear in the command line.
4324 @item
4325 The switch @option{-gnat-p} may not be combined with any other switch.
4327 @item
4328 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4329 switch), then all further characters in the switch are interpreted
4330 as style modifiers (see description of @option{-gnaty}).
4332 @item
4333 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4334 switch), then all further characters in the switch are interpreted
4335 as debug flags (see description of @option{-gnatd}).
4337 @item
4338 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4339 switch), then all further characters in the switch are interpreted
4340 as warning mode modifiers (see description of @option{-gnatw}).
4342 @item
4343 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4344 switch), then all further characters in the switch are interpreted
4345 as validity checking options (@pxref{Validity Checking}).
4347 @item
4348 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4349 a combined list of options.
4350 @end itemize
4352 @node Output and Error Message Control
4353 @subsection Output and Error Message Control
4354 @findex stderr
4356 @noindent
4357 The standard default format for error messages is called ``brief format''.
4358 Brief format messages are written to @file{stderr} (the standard error
4359 file) and have the following form:
4361 @smallexample
4362 e.adb:3:04: Incorrect spelling of keyword "function"
4363 e.adb:4:20: ";" should be "is"
4364 @end smallexample
4366 @noindent
4367 The first integer after the file name is the line number in the file,
4368 and the second integer is the column number within the line.
4369 @code{GPS} can parse the error messages
4370 and point to the referenced character.
4371 The following switches provide control over the error message
4372 format:
4374 @table @option
4375 @c !sort!
4376 @item -gnatv
4377 @cindex @option{-gnatv} (@command{gcc})
4378 @findex stdout
4379 The v stands for verbose.
4380 The effect of this setting is to write long-format error
4381 messages to @file{stdout} (the standard output file.
4382 The same program compiled with the
4383 @option{-gnatv} switch would generate:
4385 @smallexample
4386 @cartouche
4387 3. funcion X (Q : Integer)
4388    |
4389 >>> Incorrect spelling of keyword "function"
4390 4. return Integer;
4391                  |
4392 >>> ";" should be "is"
4393 @end cartouche
4394 @end smallexample
4396 @noindent
4397 The vertical bar indicates the location of the error, and the @samp{>>>}
4398 prefix can be used to search for error messages. When this switch is
4399 used the only source lines output are those with errors.
4401 @item -gnatl
4402 @cindex @option{-gnatl} (@command{gcc})
4403 The @code{l} stands for list.
4404 This switch causes a full listing of
4405 the file to be generated. In the case where a body is
4406 compiled, the corresponding spec is also listed, along
4407 with any subunits. Typical output from compiling a package
4408 body @file{p.adb} might look like:
4410 @smallexample @c ada
4411 @cartouche
4412  Compiling: p.adb
4414      1. @b{package} @b{body} p @b{is}
4415      2.    @b{procedure} a;
4416      3.    @b{procedure} a @b{is} @b{separate};
4417      4. @b{begin}
4418      5.    @b{null}
4419                |
4420         >>> missing ";"
4422      6. @b{end};
4424 Compiling: p.ads
4426      1. @b{package} p @b{is}
4427      2.    @b{pragma} Elaborate_Body
4428                                 |
4429         >>> missing ";"
4431      3. @b{end} p;
4433 Compiling: p-a.adb
4435      1. @b{separate} p
4436                 |
4437         >>> missing "("
4439      2. @b{procedure} a @b{is}
4440      3. @b{begin}
4441      4.    @b{null}
4442                |
4443         >>> missing ";"
4445      5. @b{end};
4446 @end cartouche
4447 @end smallexample
4449 @noindent
4450 @findex stderr
4451 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4452 standard output is redirected, a brief summary is written to
4453 @file{stderr} (standard error) giving the number of error messages and
4454 warning messages generated.
4456 @item -gnatl=file
4457 @cindex @option{-gnatl=fname} (@command{gcc})
4458 This has the same effect as @option{-gnatl} except that the output is
4459 written to a file instead of to standard output. If the given name
4460 @file{fname} does not start with a period, then it is the full name
4461 of the file to be written. If @file{fname} is an extension, it is
4462 appended to the name of the file being compiled. For example, if
4463 file @file{xyz.adb} is compiled with @option{-gnatl=.lst},
4464 then the output is written to file xyz.adb.lst.
4466 @item -gnatU
4467 @cindex @option{-gnatU} (@command{gcc})
4468 This switch forces all error messages to be preceded by the unique
4469 string ``error:''. This means that error messages take a few more
4470 characters in space, but allows easy searching for and identification
4471 of error messages.
4473 @item -gnatb
4474 @cindex @option{-gnatb} (@command{gcc})
4475 The @code{b} stands for brief.
4476 This switch causes GNAT to generate the
4477 brief format error messages to @file{stderr} (the standard error
4478 file) as well as the verbose
4479 format message or full listing (which as usual is written to
4480 @file{stdout} (the standard output file).
4482 @item -gnatm=@var{n}
4483 @cindex @option{-gnatm} (@command{gcc})
4484 The @code{m} stands for maximum.
4485 @var{n} is a decimal integer in the
4486 range of 1 to 999999 and limits the number of error or warning
4487 messages to be generated. For example, using
4488 @option{-gnatm2} might yield
4490 @smallexample
4491 e.adb:3:04: Incorrect spelling of keyword "function"
4492 e.adb:5:35: missing ".."
4493 fatal error: maximum number of errors detected
4494 compilation abandoned
4495 @end smallexample
4497 @noindent
4498 The default setting if
4499 no switch is given is 9999. If the number of warnings reaches this
4500 limit, then a message is output and further warnings are suppressed,
4501 but the compilation is continued. If the number of error messages
4502 reaches this limit, then a message is output and the compilation
4503 is abandoned. A value of zero means that no limit applies.
4505 @noindent
4506 Note that the equal sign is optional, so the switches
4507 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4509 @item -gnatf
4510 @cindex @option{-gnatf} (@command{gcc})
4511 @cindex Error messages, suppressing
4512 The @code{f} stands for full.
4513 Normally, the compiler suppresses error messages that are likely to be
4514 redundant. This switch causes all error
4515 messages to be generated. In particular, in the case of
4516 references to undefined variables. If a given variable is referenced
4517 several times, the normal format of messages is
4518 @smallexample
4519 e.adb:7:07: "V" is undefined (more references follow)
4520 @end smallexample
4522 @noindent
4523 where the parenthetical comment warns that there are additional
4524 references to the variable @code{V}. Compiling the same program with the
4525 @option{-gnatf} switch yields
4527 @smallexample
4528 e.adb:7:07: "V" is undefined
4529 e.adb:8:07: "V" is undefined
4530 e.adb:8:12: "V" is undefined
4531 e.adb:8:16: "V" is undefined
4532 e.adb:9:07: "V" is undefined
4533 e.adb:9:12: "V" is undefined
4534 @end smallexample
4536 @noindent
4537 The @option{-gnatf} switch also generates additional information for
4538 some error messages.  Some examples are:
4540 @itemize @bullet
4541 @item
4542 Details on possibly non-portable unchecked conversion
4543 @item
4544 List possible interpretations for ambiguous calls
4545 @item
4546 Additional details on incorrect parameters
4547 @end itemize
4549 @item -gnatjnn
4550 @cindex @option{-gnatjnn} (@command{gcc})
4551 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4552 with continuation lines are treated as though the continuation lines were
4553 separate messages (and so a warning with two continuation lines counts as
4554 three warnings, and is listed as three separate messages).
4556 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4557 messages are output in a different manner. A message and all its continuation
4558 lines are treated as a unit, and count as only one warning or message in the
4559 statistics totals. Furthermore, the message is reformatted so that no line
4560 is longer than nn characters.
4562 @item -gnatq
4563 @cindex @option{-gnatq} (@command{gcc})
4564 The @code{q} stands for quit (really ``don't quit'').
4565 In normal operation mode, the compiler first parses the program and
4566 determines if there are any syntax errors. If there are, appropriate
4567 error messages are generated and compilation is immediately terminated.
4568 This switch tells
4569 GNAT to continue with semantic analysis even if syntax errors have been
4570 found. This may enable the detection of more errors in a single run. On
4571 the other hand, the semantic analyzer is more likely to encounter some
4572 internal fatal error when given a syntactically invalid tree.
4574 @item -gnatQ
4575 @cindex @option{-gnatQ} (@command{gcc})
4576 In normal operation mode, the @file{ALI} file is not generated if any
4577 illegalities are detected in the program. The use of @option{-gnatQ} forces
4578 generation of the @file{ALI} file. This file is marked as being in
4579 error, so it cannot be used for binding purposes, but it does contain
4580 reasonably complete cross-reference information, and thus may be useful
4581 for use by tools (e.g., semantic browsing tools or integrated development
4582 environments) that are driven from the @file{ALI} file. This switch
4583 implies @option{-gnatq}, since the semantic phase must be run to get a
4584 meaningful ALI file.
4586 In addition, if @option{-gnatt} is also specified, then the tree file is
4587 generated even if there are illegalities. It may be useful in this case
4588 to also specify @option{-gnatq} to ensure that full semantic processing
4589 occurs. The resulting tree file can be processed by ASIS, for the purpose
4590 of providing partial information about illegal units, but if the error
4591 causes the tree to be badly malformed, then ASIS may crash during the
4592 analysis.
4594 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4595 being in error, @command{gnatmake} will attempt to recompile the source when it
4596 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4598 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4599 since ALI files are never generated if @option{-gnats} is set.
4601 @end table
4603 @node Warning Message Control
4604 @subsection Warning Message Control
4605 @cindex Warning messages
4606 @noindent
4607 In addition to error messages, which correspond to illegalities as defined
4608 in the Ada Reference Manual, the compiler detects two kinds of warning
4609 situations.
4611 First, the compiler considers some constructs suspicious and generates a
4612 warning message to alert you to a possible error. Second, if the
4613 compiler detects a situation that is sure to raise an exception at
4614 run time, it generates a warning message. The following shows an example
4615 of warning messages:
4616 @smallexample
4617 e.adb:4:24: warning: creation of object may raise Storage_Error
4618 e.adb:10:17: warning: static value out of range
4619 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4620 @end smallexample
4622 @noindent
4623 GNAT considers a large number of situations as appropriate
4624 for the generation of warning messages. As always, warnings are not
4625 definite indications of errors. For example, if you do an out-of-range
4626 assignment with the deliberate intention of raising a
4627 @code{Constraint_Error} exception, then the warning that may be
4628 issued does not indicate an error. Some of the situations for which GNAT
4629 issues warnings (at least some of the time) are given in the following
4630 list. This list is not complete, and new warnings are often added to
4631 subsequent versions of GNAT. The list is intended to give a general idea
4632 of the kinds of warnings that are generated.
4634 @itemize @bullet
4635 @item
4636 Possible infinitely recursive calls
4638 @item
4639 Out-of-range values being assigned
4641 @item
4642 Possible order of elaboration problems
4644 @item
4645 Size not a multiple of alignment for a record type
4647 @item
4648 Assertions (pragma Assert) that are sure to fail
4650 @item
4651 Unreachable code
4653 @item
4654 Address clauses with possibly unaligned values, or where an attempt is
4655 made to overlay a smaller variable with a larger one.
4657 @item
4658 Fixed-point type declarations with a null range
4660 @item
4661 Direct_IO or Sequential_IO instantiated with a type that has access values
4663 @item
4664 Variables that are never assigned a value
4666 @item
4667 Variables that are referenced before being initialized
4669 @item
4670 Task entries with no corresponding @code{accept} statement
4672 @item
4673 Duplicate accepts for the same task entry in a @code{select}
4675 @item
4676 Objects that take too much storage
4678 @item
4679 Unchecked conversion between types of differing sizes
4681 @item
4682 Missing @code{return} statement along some execution path in a function
4684 @item
4685 Incorrect (unrecognized) pragmas
4687 @item
4688 Incorrect external names
4690 @item
4691 Allocation from empty storage pool
4693 @item
4694 Potentially blocking operation in protected type
4696 @item
4697 Suspicious parenthesization of expressions
4699 @item
4700 Mismatching bounds in an aggregate
4702 @item
4703 Attempt to return local value by reference
4705 @item
4706 Premature instantiation of a generic body
4708 @item
4709 Attempt to pack aliased components
4711 @item
4712 Out of bounds array subscripts
4714 @item
4715 Wrong length on string assignment
4717 @item
4718 Violations of style rules if style checking is enabled
4720 @item
4721 Unused @code{with} clauses
4723 @item
4724 @code{Bit_Order} usage that does not have any effect
4726 @item
4727 @code{Standard.Duration} used to resolve universal fixed expression
4729 @item
4730 Dereference of possibly null value
4732 @item
4733 Declaration that is likely to cause storage error
4735 @item
4736 Internal GNAT unit @code{with}'ed by application unit
4738 @item
4739 Values known to be out of range at compile time
4741 @item
4742 Unreferenced or unmodified variables. Note that a special
4743 exemption applies to variables which contain any of the substrings
4744 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
4745 are considered likely to be intentionally used in a situation where
4746 otherwise a warning would be given, so warnings of this kind are
4747 always suppressed for such variables.
4749 @item
4750 Address overlays that could clobber memory
4752 @item
4753 Unexpected initialization when address clause present
4755 @item
4756 Bad alignment for address clause
4758 @item
4759 Useless type conversions
4761 @item
4762 Redundant assignment statements and other redundant constructs
4764 @item
4765 Useless exception handlers
4767 @item
4768 Accidental hiding of name by child unit
4770 @item
4771 Access before elaboration detected at compile time
4773 @item
4774 A range in a @code{for} loop that is known to be null or might be null
4776 @end itemize
4778 @noindent
4779 The following section lists compiler switches that are available
4780 to control the handling of warning messages. It is also possible
4781 to exercise much finer control over what warnings are issued and
4782 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4783 gnat_rm, GNAT Reference manual}.
4785 @table @option
4786 @c !sort!
4787 @item -gnatwa
4788 @emph{Activate most optional warnings.}
4789 @cindex @option{-gnatwa} (@command{gcc})
4790 This switch activates most optional warning messages.  See the remaining list
4791 in this section for details on optional warning messages that can be
4792 individually controlled.  The warnings that are not turned on by this
4793 switch are:
4795 @itemize
4796 @option{-gnatwd} (implicit dereferencing)
4797 @option{-gnatw.d} (tag warnings with -gnatw switch)
4798 @option{-gnatwh} (hiding)
4799 @option{-gnatw.h} (holes in record layouts)
4800 @option{-gnatw.k} (redefinition of names in standard)
4801 @option{-gnatwl} (elaboration warnings)
4802 @option{-gnatw.l} (inherited aspects)
4803 @option{-gnatw.n} (atomic synchronization)
4804 @option{-gnatwo} (address clause overlay)
4805 @option{-gnatw.o} (values set by out parameters ignored)
4806 @option{-gnatw.s} (overridden size clause)
4807 @option{-gnatwt} (tracking of deleted conditional code)
4808 @option{-gnatw.u} (unordered enumeration)
4809 @option{-gnatw.w} (use of Warnings Off)
4810 @option{-gnatw.y} (reasons for package needing body)
4811 @end itemize
4813 All other optional warnings are turned on.
4815 @item -gnatwA
4816 @emph{Suppress all optional errors.}
4817 @cindex @option{-gnatwA} (@command{gcc})
4818 This switch suppresses all optional warning messages, see remaining list
4819 in this section for details on optional warning messages that can be
4820 individually controlled. Note that unlike switch @option{-gnatws}, the
4821 use of switch @option{-gnatwA} does not suppress warnings that are
4822 normally given unconditionally and cannot be individually controlled
4823 (for example, the warning about a missing exit path in a function).
4824 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4825 the use of switch @option{-gnatwA} can be individually turned back
4826 on. For example the use of switch @option{-gnatwA} followed by
4827 switch @option{-gnatwd} will suppress all optional warnings except
4828 the warnings for implicit dereferencing.
4830 @item -gnatw.a
4831 @emph{Activate warnings on failing assertions.}
4832 @cindex @option{-gnatw.a} (@command{gcc})
4833 @cindex Assert failures
4834 This switch activates warnings for assertions where the compiler can tell at
4835 compile time that the assertion will fail. Note that this warning is given
4836 even if assertions are disabled. The default is that such warnings are
4837 generated.
4839 @item -gnatw.A
4840 @emph{Suppress warnings on failing assertions.}
4841 @cindex @option{-gnatw.A} (@command{gcc})
4842 @cindex Assert failures
4843 This switch suppresses warnings for assertions where the compiler can tell at
4844 compile time that the assertion will fail.
4846 @item -gnatwb
4847 @emph{Activate warnings on bad fixed values.}
4848 @cindex @option{-gnatwb} (@command{gcc})
4849 @cindex Bad fixed values
4850 @cindex Fixed-point Small value
4851 @cindex Small value
4852 This switch activates warnings for static fixed-point expressions whose
4853 value is not an exact multiple of Small. Such values are implementation
4854 dependent, since an implementation is free to choose either of the multiples
4855 that surround the value. GNAT always chooses the closer one, but this is not
4856 required behavior, and it is better to specify a value that is an exact
4857 multiple, ensuring predictable execution. The default is that such warnings
4858 are not generated.
4860 @item -gnatwB
4861 @emph{Suppress warnings on bad fixed values.}
4862 @cindex @option{-gnatwB} (@command{gcc})
4863 This switch suppresses warnings for static fixed-point expressions whose
4864 value is not an exact multiple of Small.
4866 @item -gnatw.b
4867 @emph{Activate warnings on biased representation.}
4868 @cindex @option{-gnatw.b} (@command{gcc})
4869 @cindex Biased representation
4870 This switch activates warnings when a size clause, value size clause, component
4871 clause, or component size clause forces the use of biased representation for an
4872 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4873 to represent 10/11). The default is that such warnings are generated.
4875 @item -gnatw.B
4876 @emph{Suppress warnings on biased representation.}
4877 @cindex @option{-gnatwB} (@command{gcc})
4878 This switch suppresses warnings for representation clauses that force the use
4879 of biased representation.
4881 @item -gnatwc
4882 @emph{Activate warnings on conditionals.}
4883 @cindex @option{-gnatwc} (@command{gcc})
4884 @cindex Conditionals, constant
4885 This switch activates warnings for conditional expressions used in
4886 tests that are known to be True or False at compile time. The default
4887 is that such warnings are not generated.
4888 Note that this warning does
4889 not get issued for the use of boolean variables or constants whose
4890 values are known at compile time, since this is a standard technique
4891 for conditional compilation in Ada, and this would generate too many
4892 false positive warnings.
4894 This warning option also activates a special test for comparisons using
4895 the operators ``>='' and`` <=''.
4896 If the compiler can tell that only the equality condition is possible,
4897 then it will warn that the ``>'' or ``<'' part of the test
4898 is useless and that the operator could be replaced by ``=''.
4899 An example would be comparing a @code{Natural} variable <= 0.
4901 This warning option also generates warnings if
4902 one or both tests is optimized away in a membership test for integer
4903 values if the result can be determined at compile time. Range tests on
4904 enumeration types are not included, since it is common for such tests
4905 to include an end point.
4907 This warning can also be turned on using @option{-gnatwa}.
4909 @item -gnatwC
4910 @emph{Suppress warnings on conditionals.}
4911 @cindex @option{-gnatwC} (@command{gcc})
4912 This switch suppresses warnings for conditional expressions used in
4913 tests that are known to be True or False at compile time.
4915 @item -gnatw.c
4916 @emph{Activate warnings on missing component clauses.}
4917 @cindex @option{-gnatw.c} (@command{gcc})
4918 @cindex Component clause, missing
4919 This switch activates warnings for record components where a record
4920 representation clause is present and has component clauses for the
4921 majority, but not all, of the components. A warning is given for each
4922 component for which no component clause is present.
4924 @item -gnatw.C
4925 @emph{Suppress warnings on missing component clauses.}
4926 @cindex @option{-gnatwC} (@command{gcc})
4927 This switch suppresses warnings for record components that are
4928 missing a component clause in the situation described above.
4930 @item -gnatwd
4931 @emph{Activate warnings on implicit dereferencing.}
4932 @cindex @option{-gnatwd} (@command{gcc})
4933 If this switch is set, then the use of a prefix of an access type
4934 in an indexed component, slice, or selected component without an
4935 explicit @code{.all} will generate a warning. With this warning
4936 enabled, access checks occur only at points where an explicit
4937 @code{.all} appears in the source code (assuming no warnings are
4938 generated as a result of this switch). The default is that such
4939 warnings are not generated.
4941 @item -gnatwD
4942 @emph{Suppress warnings on implicit dereferencing.}
4943 @cindex @option{-gnatwD} (@command{gcc})
4944 @cindex Implicit dereferencing
4945 @cindex Dereferencing, implicit
4946 This switch suppresses warnings for implicit dereferences in
4947 indexed components, slices, and selected components.
4949 @item -gnatw.d
4950 @emph{Activate tagging of warning and info messages.}
4951 @cindex @option{-gnatw.d} (@command{gcc})
4952 If this switch is set, then warning messages are tagged, with one of the
4953 following strings:
4955 @table @option
4957 @item [-gnatw?]
4958 Used to tag warnings controlled by the switch @option{-gnatwx} where x
4959 is a letter a-z.
4961 @item [-gnatw.?]
4962 Used to tag warnings controlled by the switch @option{-gnatw.x} where x
4963 is a letter a-z.
4965 @item [-gnatel]
4966 Used to tag elaboration information (info) messages generated when the
4967 static model of elaboration is used and the @option{-gnatel} switch is set.
4969 @item [restriction warning]
4970 Used to tag warning messages for restriction violations, activated by use
4971 of the pragma @option{Restriction_Warnings}.
4973 @item [warning-as-error]
4974 Used to tag warning messages that have been converted to error messages by
4975 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
4976 the string "error: " rather than "warning: ".
4978 @item [enabled by default]
4979 Used to tag all other warnings that are always given by default, unless
4980 warnings are completely suppressed using pragma @option{Warnings(Off)} or
4981 the switch @option{-gnatws}.
4983 @end table
4985 @item -gnatw.D
4986 @emph{Deactivate tagging of warning and info messages messages.}
4987 @cindex @option{-gnatw.d} (@command{gcc})
4988 If this switch is set, then warning messages return to the default
4989 mode in which warnings and info messages are not tagged as described above for
4990 @code{-gnatw.d}.
4992 @item -gnatwe
4993 @emph{Treat warnings and style checks as errors.}
4994 @cindex @option{-gnatwe} (@command{gcc})
4995 @cindex Warnings, treat as error
4996 This switch causes warning messages and style check messages to be
4997 treated as errors.
4998 The warning string still appears, but the warning messages are counted
4999 as errors, and prevent the generation of an object file. Note that this
5000 is the only -gnatw switch that affects the handling of style check messages.
5001 Note also that this switch has no effect on info (information) messages, which
5002 are not treated as errors if this switch is present.
5004 @item -gnatw.e
5005 @emph{Activate every optional warning}
5006 @cindex @option{-gnatw.e} (@command{gcc})
5007 @cindex Warnings, activate every optional warning
5008 This switch activates all optional warnings, including those which
5009 are not activated by @code{-gnatwa}. The use of this switch is not
5010 recommended for normal use. If you turn this switch on, it is almost
5011 certain that you will get large numbers of useless warnings. The
5012 warnings that are excluded from @code{-gnatwa} are typically highly
5013 specialized warnings that are suitable for use only in code that has
5014 been specifically designed according to specialized coding rules.
5016 @item -gnatwf
5017 @emph{Activate warnings on unreferenced formals.}
5018 @cindex @option{-gnatwf} (@command{gcc})
5019 @cindex Formals, unreferenced
5020 This switch causes a warning to be generated if a formal parameter
5021 is not referenced in the body of the subprogram. This warning can
5022 also be turned on using @option{-gnatwu}. The
5023 default is that these warnings are not generated.
5025 @item -gnatwF
5026 @emph{Suppress warnings on unreferenced formals.}
5027 @cindex @option{-gnatwF} (@command{gcc})
5028 This switch suppresses warnings for unreferenced formal
5029 parameters. Note that the
5030 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5031 effect of warning on unreferenced entities other than subprogram
5032 formals.
5034 @item -gnatwg
5035 @emph{Activate warnings on unrecognized pragmas.}
5036 @cindex @option{-gnatwg} (@command{gcc})
5037 @cindex Pragmas, unrecognized
5038 This switch causes a warning to be generated if an unrecognized
5039 pragma is encountered. Apart from issuing this warning, the
5040 pragma is ignored and has no effect. The default
5041 is that such warnings are issued (satisfying the Ada Reference
5042 Manual requirement that such warnings appear).
5044 @item -gnatwG
5045 @emph{Suppress warnings on unrecognized pragmas.}
5046 @cindex @option{-gnatwG} (@command{gcc})
5047 This switch suppresses warnings for unrecognized pragmas.
5049 @item -gnatw.g
5050 @emph{Warnings used for GNAT sources}
5051 @cindex @option{-gnatw.g} (@command{gcc})
5052 This switch sets the warning categories that are used by the standard
5053 GNAT style. Currently this is equivalent to
5054 @option{-gnatwAao.sI.C.V.X}
5055 but more warnings may be added in the future without advanced notice.
5057 @item -gnatwh
5058 @emph{Activate warnings on hiding.}
5059 @cindex @option{-gnatwh} (@command{gcc})
5060 @cindex Hiding of Declarations
5061 This switch activates warnings on hiding declarations.
5062 A declaration is considered hiding
5063 if it is for a non-overloadable entity, and it declares an entity with the
5064 same name as some other entity that is directly or use-visible. The default
5065 is that such warnings are not generated.
5067 @item -gnatwH
5068 @emph{Suppress warnings on hiding.}
5069 @cindex @option{-gnatwH} (@command{gcc})
5070 This switch suppresses warnings on hiding declarations.
5072 @item -gnatw.h
5073 @emph{Activate warnings on holes/gaps in records.}
5074 @cindex @option{-gnatw.h} (@command{gcc})
5075 @cindex Record Representation (gaps)
5076 This switch activates warnings on component clauses in record
5077 representation clauses that leave holes (gaps) in the record layout.
5078 If this warning option is active, then record representation clauses
5079 should specify a contiguous layout, adding unused fill fields if needed.
5081 @item -gnatw.H
5082 @emph{Suppress warnings on holes/gaps in records.}
5083 @cindex @option{-gnatw.H} (@command{gcc})
5084 This switch suppresses warnings on component clauses in record
5085 representation clauses that leave holes (haps) in the record layout.
5087 @item -gnatwi
5088 @emph{Activate warnings on implementation units.}
5089 @cindex @option{-gnatwi} (@command{gcc})
5090 This switch activates warnings for a @code{with} of an internal GNAT
5091 implementation unit, defined as any unit from the @code{Ada},
5092 @code{Interfaces}, @code{GNAT},
5093  or @code{System}
5094 hierarchies that is not
5095 documented in either the Ada Reference Manual or the GNAT
5096 Programmer's Reference Manual. Such units are intended only
5097 for internal implementation purposes and should not be @code{with}'ed
5098 by user programs. The default is that such warnings are generated
5100 @item -gnatwI
5101 @emph{Disable warnings on implementation units.}
5102 @cindex @option{-gnatwI} (@command{gcc})
5103 This switch disables warnings for a @code{with} of an internal GNAT
5104 implementation unit.
5106 @item -gnatw.i
5107 @emph{Activate warnings on overlapping actuals.}
5108 @cindex @option{-gnatw.i} (@command{gcc})
5109 This switch enables a warning on statically detectable overlapping actuals in
5110 a subprogram call, when one of the actuals is an in-out parameter, and the
5111 types of the actuals are not by-copy types. This warning is off by default.
5113 @item -gnatw.I
5114 @emph{Disable warnings on overlapping actuals.}
5115 @cindex @option{-gnatw.I} (@command{gcc})
5116 This switch disables warnings on overlapping actuals in a call..
5118 @item -gnatwj
5119 @emph{Activate warnings on obsolescent features (Annex J).}
5120 @cindex @option{-gnatwj} (@command{gcc})
5121 @cindex Features, obsolescent
5122 @cindex Obsolescent features
5123 If this warning option is activated, then warnings are generated for
5124 calls to subprograms marked with @code{pragma Obsolescent} and
5125 for use of features in Annex J of the Ada Reference Manual. In the
5126 case of Annex J, not all features are flagged. In particular use
5127 of the renamed packages (like @code{Text_IO}) and use of package
5128 @code{ASCII} are not flagged, since these are very common and
5129 would generate many annoying positive warnings. The default is that
5130 such warnings are not generated.
5132 In addition to the above cases, warnings are also generated for
5133 GNAT features that have been provided in past versions but which
5134 have been superseded (typically by features in the new Ada standard).
5135 For example, @code{pragma Ravenscar} will be flagged since its
5136 function is replaced by @code{pragma Profile(Ravenscar)}, and
5137 @code{pragma Interface_Name} will be flagged since its function
5138 is replaced by @code{pragma Import}.
5140 Note that this warning option functions differently from the
5141 restriction @code{No_Obsolescent_Features} in two respects.
5142 First, the restriction applies only to annex J features.
5143 Second, the restriction does flag uses of package @code{ASCII}.
5145 @item -gnatwJ
5146 @emph{Suppress warnings on obsolescent features (Annex J).}
5147 @cindex @option{-gnatwJ} (@command{gcc})
5148 This switch disables warnings on use of obsolescent features.
5150 @item -gnatwk
5151 @emph{Activate warnings on variables that could be constants.}
5152 @cindex @option{-gnatwk} (@command{gcc})
5153 This switch activates warnings for variables that are initialized but
5154 never modified, and then could be declared constants. The default is that
5155 such warnings are not given.
5157 @item -gnatwK
5158 @emph{Suppress warnings on variables that could be constants.}
5159 @cindex @option{-gnatwK} (@command{gcc})
5160 This switch disables warnings on variables that could be declared constants.
5162 @item -gnatw.k
5163 @emph{Activate warnings on redefinition of names in standard.}
5164 @cindex @option{-gnatw.k} (@command{gcc})
5165 This switch activates warnings for declarations that declare a name that
5166 is defined in package Standard. Such declarations can be confusing,
5167 especially since the names in package Standard continue to be directly
5168 visible, meaning that use visibiliy on such redeclared names does not
5169 work as expected. Names of discriminants and components in records are
5170 not included in this check.
5172 @item -gnatw.K
5173 @emph{Suppress warnings on redefinition of names in standard.}
5174 @cindex @option{-gnatwK} (@command{gcc})
5175 This switch activates warnings for declarations that declare a name that
5176 is defined in package Standard.
5178 @item -gnatwl
5179 @emph{Activate warnings for elaboration pragmas.}
5180 @cindex @option{-gnatwl} (@command{gcc})
5181 @cindex Elaboration, warnings
5182 This switch activates warnings for possible elaboration problems,
5183 including suspicious use
5184 of @code{Elaborate} pragmas, when using the static elaboration model, and
5185 possible situations that may raise @code{Program_Error} when using the
5186 dynamic elaboration model.
5187 See the section in this guide on elaboration checking for further details.
5188 The default is that such warnings
5189 are not generated.
5191 @item -gnatwL
5192 @emph{Suppress warnings for elaboration pragmas.}
5193 @cindex @option{-gnatwL} (@command{gcc})
5194 This switch suppresses warnings for possible elaboration problems.
5196 @item -gnatw.l
5197 @emph{List inherited aspects.}
5198 @cindex @option{-gnatw.l} (@command{gcc})
5199 This switch causes the compiler to list inherited invariants,
5200 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5201 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5203 @item -gnatw.L
5204 @emph{Suppress listing of inherited aspects.}
5205 @cindex @option{-gnatw.L} (@command{gcc})
5206 This switch suppresses listing of inherited aspects.
5208 @item -gnatwm
5209 @emph{Activate warnings on modified but unreferenced variables.}
5210 @cindex @option{-gnatwm} (@command{gcc})
5211 This switch activates warnings for variables that are assigned (using
5212 an initialization value or with one or more assignment statements) but
5213 whose value is never read. The warning is suppressed for volatile
5214 variables and also for variables that are renamings of other variables
5215 or for which an address clause is given.
5216 The default is that these warnings are not given.
5218 @item -gnatwM
5219 @emph{Disable warnings on modified but unreferenced variables.}
5220 @cindex @option{-gnatwM} (@command{gcc})
5221 This switch disables warnings for variables that are assigned or
5222 initialized, but never read.
5224 @item -gnatw.m
5225 @emph{Activate warnings on suspicious modulus values.}
5226 @cindex @option{-gnatw.m} (@command{gcc})
5227 This switch activates warnings for modulus values that seem suspicious.
5228 The cases caught are where the size is the same as the modulus (e.g.
5229 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5230 with no size clause. The guess in both cases is that 2**x was intended
5231 rather than x. In addition expressions of the form 2*x for small x
5232 generate a warning (the almost certainly accurate guess being that
5233 2**x was intended). The default is that these warnings are given.
5235 @item -gnatw.M
5236 @emph{Disable warnings on suspicious modulus values.}
5237 @cindex @option{-gnatw.M} (@command{gcc})
5238 This switch disables warnings for suspicious modulus values.
5240 @item -gnatwn
5241 @emph{Set normal warnings mode.}
5242 @cindex @option{-gnatwn} (@command{gcc})
5243 This switch sets normal warning mode, in which enabled warnings are
5244 issued and treated as warnings rather than errors. This is the default
5245 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5246 an explicit @option{-gnatws} or
5247 @option{-gnatwe}. It also cancels the effect of the
5248 implicit @option{-gnatwe} that is activated by the
5249 use of @option{-gnatg}.
5251 @item -gnatw.n
5252 @emph{Activate warnings on atomic synchronization.}
5253 @cindex @option{-gnatw.n} (@command{gcc})
5254 @cindex Atomic Synchronization, warnings
5255 This switch actives warnings when an access to an atomic variable
5256 requires the generation of atomic synchronization code. These
5257 warnings are off by default.
5258 @item -gnatw.N
5259 @emph{Suppress warnings on atomic synchronization.}
5260 @cindex @option{-gnatw.n} (@command{gcc})
5261 @cindex Atomic Synchronization, warnings
5262 This switch suppresses warnings when an access to an atomic variable
5263 requires the generation of atomic synchronization code.
5265 @item -gnatwo
5266 @emph{Activate warnings on address clause overlays.}
5267 @cindex @option{-gnatwo} (@command{gcc})
5268 @cindex Address Clauses, warnings
5269 This switch activates warnings for possibly unintended initialization
5270 effects of defining address clauses that cause one variable to overlap
5271 another. The default is that such warnings are generated.
5273 @item -gnatwO
5274 @emph{Suppress warnings on address clause overlays.}
5275 @cindex @option{-gnatwO} (@command{gcc})
5276 This switch suppresses warnings on possibly unintended initialization
5277 effects of defining address clauses that cause one variable to overlap
5278 another.
5280 @item -gnatw.o
5281 @emph{Activate warnings on modified but unreferenced out parameters.}
5282 @cindex @option{-gnatw.o} (@command{gcc})
5283 This switch activates warnings for variables that are modified by using
5284 them as actuals for a call to a procedure with an out mode formal, where
5285 the resulting assigned value is never read. It is applicable in the case
5286 where there is more than one out mode formal. If there is only one out
5287 mode formal, the warning is issued by default (controlled by -gnatwu).
5288 The warning is suppressed for volatile
5289 variables and also for variables that are renamings of other variables
5290 or for which an address clause is given.
5291 The default is that these warnings are not given.
5293 @item -gnatw.O
5294 @emph{Disable warnings on modified but unreferenced out parameters.}
5295 @cindex @option{-gnatw.O} (@command{gcc})
5296 This switch suppresses warnings for variables that are modified by using
5297 them as actuals for a call to a procedure with an out mode formal, where
5298 the resulting assigned value is never read.
5300 @item -gnatwp
5301 @emph{Activate warnings on ineffective pragma Inlines.}
5302 @cindex @option{-gnatwp} (@command{gcc})
5303 @cindex Inlining, warnings
5304 This switch activates warnings for failure of front end inlining
5305 (activated by @option{-gnatN}) to inline a particular call. There are
5306 many reasons for not being able to inline a call, including most
5307 commonly that the call is too complex to inline. The default is
5308 that such warnings are not given.
5309 Warnings on ineffective inlining by the gcc back-end can be activated
5310 separately, using the gcc switch -Winline.
5312 @item -gnatwP
5313 @emph{Suppress warnings on ineffective pragma Inlines.}
5314 @cindex @option{-gnatwP} (@command{gcc})
5315 This switch suppresses warnings on ineffective pragma Inlines. If the
5316 inlining mechanism cannot inline a call, it will simply ignore the
5317 request silently.
5319 @item -gnatw.p
5320 @emph{Activate warnings on parameter ordering.}
5321 @cindex @option{-gnatw.p} (@command{gcc})
5322 @cindex Parameter order, warnings
5323 This switch activates warnings for cases of suspicious parameter
5324 ordering when the list of arguments are all simple identifiers that
5325 match the names of the formals, but are in a different order. The
5326 warning is suppressed if any use of named parameter notation is used,
5327 so this is the appropriate way to suppress a false positive (and
5328 serves to emphasize that the "misordering" is deliberate). The
5329 default is that such warnings are not given.
5331 @item -gnatw.P
5332 @emph{Suppress warnings on parameter ordering.}
5333 @cindex @option{-gnatw.P} (@command{gcc})
5334 This switch suppresses warnings on cases of suspicious parameter
5335 ordering.
5337 @item -gnatwq
5338 @emph{Activate warnings on questionable missing parentheses.}
5339 @cindex @option{-gnatwq} (@command{gcc})
5340 @cindex Parentheses, warnings
5341 This switch activates warnings for cases where parentheses are not used and
5342 the result is potential ambiguity from a readers point of view. For example
5343 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5344 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5345 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5346 follow the rule of always parenthesizing to make the association clear, and
5347 this warning switch warns if such parentheses are not present. The default
5348 is that these warnings are given.
5350 @item -gnatwQ
5351 @emph{Suppress warnings on questionable missing parentheses.}
5352 @cindex @option{-gnatwQ} (@command{gcc})
5353 This switch suppresses warnings for cases where the association is not
5354 clear and the use of parentheses is preferred.
5356 @item -gnatwr
5357 @emph{Activate warnings on redundant constructs.}
5358 @cindex @option{-gnatwr} (@command{gcc})
5359 This switch activates warnings for redundant constructs. The following
5360 is the current list of constructs regarded as redundant:
5362 @itemize @bullet
5363 @item
5364 Assignment of an item to itself.
5365 @item
5366 Type conversion that converts an expression to its own type.
5367 @item
5368 Use of the attribute @code{Base} where @code{typ'Base} is the same
5369 as @code{typ}.
5370 @item
5371 Use of pragma @code{Pack} when all components are placed by a record
5372 representation clause.
5373 @item
5374 Exception handler containing only a reraise statement (raise with no
5375 operand) which has no effect.
5376 @item
5377 Use of the operator abs on an operand that is known at compile time
5378 to be non-negative
5379 @item
5380 Comparison of boolean expressions to an explicit True value.
5381 @end itemize
5383 The default is that warnings for redundant constructs are not given.
5385 @item -gnatwR
5386 @emph{Suppress warnings on redundant constructs.}
5387 @cindex @option{-gnatwR} (@command{gcc})
5388 This switch suppresses warnings for redundant constructs.
5390 @item -gnatw.r
5391 @emph{Activate warnings for object renaming function.}
5392 @cindex @option{-gnatw.r} (@command{gcc})
5393 This switch activates warnings for an object renaming that renames a
5394 function call, which is equivalent to a constant declaration (as
5395 opposed to renaming the function itself).  The default is that these
5396 warnings are given.
5398 @item -gnatw.R
5399 @emph{Suppress warnings for object renaming function.}
5400 @cindex @option{-gnatwT} (@command{gcc})
5401 This switch suppresses warnings for object renaming function.
5403 @item -gnatws
5404 @emph{Suppress all warnings.}
5405 @cindex @option{-gnatws} (@command{gcc})
5406 This switch completely suppresses the
5407 output of all warning messages from the GNAT front end, including
5408 both warnings that can be controlled by switches described in this
5409 section, and those that are normally given unconditionally. The
5410 effect of this suppress action can only be cancelled by a subsequent
5411 use of the switch @option{-gnatwn}.
5413 Note that switch @option{-gnatws} does not suppress
5414 warnings from the @command{gcc} back end.
5415 To suppress these back end warnings as well, use the switch @option{-w}
5416 in addition to @option{-gnatws}. Also this switch has no effect on the
5417 handling of style check messages.
5419 @item -gnatw.s
5420 @emph{Activate warnings on overridden size clauses.}
5421 @cindex @option{-gnatw.s} (@command{gcc})
5422 @cindex Record Representation (component sizes)
5423 This switch activates warnings on component clauses in record
5424 representation clauses where the length given overrides that
5425 specified by an explicit size clause for the component type. A
5426 warning is similarly given in the array case if a specified
5427 component size overrides an explicit size clause for the array
5428 component type.
5430 @item -gnatw.S
5431 @emph{Suppress warnings on overridden size clauses.}
5432 @cindex @option{-gnatw.S} (@command{gcc})
5433 This switch suppresses warnings on component clauses in record
5434 representation clauses that override size clauses, and similar
5435 warnings when an array component size overrides a size clause.
5437 @item -gnatwt
5438 @emph{Activate warnings for tracking of deleted conditional code.}
5439 @cindex @option{-gnatwt} (@command{gcc})
5440 @cindex Deactivated code, warnings
5441 @cindex Deleted code, warnings
5442 This switch activates warnings for tracking of code in conditionals (IF and
5443 CASE statements) that is detected to be dead code which cannot be executed, and
5444 which is removed by the front end. This warning is off by default. This may be
5445 useful for detecting deactivated code in certified applications.
5447 @item -gnatwT
5448 @emph{Suppress warnings for tracking of deleted conditional code.}
5449 @cindex @option{-gnatwT} (@command{gcc})
5450 This switch suppresses warnings for tracking of deleted conditional code.
5452 @item -gnatw.t
5453 @emph{Activate warnings on suspicious contracts.}
5454 @cindex @option{-gnatw.t} (@command{gcc})
5455 This switch activates warnings on suspicious postconditions (whether a
5456 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5457 and suspicious contract cases (pragma @code{Contract_Cases}). A
5458 function postcondition or contract case is suspicious when no postcondition
5459 or contract case for this function mentions the result of the function.
5460 A procedure postcondition or contract case is suspicious when it only
5461 refers to the pre-state of the procedure, because in that case it should
5462 rather be expressed as a precondition. The default is that such warnings
5463 are not generated.
5465 @item -gnatw.T
5466 @emph{Suppress warnings on suspicious contracts.}
5467 @cindex @option{-gnatw.T} (@command{gcc})
5468 This switch suppresses warnings on suspicious postconditions.
5470 @item -gnatwu
5471 @emph{Activate warnings on unused entities.}
5472 @cindex @option{-gnatwu} (@command{gcc})
5473 This switch activates warnings to be generated for entities that
5474 are declared but not referenced, and for units that are @code{with}'ed
5475 and not
5476 referenced. In the case of packages, a warning is also generated if
5477 no entities in the package are referenced. This means that if a with'ed
5478 package is referenced but the only references are in @code{use}
5479 clauses or @code{renames}
5480 declarations, a warning is still generated. A warning is also generated
5481 for a generic package that is @code{with}'ed but never instantiated.
5482 In the case where a package or subprogram body is compiled, and there
5483 is a @code{with} on the corresponding spec
5484 that is only referenced in the body,
5485 a warning is also generated, noting that the
5486 @code{with} can be moved to the body. The default is that
5487 such warnings are not generated.
5488 This switch also activates warnings on unreferenced formals
5489 (it includes the effect of @option{-gnatwf}).
5491 @item -gnatwU
5492 @emph{Suppress warnings on unused entities.}
5493 @cindex @option{-gnatwU} (@command{gcc})
5494 This switch suppresses warnings for unused entities and packages.
5495 It also turns off warnings on unreferenced formals (and thus includes
5496 the effect of @option{-gnatwF}).
5498 @item -gnatw.u
5499 @emph{Activate warnings on unordered enumeration types.}
5500 @cindex @option{-gnatw.u} (@command{gcc})
5501 This switch causes enumeration types to be considered as conceptually
5502 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5503 The effect is to generate warnings in clients that use explicit comparisons
5504 or subranges, since these constructs both treat objects of the type as
5505 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5506 which the type is declared, or its body or subunits.) Please refer to
5507 the description of pragma @code{Ordered} in the
5508 @cite{@value{EDITION} Reference Manual} for further details.
5509 The default is that such warnings are not generated.
5511 @item -gnatw.U
5512 @emph{Deactivate warnings on unordered enumeration types.}
5513 @cindex @option{-gnatw.U} (@command{gcc})
5514 This switch causes all enumeration types to be considered as ordered, so
5515 that no warnings are given for comparisons or subranges for any type.
5517 @item -gnatwv
5518 @emph{Activate warnings on unassigned variables.}
5519 @cindex @option{-gnatwv} (@command{gcc})
5520 @cindex Unassigned variable warnings
5521 This switch activates warnings for access to variables which
5522 may not be properly initialized. The default is that
5523 such warnings are generated.
5525 @item -gnatwV
5526 @emph{Suppress warnings on unassigned variables.}
5527 @cindex @option{-gnatwV} (@command{gcc})
5528 This switch suppresses warnings for access to variables which
5529 may not be properly initialized.
5530 For variables of a composite type, the warning can also be suppressed in
5531 Ada 2005 by using a default initialization with a box. For example, if
5532 Table is an array of records whose components are only partially uninitialized,
5533 then the following code:
5535 @smallexample @c ada
5536    Tab : Table := (@b{others} => <>);
5537 @end smallexample
5539 will suppress warnings on subsequent statements that access components
5540 of variable Tab.
5542 @item -gnatw.v
5543 @emph{Activate info messages for non-default bit order.}
5544 @cindex @option{-gnatw.v} (@command{gcc})
5545 @cindex bit order warnings
5546 This switch activates messages (labeled "info", they are not warnings,
5547 just informational messages) about the effects of non-default bit-order
5548 on records to which a component clause is applied. The effect of specifying
5549 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5550 these messages, which are given by default, are useful in understanding the
5551 exact consequences of using this feature.
5553 @item -gnatw.V
5554 @emph{Suppress info messages for non-default bit order.}
5555 @cindex @option{-gnatw.V} (@command{gcc})
5556 This switch suppresses information messages for the effects of specifying
5557 non-default bit order on record components with component clauses.
5559 @item -gnatww
5560 @emph{Activate warnings on wrong low bound assumption.}
5561 @cindex @option{-gnatww} (@command{gcc})
5562 @cindex String indexing warnings
5563 This switch activates warnings for indexing an unconstrained string parameter
5564 with a literal or S'Length. This is a case where the code is assuming that the
5565 low bound is one, which is in general not true (for example when a slice is
5566 passed). The default is that such warnings are generated.
5568 @item -gnatwW
5569 @emph{Suppress warnings on wrong low bound assumption.}
5570 @cindex @option{-gnatwW} (@command{gcc})
5571 This switch suppresses warnings for indexing an unconstrained string parameter
5572 with a literal or S'Length. Note that this warning can also be suppressed
5573 in a particular case by adding an
5574 assertion that the lower bound is 1,
5575 as shown in the following example.
5577 @smallexample @c ada
5578    @b{procedure} K (S : String) @b{is}
5579       @b{pragma} Assert (S'First = 1);
5580       @dots{}
5581 @end smallexample
5583 @item -gnatw.w
5584 @emph{Activate warnings on Warnings Off pragmas}
5585 @cindex @option{-gnatw.w} (@command{gcc})
5586 @cindex Warnings Off control
5587 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5588 where either the pragma is entirely useless (because it suppresses no
5589 warnings), or it could be replaced by @code{pragma Unreferenced} or
5590 @code{pragma Unmodified}.
5591 Also activates warnings for the case of
5592 Warnings (Off, String), where either there is no matching
5593 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
5594 The default is that these warnings are not given.
5596 @item -gnatw.W
5597 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5598 @cindex @option{-gnatw.W} (@command{gcc})
5599 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
5601 @item -gnatwx
5602 @emph{Activate warnings on Export/Import pragmas.}
5603 @cindex @option{-gnatwx} (@command{gcc})
5604 @cindex Export/Import pragma warnings
5605 This switch activates warnings on Export/Import pragmas when
5606 the compiler detects a possible conflict between the Ada and
5607 foreign language calling sequences. For example, the use of
5608 default parameters in a convention C procedure is dubious
5609 because the C compiler cannot supply the proper default, so
5610 a warning is issued. The default is that such warnings are
5611 generated.
5613 @item -gnatwX
5614 @emph{Suppress warnings on Export/Import pragmas.}
5615 @cindex @option{-gnatwX} (@command{gcc})
5616 This switch suppresses warnings on Export/Import pragmas.
5617 The sense of this is that you are telling the compiler that
5618 you know what you are doing in writing the pragma, and it
5619 should not complain at you.
5621 @item -gnatw.x
5622 @emph{Activate warnings for No_Exception_Propagation mode.}
5623 @cindex @option{-gnatwm} (@command{gcc})
5624 This switch activates warnings for exception usage when pragma Restrictions
5625 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5626 explicit exception raises which are not covered by a local handler, and for
5627 exception handlers which do not cover a local raise. The default is that these
5628 warnings are not given.
5630 @item -gnatw.X
5631 @emph{Disable warnings for No_Exception_Propagation mode.}
5632 This switch disables warnings for exception usage when pragma Restrictions
5633 (No_Exception_Propagation) is in effect.
5635 @item -gnatwy
5636 @emph{Activate warnings for Ada compatibility issues.}
5637 @cindex @option{-gnatwy} (@command{gcc})
5638 @cindex Ada compatibility issues warnings
5639 For the most part, newer versions of Ada are upwards compatible
5640 with older versions. For example, Ada 2005 programs will almost
5641 always work when compiled as Ada 2012.
5642 However there are some exceptions (for example the fact that
5643 @code{some} is now a reserved word in Ada 2012). This
5644 switch activates several warnings to help in identifying
5645 and correcting such incompatibilities. The default is that
5646 these warnings are generated. Note that at one point Ada 2005
5647 was called Ada 0Y, hence the choice of character.
5649 @item -gnatwY
5650 @emph{Disable warnings for Ada compatibility issues.}
5651 @cindex @option{-gnatwY} (@command{gcc})
5652 @cindex Ada compatibility issues warnings
5653 This switch suppresses the warnings intended to help in identifying
5654 incompatibilities between Ada language versions.
5656 @item -gnatw.y
5657 @emph{Activate information messages for why package spec needs body}
5658 @cindex @option{-gnatw.y} (@command{gcc})
5659 @cindex Package spec needing body
5660 There are a number of cases in which a package spec needs a body.
5661 For example, the use of pragma Elaborate_Body, or the declaration
5662 of a procedure specification requiring a completion. This switch
5663 causes information messages to be output showing why a package
5664 specification requires a body. This can be useful in the case of
5665 a large package specification which is unexpectedly requiring a
5666 body. The default is that such information messages are not output.
5668 @item -gnatw.Y
5669 @emph{Disable information messages for why package spec needs body}
5670 @cindex @option{-gnatw.Y} (@command{gcc})
5671 @cindex No information messages for why package spec needs body
5672 This switch suppresses the output of information messages showing why
5673 a package specification needs a body.
5675 @item -gnatwz
5676 @emph{Activate warnings on unchecked conversions.}
5677 @cindex @option{-gnatwz} (@command{gcc})
5678 @cindex Unchecked_Conversion warnings
5679 This switch activates warnings for unchecked conversions
5680 where the types are known at compile time to have different
5681 sizes. The default
5682 is that such warnings are generated. Warnings are also
5683 generated for subprogram pointers with different conventions,
5684 and, on VMS only, for data pointers with different conventions.
5686 @item -gnatwZ
5687 @emph{Suppress warnings on unchecked conversions.}
5688 @cindex @option{-gnatwZ} (@command{gcc})
5689 This switch suppresses warnings for unchecked conversions
5690 where the types are known at compile time to have different
5691 sizes or conventions.
5693 @item -gnatw.z
5694 @emph{Activate warnings for size not a multiple of alignment.}
5695 @cindex @option{-gnatw.z} (@command{gcc})
5696 @cindex Size/Alignment warnings
5697 This switch activates warnings for cases of record types with
5698 specified @code{Size} and @code{Alignment} attributes where the
5699 size is not a multiple of the alignment, resulting in an object
5700 size that is greater than the specified size. The default
5701 is that such warnings are generated.
5703 @item -gnatw.Z
5704 @emph{Suppress warnings for size not a multiple of alignment.}
5705 @cindex @option{-gnatw.Z} (@command{gcc})
5706 @cindex Size/Alignment warnings
5707 This switch suppresses warnings for cases of record types with
5708 specified @code{Size} and @code{Alignment} attributes where the
5709 size is not a multiple of the alignment, resulting in an object
5710 size that is greater than the specified size.
5711 The warning can also be
5712 suppressed by giving an explicit @code{Object_Size} value.
5714 @item -Wunused
5715 @cindex @option{-Wunused}
5716 The warnings controlled by the @option{-gnatw} switch are generated by
5717 the front end of the compiler. The @option{GCC} back end can provide
5718 additional warnings and they are controlled by the @option{-W} switch.
5719 For example, @option{-Wunused} activates back end
5720 warnings for entities that are declared but not referenced.
5722 @item -Wuninitialized
5723 @cindex @option{-Wuninitialized}
5724 Similarly, @option{-Wuninitialized} activates
5725 the back end warning for uninitialized variables. This switch must be
5726 used in conjunction with an optimization level greater than zero.
5728 @item -Wstack-usage=@var{len}
5729 @cindex @option{-Wstack-usage}
5730 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5731 See @ref{Static Stack Usage Analysis} for details.
5733 @item -Wall
5734 @cindex @option{-Wall}
5735 This switch enables most warnings from the @option{GCC} back end.
5736 The code generator detects a number of warning situations that are missed
5737 by the @option{GNAT} front end, and this switch can be used to activate them.
5738 The use of this switch also sets the default front end warning mode to
5739 @option{-gnatwa}, that is, most front end warnings activated as well.
5741 @item -w
5742 @cindex @option{-w}
5743 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5744 The use of this switch also sets the default front end warning mode to
5745 @option{-gnatws}, that is, front end warnings suppressed as well.
5747 @item -Werror
5748 @cindex @option{-Werror}
5749 This switch causes warnings from the @option{GCC} back end to be treated as
5750 errors.  The warning string still appears, but the warning messages are
5751 counted as errors, and prevent the generation of an object file.
5753 @end table
5755 @noindent
5756 A string of warning parameters can be used in the same parameter. For example:
5758 @smallexample
5759 -gnatwaGe
5760 @end smallexample
5762 @noindent
5763 will turn on all optional warnings except for unrecognized pragma warnings,
5764 and also specify that warnings should be treated as errors.
5766 When no switch @option{-gnatw} is used, this is equivalent to:
5768 @table @option
5769 @c !sort!
5770 @item -gnatw.a
5771 @item -gnatwB
5772 @item -gnatw.b
5773 @item -gnatwC
5774 @item -gnatw.C
5775 @item -gnatwD
5776 @item -gnatwF
5777 @item -gnatwg
5778 @item -gnatwH
5779 @item -gnatwi
5780 @item -gnatw.I
5781 @item -gnatwJ
5782 @item -gnatwK
5783 @item -gnatwL
5784 @item -gnatw.L
5785 @item -gnatwM
5786 @item -gnatw.m
5787 @item -gnatwn
5788 @item -gnatwo
5789 @item -gnatw.O
5790 @item -gnatwP
5791 @item -gnatw.P
5792 @item -gnatwq
5793 @item -gnatwR
5794 @item -gnatw.R
5795 @item -gnatw.S
5796 @item -gnatwT
5797 @item -gnatw.T
5798 @item -gnatwU
5799 @item -gnatwv
5800 @item -gnatww
5801 @item -gnatw.W
5802 @item -gnatwx
5803 @item -gnatw.X
5804 @item -gnatwy
5805 @item -gnatwz
5807 @end table
5809 @node Debugging and Assertion Control
5810 @subsection Debugging and Assertion Control
5812 @table @option
5813 @item -gnata
5814 @cindex @option{-gnata} (@command{gcc})
5815 @findex Assert
5816 @findex Debug
5817 @cindex Assertions
5819 @noindent
5820 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5821 are ignored. This switch, where @samp{a} stands for assert, causes
5822 @code{Assert} and @code{Debug} pragmas to be activated.
5824 The pragmas have the form:
5826 @smallexample
5827 @cartouche
5828    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5829                       @var{static-string-expression}@r{]})
5830    @b{pragma} Debug (@var{procedure call})
5831 @end cartouche
5832 @end smallexample
5834 @noindent
5835 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5836 If the result is @code{True}, the pragma has no effect (other than
5837 possible side effects from evaluating the expression). If the result is
5838 @code{False}, the exception @code{Assert_Failure} declared in the package
5839 @code{System.Assertions} is
5840 raised (passing @var{static-string-expression}, if present, as the
5841 message associated with the exception). If no string expression is
5842 given the default is a string giving the file name and line number
5843 of the pragma.
5845 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5846 @code{pragma Debug} may appear within a declaration sequence, allowing
5847 debugging procedures to be called between declarations.
5849 @end table
5851 @node Validity Checking
5852 @subsection Validity Checking
5853 @findex Validity Checking
5855 @noindent
5856 The Ada Reference Manual defines the concept of invalid values (see
5857 RM 13.9.1). The primary source of invalid values is uninitialized
5858 variables. A scalar variable that is left uninitialized may contain
5859 an invalid value; the concept of invalid does not apply to access or
5860 composite types.
5862 It is an error to read an invalid value, but the RM does not require
5863 run-time checks to detect such errors, except for some minimal
5864 checking to prevent erroneous execution (i.e. unpredictable
5865 behavior). This corresponds to the @option{-gnatVd} switch below,
5866 which is the default. For example, by default, if the expression of a
5867 case statement is invalid, it will raise Constraint_Error rather than
5868 causing a wild jump, and if an array index on the left-hand side of an
5869 assignment is invalid, it will raise Constraint_Error rather than
5870 overwriting an arbitrary memory location.
5872 The @option{-gnatVa} may be used to enable additional validity checks,
5873 which are not required by the RM. These checks are often very
5874 expensive (which is why the RM does not require them). These checks
5875 are useful in tracking down uninitialized variables, but they are
5876 not usually recommended for production builds, and in particular
5877 we do not recommend using these extra validity checking options in
5878 combination with optimization, since this can confuse the optimizer.
5879 If performance is a consideration, leading to the need to optimize,
5880 then the validity checking options should not be used.
5882 The other @option{-gnatV@var{x}} switches below allow finer-grained
5883 control; you can enable whichever validity checks you desire. However,
5884 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5885 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5886 sufficient for non-debugging use.
5888 The @option{-gnatB} switch tells the compiler to assume that all
5889 values are valid (that is, within their declared subtype range)
5890 except in the context of a use of the Valid attribute. This means
5891 the compiler can generate more efficient code, since the range
5892 of values is better known at compile time. However, an uninitialized
5893 variable can cause wild jumps and memory corruption in this mode.
5895 The @option{-gnatV@var{x}} switch allows control over the validity
5896 checking mode as described below.
5897 The @code{x} argument is a string of letters that
5898 indicate validity checks that are performed or not performed in addition
5899 to the default checks required by Ada as described above.
5901 @table @option
5902 @c !sort!
5903 @item -gnatVa
5904 @emph{All validity checks.}
5905 @cindex @option{-gnatVa} (@command{gcc})
5906 All validity checks are turned on.
5907 That is, @option{-gnatVa} is
5908 equivalent to @option{gnatVcdfimorst}.
5910 @item -gnatVc
5911 @emph{Validity checks for copies.}
5912 @cindex @option{-gnatVc} (@command{gcc})
5913 The right hand side of assignments, and the initializing values of
5914 object declarations are validity checked.
5916 @item -gnatVd
5917 @emph{Default (RM) validity checks.}
5918 @cindex @option{-gnatVd} (@command{gcc})
5919 Some validity checks are done by default following normal Ada semantics
5920 (RM 13.9.1 (9-11)).
5921 A check is done in case statements that the expression is within the range
5922 of the subtype. If it is not, Constraint_Error is raised.
5923 For assignments to array components, a check is done that the expression used
5924 as index is within the range. If it is not, Constraint_Error is raised.
5925 Both these validity checks may be turned off using switch @option{-gnatVD}.
5926 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5927 switch @option{-gnatVd} will leave the checks turned on.
5928 Switch @option{-gnatVD} should be used only if you are sure that all such
5929 expressions have valid values. If you use this switch and invalid values
5930 are present, then the program is erroneous, and wild jumps or memory
5931 overwriting may occur.
5933 @item -gnatVe
5934 @emph{Validity checks for elementary components.}
5935 @cindex @option{-gnatVe} (@command{gcc})
5936 In the absence of this switch, assignments to record or array components are
5937 not validity checked, even if validity checks for assignments generally
5938 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5939 require valid data, but assignment of individual components does. So for
5940 example, there is a difference between copying the elements of an array with a
5941 slice assignment, compared to assigning element by element in a loop. This
5942 switch allows you to turn off validity checking for components, even when they
5943 are assigned component by component.
5945 @item -gnatVf
5946 @emph{Validity checks for floating-point values.}
5947 @cindex @option{-gnatVf} (@command{gcc})
5948 In the absence of this switch, validity checking occurs only for discrete
5949 values. If @option{-gnatVf} is specified, then validity checking also applies
5950 for floating-point values, and NaNs and infinities are considered invalid,
5951 as well as out of range values for constrained types. Note that this means
5952 that standard IEEE infinity mode is not allowed. The exact contexts
5953 in which floating-point values are checked depends on the setting of other
5954 options. For example,
5955 @option{-gnatVif} or
5956 @option{-gnatVfi}
5957 (the order does not matter) specifies that floating-point parameters of mode
5958 @code{in} should be validity checked.
5960 @item -gnatVi
5961 @emph{Validity checks for @code{in} mode parameters}
5962 @cindex @option{-gnatVi} (@command{gcc})
5963 Arguments for parameters of mode @code{in} are validity checked in function
5964 and procedure calls at the point of call.
5966 @item -gnatVm
5967 @emph{Validity checks for @code{in out} mode parameters.}
5968 @cindex @option{-gnatVm} (@command{gcc})
5969 Arguments for parameters of mode @code{in out} are validity checked in
5970 procedure calls at the point of call. The @code{'m'} here stands for
5971 modify, since this concerns parameters that can be modified by the call.
5972 Note that there is no specific option to test @code{out} parameters,
5973 but any reference within the subprogram will be tested in the usual
5974 manner, and if an invalid value is copied back, any reference to it
5975 will be subject to validity checking.
5977 @item -gnatVn
5978 @emph{No validity checks.}
5979 @cindex @option{-gnatVn} (@command{gcc})
5980 This switch turns off all validity checking, including the default checking
5981 for case statements and left hand side subscripts. Note that the use of
5982 the switch @option{-gnatp} suppresses all run-time checks, including
5983 validity checks, and thus implies @option{-gnatVn}. When this switch
5984 is used, it cancels any other @option{-gnatV} previously issued.
5986 @item -gnatVo
5987 @emph{Validity checks for operator and attribute operands.}
5988 @cindex @option{-gnatVo} (@command{gcc})
5989 Arguments for predefined operators and attributes are validity checked.
5990 This includes all operators in package @code{Standard},
5991 the shift operators defined as intrinsic in package @code{Interfaces}
5992 and operands for attributes such as @code{Pos}. Checks are also made
5993 on individual component values for composite comparisons, and on the
5994 expressions in type conversions and qualified expressions. Checks are
5995 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5997 @item -gnatVp
5998 @emph{Validity checks for parameters.}
5999 @cindex @option{-gnatVp} (@command{gcc})
6000 This controls the treatment of parameters within a subprogram (as opposed
6001 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6002 of parameters on a call. If either of these call options is used, then
6003 normally an assumption is made within a subprogram that the input arguments
6004 have been validity checking at the point of call, and do not need checking
6005 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6006 is not made, and parameters are not assumed to be valid, so their validity
6007 will be checked (or rechecked) within the subprogram.
6009 @item -gnatVr
6010 @emph{Validity checks for function returns.}
6011 @cindex @option{-gnatVr} (@command{gcc})
6012 The expression in @code{return} statements in functions is validity
6013 checked.
6015 @item -gnatVs
6016 @emph{Validity checks for subscripts.}
6017 @cindex @option{-gnatVs} (@command{gcc})
6018 All subscripts expressions are checked for validity, whether they appear
6019 on the right side or left side (in default mode only left side subscripts
6020 are validity checked).
6022 @item -gnatVt
6023 @emph{Validity checks for tests.}
6024 @cindex @option{-gnatVt} (@command{gcc})
6025 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6026 statements are checked, as well as guard expressions in entry calls.
6028 @end table
6030 @noindent
6031 The @option{-gnatV} switch may be followed by
6032 a string of letters
6033 to turn on a series of validity checking options.
6034 For example,
6035 @option{-gnatVcr}
6036 specifies that in addition to the default validity checking, copies and
6037 function return expressions are to be validity checked.
6038 In order to make it easier
6039 to specify the desired combination of effects,
6040 the upper case letters @code{CDFIMORST} may
6041 be used to turn off the corresponding lower case option.
6042 Thus
6043 @option{-gnatVaM}
6044 turns on all validity checking options except for
6045 checking of @code{@b{in out}} procedure arguments.
6047 The specification of additional validity checking generates extra code (and
6048 in the case of @option{-gnatVa} the code expansion can be substantial).
6049 However, these additional checks can be very useful in detecting
6050 uninitialized variables, incorrect use of unchecked conversion, and other
6051 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6052 is useful in conjunction with the extra validity checking, since this
6053 ensures that wherever possible uninitialized variables have invalid values.
6055 See also the pragma @code{Validity_Checks} which allows modification of
6056 the validity checking mode at the program source level, and also allows for
6057 temporary disabling of validity checks.
6059 @node Style Checking
6060 @subsection Style Checking
6061 @findex Style checking
6063 @noindent
6064 The @option{-gnatyx} switch
6065 @cindex @option{-gnaty} (@command{gcc})
6066 causes the compiler to
6067 enforce specified style rules. A limited set of style rules has been used
6068 in writing the GNAT sources themselves. This switch allows user programs
6069 to activate all or some of these checks. If the source program fails a
6070 specified style check, an appropriate message is given, preceded by
6071 the character sequence ``(style)''. This message does not prevent
6072 successful compilation (unless the @option{-gnatwe} switch is used).
6074 Note that this is by no means intended to be a general facility for
6075 checking arbitrary coding standards. It is simply an embedding of the
6076 style rules we have chosen for the GNAT sources. If you are starting
6077 a project which does not have established style standards, you may
6078 find it useful to adopt the entire set of GNAT coding standards, or
6079 some subset of them.
6080 @ifclear FSFEDITION
6081 If you already have an established set of coding
6082 standards, then the selected style checking options may
6083 indeed correspond to choices you have made, but for general checking
6084 of an existing set of coding rules, you should look to the gnatcheck
6085 tool, which is designed for that purpose.
6086 @end ifclear
6088 The string @var{x} is a sequence of letters or digits
6089 indicating the particular style
6090 checks to be performed. The following checks are defined:
6092 @table @option
6093 @c !sort!
6094 @item 0-9
6095 @emph{Specify indentation level.}
6096 If a digit from 1-9 appears
6097 in the string after @option{-gnaty}
6098 then proper indentation is checked, with the digit indicating the
6099 indentation level required. A value of zero turns off this style check.
6100 The general style of required indentation is as specified by
6101 the examples in the Ada Reference Manual. Full line comments must be
6102 aligned with the @code{--} starting on a column that is a multiple of
6103 the alignment level, or they may be aligned the same way as the following
6104 non-blank line (this is useful when full line comments appear in the middle
6105 of a statement, or they may be aligned with the source line on the previous
6106 non-blank line.
6108 @item a
6109 @emph{Check attribute casing.}
6110 Attribute names, including the case of keywords such as @code{digits}
6111 used as attributes names, must be written in mixed case, that is, the
6112 initial letter and any letter following an underscore must be uppercase.
6113 All other letters must be lowercase.
6115 @item A
6116 @emph{Use of array index numbers in array attributes.}
6117 When using the array attributes First, Last, Range,
6118 or Length, the index number must be omitted for one-dimensional arrays
6119 and is required for multi-dimensional arrays.
6121 @item b
6122 @emph{Blanks not allowed at statement end.}
6123 Trailing blanks are not allowed at the end of statements. The purpose of this
6124 rule, together with h (no horizontal tabs), is to enforce a canonical format
6125 for the use of blanks to separate source tokens.
6127 @item B
6128 @emph{Check Boolean operators.}
6129 The use of AND/OR operators is not permitted except in the cases of modular
6130 operands, array operands, and simple stand-alone boolean variables or
6131 boolean constants. In all other cases @code{and then}/@code{or else} are
6132 required.
6134 @item c
6135 @emph{Check comments, double space.}
6136 Comments must meet the following set of rules:
6138 @itemize @bullet
6140 @item
6141 The ``@code{--}'' that starts the column must either start in column one,
6142 or else at least one blank must precede this sequence.
6144 @item
6145 Comments that follow other tokens on a line must have at least one blank
6146 following the ``@code{--}'' at the start of the comment.
6148 @item
6149 Full line comments must have at least two blanks following the
6150 ``@code{--}'' that starts the comment, with the following exceptions.
6152 @item
6153 A line consisting only of the ``@code{--}'' characters, possibly preceded
6154 by blanks is permitted.
6156 @item
6157 A comment starting with ``@code{--x}'' where @code{x} is a special character
6158 is permitted.
6159 This allows proper processing of the output generated by specialized tools
6160 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6161 annotation
6162 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6163 special character is defined as being in one of the ASCII ranges
6164 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6165 Note that this usage is not permitted
6166 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6168 @item
6169 A line consisting entirely of minus signs, possibly preceded by blanks, is
6170 permitted. This allows the construction of box comments where lines of minus
6171 signs are used to form the top and bottom of the box.
6173 @item
6174 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6175 least one blank follows the initial ``@code{--}''. Together with the preceding
6176 rule, this allows the construction of box comments, as shown in the following
6177 example:
6178 @smallexample
6179 ---------------------------
6180 -- This is a box comment --
6181 -- with two text lines.  --
6182 ---------------------------
6183 @end smallexample
6184 @end itemize
6186 @item C
6187 @emph{Check comments, single space.}
6188 This is identical to @code{c} except that only one space
6189 is required following the @code{--} of a comment instead of two.
6191 @item d
6192 @emph{Check no DOS line terminators present.}
6193 All lines must be terminated by a single ASCII.LF
6194 character (in particular the DOS line terminator sequence CR/LF is not
6195 allowed).
6197 @item e
6198 @emph{Check end/exit labels.}
6199 Optional labels on @code{end} statements ending subprograms and on
6200 @code{exit} statements exiting named loops, are required to be present.
6202 @item f
6203 @emph{No form feeds or vertical tabs.}
6204 Neither form feeds nor vertical tab characters are permitted
6205 in the source text.
6207 @item g
6208 @emph{GNAT style mode.}
6209 The set of style check switches is set to match that used by the GNAT sources.
6210 This may be useful when developing code that is eventually intended to be
6211 incorporated into GNAT. Currently this is equivalent to @option{-gnatwydISux})
6212 but additional style switches may be added to this set in the future without
6213 advance notice.
6215 @item h
6216 @emph{No horizontal tabs.}
6217 Horizontal tab characters are not permitted in the source text.
6218 Together with the b (no blanks at end of line) check, this
6219 enforces a canonical form for the use of blanks to separate
6220 source tokens.
6222 @item i
6223 @emph{Check if-then layout.}
6224 The keyword @code{then} must appear either on the same
6225 line as corresponding @code{if}, or on a line on its own, lined
6226 up under the @code{if}.
6228 @item I
6229 @emph{check mode IN keywords.}
6230 Mode @code{in} (the default mode) is not
6231 allowed to be given explicitly. @code{in out} is fine,
6232 but not @code{in} on its own.
6234 @item k
6235 @emph{Check keyword casing.}
6236 All keywords must be in lower case (with the exception of keywords
6237 such as @code{digits} used as attribute names to which this check
6238 does not apply).
6240 @item l
6241 @emph{Check layout.}
6242 Layout of statement and declaration constructs must follow the
6243 recommendations in the Ada Reference Manual, as indicated by the
6244 form of the syntax rules. For example an @code{else} keyword must
6245 be lined up with the corresponding @code{if} keyword.
6247 There are two respects in which the style rule enforced by this check
6248 option are more liberal than those in the Ada Reference Manual. First
6249 in the case of record declarations, it is permissible to put the
6250 @code{record} keyword on the same line as the @code{type} keyword, and
6251 then the @code{end} in @code{end record} must line up under @code{type}.
6252 This is also permitted when the type declaration is split on two lines.
6253 For example, any of the following three layouts is acceptable:
6255 @smallexample @c ada
6256 @cartouche
6257 @b{type} q @b{is} @b{record}
6258    a : integer;
6259    b : integer;
6260 @b{end} @b{record};
6262 @b{type} q @b{is}
6263    @b{record}
6264       a : integer;
6265       b : integer;
6266    @b{end} @b{record};
6268 @b{type} q @b{is}
6269    @b{record}
6270       a : integer;
6271       b : integer;
6272 @b{end} @b{record};
6274 @end cartouche
6275 @end smallexample
6277 @noindent
6278 Second, in the case of a block statement, a permitted alternative
6279 is to put the block label on the same line as the @code{declare} or
6280 @code{begin} keyword, and then line the @code{end} keyword up under
6281 the block label. For example both the following are permitted:
6283 @smallexample @c ada
6284 @cartouche
6285 Block : @b{declare}
6286    A : Integer := 3;
6287 @b{begin}
6288    Proc (A, A);
6289 @b{end} Block;
6291 Block :
6292    @b{declare}
6293       A : Integer := 3;
6294    @b{begin}
6295       Proc (A, A);
6296    @b{end} Block;
6297 @end cartouche
6298 @end smallexample
6300 @noindent
6301 The same alternative format is allowed for loops. For example, both of
6302 the following are permitted:
6304 @smallexample @c ada
6305 @cartouche
6306 Clear : @b{while} J < 10 @b{loop}
6307    A (J) := 0;
6308 @b{end} @b{loop} Clear;
6310 Clear :
6311    @b{while} J < 10 @b{loop}
6312       A (J) := 0;
6313    @b{end} @b{loop} Clear;
6314 @end cartouche
6315 @end smallexample
6317 @item Lnnn
6318 @emph{Set maximum nesting level.}
6319 The maximum level of nesting of constructs (including subprograms, loops,
6320 blocks, packages, and conditionals) may not exceed the given value
6321 @option{nnn}. A value of zero disconnects this style check.
6323 @item m
6324 @emph{Check maximum line length.}
6325 The length of source lines must not exceed 79 characters, including
6326 any trailing blanks. The value of 79 allows convenient display on an
6327 80 character wide device or window, allowing for possible special
6328 treatment of 80 character lines. Note that this count is of
6329 characters in the source text. This means that a tab character counts
6330 as one character in this count and a wide character sequence counts as
6331 a single character (however many bytes are needed in the encoding).
6333 @item Mnnn
6334 @emph{Set maximum line length.}
6335 The length of lines must not exceed the
6336 given value @option{nnn}. The maximum value that can be specified is 32767.
6337 If neither style option for setting the line length is used, then the
6338 default is 255. This also controls the maximum length of lexical elements,
6339 where the only restriction is that they must fit on a single line.
6341 @item n
6342 @emph{Check casing of entities in Standard.}
6343 Any identifier from Standard must be cased
6344 to match the presentation in the Ada Reference Manual (for example,
6345 @code{Integer} and @code{ASCII.NUL}).
6347 @item N
6348 @emph{Turn off all style checks.}
6349 All style check options are turned off.
6351 @item o
6352 @emph{Check order of subprogram bodies.}
6353 All subprogram bodies in a given scope
6354 (e.g.@: a package body) must be in alphabetical order. The ordering
6355 rule uses normal Ada rules for comparing strings, ignoring casing
6356 of letters, except that if there is a trailing numeric suffix, then
6357 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6358 before Junk10).
6360 @item O
6361 @emph{Check that overriding subprograms are explicitly marked as such.}
6362 The declaration of a primitive operation of a type extension that overrides
6363 an inherited operation must carry an overriding indicator.
6365 @item p
6366 @emph{Check pragma casing.}
6367 Pragma names must be written in mixed case, that is, the
6368 initial letter and any letter following an underscore must be uppercase.
6369 All other letters must be lowercase. An exception is that SPARK_Mode is
6370 allowed as an alternative for Spark_Mode.
6372 @item r
6373 @emph{Check references.}
6374 All identifier references must be cased in the same way as the
6375 corresponding declaration. No specific casing style is imposed on
6376 identifiers. The only requirement is for consistency of references
6377 with declarations.
6379 @item s
6380 @emph{Check separate specs.}
6381 Separate declarations (``specs'') are required for subprograms (a
6382 body is not allowed to serve as its own declaration). The only
6383 exception is that parameterless library level procedures are
6384 not required to have a separate declaration. This exception covers
6385 the most frequent form of main program procedures.
6387 @item S
6388 @emph{Check no statements after @code{then}/@code{else}.}
6389 No statements are allowed
6390 on the same line as a @code{then} or @code{else} keyword following the
6391 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6392 affected, and a special exception allows a pragma to appear after @code{else}.
6394 @item t
6395 @emph{Check token spacing.}
6396 The following token spacing rules are enforced:
6398 @itemize @bullet
6400 @item
6401 The keywords @code{abs} and @code{not} must be followed by a space.
6403 @item
6404 The token @code{=>} must be surrounded by spaces.
6406 @item
6407 The token @code{<>} must be preceded by a space or a left parenthesis.
6409 @item
6410 Binary operators other than @code{**} must be surrounded by spaces.
6411 There is no restriction on the layout of the @code{**} binary operator.
6413 @item
6414 Colon must be surrounded by spaces.
6416 @item
6417 Colon-equal (assignment, initialization) must be surrounded by spaces.
6419 @item
6420 Comma must be the first non-blank character on the line, or be
6421 immediately preceded by a non-blank character, and must be followed
6422 by a space.
6424 @item
6425 If the token preceding a left parenthesis ends with a letter or digit, then
6426 a space must separate the two tokens.
6428 @item
6429 if the token following a right parenthesis starts with a letter or digit, then
6430 a space must separate the two tokens.
6432 @item
6433 A right parenthesis must either be the first non-blank character on
6434 a line, or it must be preceded by a non-blank character.
6436 @item
6437 A semicolon must not be preceded by a space, and must not be followed by
6438 a non-blank character.
6440 @item
6441 A unary plus or minus may not be followed by a space.
6443 @item
6444 A vertical bar must be surrounded by spaces.
6445 @end itemize
6447 @item
6448 Exactly one blank (and no other white space) must appear between
6449 a @code{not} token and a following @code{in} token.
6451 @item u
6452 @emph{Check unnecessary blank lines.}
6453 Unnecessary blank lines are not allowed. A blank line is considered
6454 unnecessary if it appears at the end of the file, or if more than
6455 one blank line occurs in sequence.
6457 @item x
6458 @emph{Check extra parentheses.}
6459 Unnecessary extra level of parentheses (C-style) are not allowed
6460 around conditions in @code{if} statements, @code{while} statements and
6461 @code{exit} statements.
6463 @item y
6464 @emph{Set all standard style check options}
6465 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6466 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6467 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6468 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6470 @item -
6471 @emph{Remove style check options}
6472 This causes any subsequent options in the string to act as canceling the
6473 corresponding style check option. To cancel maximum nesting level control,
6474 use @option{L} parameter witout any integer value after that, because any
6475 digit following @option{-} in the parameter string of the @option{-gnaty}
6476 option will be threated as canceling indentation check. The same is true
6477 for @option{M} parameter. @option{y} and @option{N} parameters are not
6478 allowed after @option{-}.
6480 @item +
6481 This causes any subsequent options in the string to enable the corresponding
6482 style check option. That is, it cancels the effect of a previous -,
6483 if any.
6485 @end table
6487 @noindent
6488 In the above rules, appearing in column one is always permitted, that is,
6489 counts as meeting either a requirement for a required preceding space,
6490 or as meeting a requirement for no preceding space.
6492 Appearing at the end of a line is also always permitted, that is, counts
6493 as meeting either a requirement for a following space, or as meeting
6494 a requirement for no following space.
6496 @noindent
6497 If any of these style rules is violated, a message is generated giving
6498 details on the violation. The initial characters of such messages are
6499 always ``@code{(style)}''. Note that these messages are treated as warning
6500 messages, so they normally do not prevent the generation of an object
6501 file. The @option{-gnatwe} switch can be used to treat warning messages,
6502 including style messages, as fatal errors.
6504 The switch
6505 @option{-gnaty} on its own (that is not
6506 followed by any letters or digits) is equivalent
6507 to the use of @option{-gnatyy} as described above, that is all
6508 built-in standard style check options are enabled.
6511 The switch
6512 @option{-gnatyN}
6513 clears any previously set style checks.
6515 @node Run-Time Checks
6516 @subsection Run-Time Checks
6517 @cindex Division by zero
6518 @cindex Access before elaboration
6519 @cindex Checks, division by zero
6520 @cindex Checks, access before elaboration
6521 @cindex Checks, stack overflow checking
6523 @noindent
6524 By default, the following checks are suppressed: integer overflow
6525 checks, stack overflow checks, and checks for access before
6526 elaboration on subprogram calls. All other checks, including range
6527 checks and array bounds checks, are turned on by default. The
6528 following @command{gcc} switches refine this default behavior.
6530 @table @option
6531 @c !sort!
6532 @item -gnatp
6533 @cindex @option{-gnatp} (@command{gcc})
6534 @cindex Suppressing checks
6535 @cindex Checks, suppressing
6536 @findex Suppress
6537 This switch causes the unit to be compiled
6538 as though @code{pragma Suppress (All_checks)}
6539 had been present in the source. Validity checks are also eliminated (in
6540 other words @option{-gnatp} also implies @option{-gnatVn}.
6541 Use this switch to improve the performance
6542 of the code at the expense of safety in the presence of invalid data or
6543 program bugs.
6545 Note that when checks are suppressed, the compiler is allowed, but not
6546 required, to omit the checking code. If the run-time cost of the
6547 checking code is zero or near-zero, the compiler will generate it even
6548 if checks are suppressed. In particular, if the compiler can prove
6549 that a certain check will necessarily fail, it will generate code to
6550 do an unconditional ``raise'', even if checks are suppressed. The
6551 compiler warns in this case. Another case in which checks may not be
6552 eliminated is when they are embedded in certain run time routines such
6553 as math library routines.
6555 Of course, run-time checks are omitted whenever the compiler can prove
6556 that they will not fail, whether or not checks are suppressed.
6558 Note that if you suppress a check that would have failed, program
6559 execution is erroneous, which means the behavior is totally
6560 unpredictable. The program might crash, or print wrong answers, or
6561 do anything else. It might even do exactly what you wanted it to do
6562 (and then it might start failing mysteriously next week or next
6563 year). The compiler will generate code based on the assumption that
6564 the condition being checked is true, which can result in erroneous
6565 execution if that assumption is wrong.
6567 The checks subject to suppression include all the checks defined by
6568 the Ada standard, the additional implementation defined checks
6569 @code{Alignment_Check},
6570 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, and
6571 @code{Validity_Check}, as well as any checks introduced using
6572 @code{pragma Check_Name}. Note that @code{Atomic_Synchronization}
6573 is not automatically suppressed by use of this option.
6575 If the code depends on certain checks being active, you can use
6576 pragma @code{Unsuppress} either as a configuration pragma or as
6577 a local pragma to make sure that a specified check is performed
6578 even if @option{gnatp} is specified.
6580 The @option{-gnatp} switch has no effect if a subsequent
6581 @option{-gnat-p} switch appears.
6583 @item -gnat-p
6584 @cindex @option{-gnat-p} (@command{gcc})
6585 @cindex Suppressing checks
6586 @cindex Checks, suppressing
6587 @findex Suppress
6588 This switch cancels the effect of a previous @option{gnatp} switch.
6590 @item -gnato??
6591 @cindex @option{-gnato??} (@command{gcc})
6592 @cindex Overflow checks
6593 @cindex Overflow mode
6594 @cindex Check, overflow
6595 This switch controls the mode used for computing intermediate
6596 arithmetic integer operations, and also enables overflow checking.
6597 For a full description of overflow mode and checking control, see
6598 the ``Overflow Check Handling in GNAT'' appendix in this
6599 User's Guide.
6601 Overflow checks are always enabled by this switch. The argument
6602 controls the mode, using the codes
6604 @itemize
6605 @item 1 = STRICT
6606 In STRICT mode, intermediate operations are always done using the
6607 base type, and overflow checking ensures that the result is within
6608 the base type range.
6610 @item 2 = MINIMIZED
6611 In MINIMIZED mode, overflows in intermediate operations are avoided
6612 where possible by using a larger integer type for the computation
6613 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6614 the result fits in this larger integer type.
6616 @item 3 = ELIMINATED
6617 In ELIMINATED mode, overflows in intermediate operations are avoided
6618 by using multi-precision arithmetic. In this case, overflow checking
6619 has no effect on intermediate operations (since overflow is impossible).
6620 @end itemize
6622 If two digits are present after @option{-gnato} then the first digit
6623 sets the mode for expressions outside assertions, and the second digit
6624 sets the mode for expressions within assertions. Here assertions is used
6625 in the technical sense (which includes for example precondition and
6626 postcondition expressions).
6628 If one digit is present, the corresponding mode is applicable to both
6629 expressions within and outside assertion expressions.
6631 If no digits are present, the default is to enable overflow checks
6632 and set STRICT mode for both kinds of expressions. This is compatible
6633 with the use of @option{-gnato} in previous versions of GNAT.
6635 @findex Machine_Overflows
6636 Note that the @option{-gnato??} switch does not affect the code generated
6637 for any floating-point operations; it applies only to integer semantics.
6638 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6639 attribute set to @code{False} and the normal mode of operation is to
6640 generate IEEE NaN and infinite values on overflow or invalid operations
6641 (such as dividing 0.0 by 0.0).
6643 The reason that we distinguish overflow checking from other kinds of
6644 range constraint checking is that a failure of an overflow check, unlike
6645 for example the failure of a range check, can result in an incorrect
6646 value, but cannot cause random memory destruction (like an out of range
6647 subscript), or a wild jump (from an out of range case value). Overflow
6648 checking is also quite expensive in time and space, since in general it
6649 requires the use of double length arithmetic.
6651 Note again that the default is @option{-gnato00},
6652 so overflow checking is not performed in default mode. This means that out of
6653 the box, with the default settings, @value{EDITION} does not do all the checks
6654 expected from the language description in the Ada Reference Manual.
6655 If you want all constraint checks to be performed, as described in this Manual,
6656 then you must explicitly use the @option{-gnato??}
6657 switch either on the @command{gnatmake} or @command{gcc} command.
6659 @item -gnatE
6660 @cindex @option{-gnatE} (@command{gcc})
6661 @cindex Elaboration checks
6662 @cindex Check, elaboration
6663 Enables dynamic checks for access-before-elaboration
6664 on subprogram calls and generic instantiations.
6665 Note that @option{-gnatE} is not necessary for safety, because in the
6666 default mode, GNAT ensures statically that the checks would not fail.
6667 For full details of the effect and use of this switch,
6668 @xref{Compiling with gcc}.
6670 @item -fstack-check
6671 @cindex @option{-fstack-check} (@command{gcc})
6672 @cindex Stack Overflow Checking
6673 @cindex Checks, stack overflow checking
6674 Activates stack overflow checking. For full details of the effect and use of
6675 this switch see @ref{Stack Overflow Checking}.
6676 @end table
6678 @findex Unsuppress
6679 @noindent
6680 The setting of these switches only controls the default setting of the
6681 checks. You may modify them using either @code{Suppress} (to remove
6682 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6683 the program source.
6685 @node Using gcc for Syntax Checking
6686 @subsection Using @command{gcc} for Syntax Checking
6687 @table @option
6688 @item -gnats
6689 @cindex @option{-gnats} (@command{gcc})
6691 @noindent
6692 The @code{s} stands for ``syntax''.
6694 Run GNAT in syntax checking only mode. For
6695 example, the command
6697 @smallexample
6698 $ gcc -c -gnats x.adb
6699 @end smallexample
6701 @noindent
6702 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6703 series of files in a single command
6704 , and can use wild cards to specify such a group of files.
6705 Note that you must specify the @option{-c} (compile
6706 only) flag in addition to the @option{-gnats} flag.
6708 You may use other switches in conjunction with @option{-gnats}. In
6709 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6710 format of any generated error messages.
6712 When the source file is empty or contains only empty lines and/or comments,
6713 the output is a warning:
6715 @smallexample
6716 $ gcc -c -gnats -x ada toto.txt
6717 toto.txt:1:01: warning: empty file, contains no compilation units
6719 @end smallexample
6721 Otherwise, the output is simply the error messages, if any. No object file or
6722 ALI file is generated by a syntax-only compilation. Also, no units other
6723 than the one specified are accessed. For example, if a unit @code{X}
6724 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6725 check only mode does not access the source file containing unit
6726 @code{Y}.
6728 @cindex Multiple units, syntax checking
6729 Normally, GNAT allows only a single unit in a source file. However, this
6730 restriction does not apply in syntax-check-only mode, and it is possible
6731 to check a file containing multiple compilation units concatenated
6732 together. This is primarily used by the @code{gnatchop} utility
6733 (@pxref{Renaming Files with gnatchop}).
6734 @end table
6736 @node Using gcc for Semantic Checking
6737 @subsection Using @command{gcc} for Semantic Checking
6738 @table @option
6739 @item -gnatc
6740 @cindex @option{-gnatc} (@command{gcc})
6742 @noindent
6743 The @code{c} stands for ``check''.
6744 Causes the compiler to operate in semantic check mode,
6745 with full checking for all illegalities specified in the
6746 Ada Reference Manual, but without generation of any object code
6747 (no object file is generated).
6749 Because dependent files must be accessed, you must follow the GNAT
6750 semantic restrictions on file structuring to operate in this mode:
6752 @itemize @bullet
6753 @item
6754 The needed source files must be accessible
6755 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6757 @item
6758 Each file must contain only one compilation unit.
6760 @item
6761 The file name and unit name must match (@pxref{File Naming Rules}).
6762 @end itemize
6764 The output consists of error messages as appropriate. No object file is
6765 generated. An @file{ALI} file is generated for use in the context of
6766 cross-reference tools, but this file is marked as not being suitable
6767 for binding (since no object file is generated).
6768 The checking corresponds exactly to the notion of
6769 legality in the Ada Reference Manual.
6771 Any unit can be compiled in semantics-checking-only mode, including
6772 units that would not normally be compiled (subunits,
6773 and specifications where a separate body is present).
6774 @end table
6776 @node Compiling Different Versions of Ada
6777 @subsection Compiling Different Versions of Ada
6779 @noindent
6780 The switches described in this section allow you to explicitly specify
6781 the version of the Ada language that your programs are written in.
6782 The default mode is Ada 2012,
6783 but you can also specify Ada 95, Ada 2005 mode, or
6784 indicate Ada 83 compatibility mode.
6786 @table @option
6787 @cindex Compatibility with Ada 83
6789 @item -gnat83 (Ada 83 Compatibility Mode)
6790 @cindex @option{-gnat83} (@command{gcc})
6791 @cindex ACVC, Ada 83 tests
6792 @cindex Ada 83 mode
6794 @noindent
6795 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6796 specifies that the program is to be compiled in Ada 83 mode. With
6797 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6798 semantics where this can be done easily.
6799 It is not possible to guarantee this switch does a perfect
6800 job; some subtle tests, such as are
6801 found in earlier ACVC tests (and that have been removed from the ACATS suite
6802 for Ada 95), might not compile correctly.
6803 Nevertheless, this switch may be useful in some circumstances, for example
6804 where, due to contractual reasons, existing code needs to be maintained
6805 using only Ada 83 features.
6807 With few exceptions (most notably the need to use @code{<>} on
6808 @cindex Generic formal parameters
6809 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6810 reserved words, and the use of packages
6811 with optional bodies), it is not necessary to specify the
6812 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6813 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6814 a correct Ada 83 program is usually also a correct program
6815 in these later versions of the language standard.
6816 For further information, please refer to @ref{Compatibility and Porting Guide}.
6818 @item -gnat95 (Ada 95 mode)
6819 @cindex @option{-gnat95} (@command{gcc})
6820 @cindex Ada 95 mode
6822 @noindent
6823 This switch directs the compiler to implement the Ada 95 version of the
6824 language.
6825 Since Ada 95 is almost completely upwards
6826 compatible with Ada 83, Ada 83 programs may generally be compiled using
6827 this switch (see the description of the @option{-gnat83} switch for further
6828 information about Ada 83 mode).
6829 If an Ada 2005 program is compiled in Ada 95 mode,
6830 uses of the new Ada 2005 features will cause error
6831 messages or warnings.
6833 This switch also can be used to cancel the effect of a previous
6834 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6835 switch earlier in the command line.
6837 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6838 @cindex @option{-gnat05} (@command{gcc})
6839 @cindex @option{-gnat2005} (@command{gcc})
6840 @cindex Ada 2005 mode
6842 @noindent
6843 This switch directs the compiler to implement the Ada 2005 version of the
6844 language, as documented in the official Ada standards document.
6845 Since Ada 2005 is almost completely upwards
6846 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6847 may generally be compiled using this switch (see the description of the
6848 @option{-gnat83} and @option{-gnat95} switches for further
6849 information).
6851 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6852 @cindex @option{-gnat12} (@command{gcc})
6853 @cindex @option{-gnat2012} (@command{gcc})
6854 @cindex Ada 2012 mode
6856 @noindent
6857 This switch directs the compiler to implement the Ada 2012 version of the
6858 language (also the default).
6859 Since Ada 2012 is almost completely upwards
6860 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6861 Ada 83 and Ada 95 programs
6862 may generally be compiled using this switch (see the description of the
6863 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6864 for further information).
6866 @item -gnatX (Enable GNAT Extensions)
6867 @cindex @option{-gnatX} (@command{gcc})
6868 @cindex Ada language extensions
6869 @cindex GNAT extensions
6871 @noindent
6872 This switch directs the compiler to implement the latest version of the
6873 language (currently Ada 2012) and also to enable certain GNAT implementation
6874 extensions that are not part of any Ada standard. For a full list of these
6875 extensions, see the GNAT reference manual.
6877 @end table
6879 @node Character Set Control
6880 @subsection Character Set Control
6881 @table @option
6882 @item -gnati@var{c}
6883 @cindex @option{-gnati} (@command{gcc})
6885 @noindent
6886 Normally GNAT recognizes the Latin-1 character set in source program
6887 identifiers, as described in the Ada Reference Manual.
6888 This switch causes
6889 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6890 single character  indicating the character set, as follows:
6892 @table @code
6893 @item 1
6894 ISO 8859-1 (Latin-1) identifiers
6896 @item 2
6897 ISO 8859-2 (Latin-2) letters allowed in identifiers
6899 @item 3
6900 ISO 8859-3 (Latin-3) letters allowed in identifiers
6902 @item 4
6903 ISO 8859-4 (Latin-4) letters allowed in identifiers
6905 @item 5
6906 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6908 @item 9
6909 ISO 8859-15 (Latin-9) letters allowed in identifiers
6911 @item p
6912 IBM PC letters (code page 437) allowed in identifiers
6914 @item 8
6915 IBM PC letters (code page 850) allowed in identifiers
6917 @item f
6918 Full upper-half codes allowed in identifiers
6920 @item n
6921 No upper-half codes allowed in identifiers
6923 @item w
6924 Wide-character codes (that is, codes greater than 255)
6925 allowed in identifiers
6926 @end table
6928 @xref{Foreign Language Representation}, for full details on the
6929 implementation of these character sets.
6931 @item -gnatW@var{e}
6932 @cindex @option{-gnatW} (@command{gcc})
6933 Specify the method of encoding for wide characters.
6934 @var{e} is one of the following:
6936 @table @code
6938 @item h
6939 Hex encoding (brackets coding also recognized)
6941 @item u
6942 Upper half encoding (brackets encoding also recognized)
6944 @item s
6945 Shift/JIS encoding (brackets encoding also recognized)
6947 @item e
6948 EUC encoding (brackets encoding also recognized)
6950 @item 8
6951 UTF-8 encoding (brackets encoding also recognized)
6953 @item b
6954 Brackets encoding only (default value)
6955 @end table
6956 For full details on these encoding
6957 methods see @ref{Wide_Character Encodings}.
6958 Note that brackets coding is always accepted, even if one of the other
6959 options is specified, so for example @option{-gnatW8} specifies that both
6960 brackets and UTF-8 encodings will be recognized. The units that are
6961 with'ed directly or indirectly will be scanned using the specified
6962 representation scheme, and so if one of the non-brackets scheme is
6963 used, it must be used consistently throughout the program. However,
6964 since brackets encoding is always recognized, it may be conveniently
6965 used in standard libraries, allowing these libraries to be used with
6966 any of the available coding schemes.
6968 Note that brackets encoding only applies to program text. Within comments,
6969 brackets are considered to be normal graphic characters, and bracket sequences
6970 are never recognized as wide characters.
6972 If no @option{-gnatW?} parameter is present, then the default
6973 representation is normally Brackets encoding only. However, if the
6974 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6975 byte order mark or BOM for UTF-8), then these three characters are
6976 skipped and the default representation for the file is set to UTF-8.
6978 Note that the wide character representation that is specified (explicitly
6979 or by default) for the main program also acts as the default encoding used
6980 for Wide_Text_IO files if not specifically overridden by a WCEM form
6981 parameter.
6983 @end table
6985 When no @option{-gnatW?} is specified, then characters (other than wide
6986 characters represented using brackets notation) are treated as 8-bit
6987 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
6988 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
6989 characters in the range 16#00#..16#1F# are not accepted in program text
6990 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
6991 in program text, but allowed and ignored in comments. Note in particular
6992 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
6993 as an end of line in this default mode. If your source program contains
6994 instances of the NEL character used as a line terminator,
6995 you must use UTF-8 encoding for the whole
6996 source program. In default mode, all lines must be ended by a standard
6997 end of line sequence (CR, CR/LF, or LF).
6999 Note that the convention of simply accepting all upper half characters in
7000 comments means that programs that use standard ASCII for program text, but
7001 UTF-8 encoding for comments are accepted in default mode, providing that the
7002 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7003 This is a common mode for many programs with foreign language comments.
7005 @node File Naming Control
7006 @subsection File Naming Control
7008 @table @option
7009 @item -gnatk@var{n}
7010 @cindex @option{-gnatk} (@command{gcc})
7011 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7012 1-999, indicates the maximum allowable length of a file name (not
7013 including the @file{.ads} or @file{.adb} extension). The default is not
7014 to enable file name krunching.
7016 For the source file naming rules, @xref{File Naming Rules}.
7017 @end table
7019 @node Subprogram Inlining Control
7020 @subsection Subprogram Inlining Control
7022 @table @option
7023 @c !sort!
7024 @item -gnatn[12]
7025 @cindex @option{-gnatn} (@command{gcc})
7026 The @code{n} here is intended to suggest the first syllable of the
7027 word ``inline''.
7028 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7029 inlining to actually occur, optimization must be enabled and, in order
7030 to enable inlining of subprograms specified by pragma @code{Inline},
7031 you must also specify this switch.
7032 In the absence of this switch, GNAT does not attempt
7033 inlining and does not need to access the bodies of
7034 subprograms for which @code{pragma Inline} is specified if they are not
7035 in the current unit.
7037 You can optionally specify the inlining level: 1 for moderate inlining across
7038 modules, which is a good compromise between compilation times and performances
7039 at run time, or 2 for full inlining across modules, which may bring about
7040 longer compilation times. If no inlining level is specified, the compiler will
7041 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7042 @option{-Os} and 2 for @option{-O3}.
7044 If you specify this switch the compiler will access these bodies,
7045 creating an extra source dependency for the resulting object file, and
7046 where possible, the call will be inlined.
7047 For further details on when inlining is possible
7048 see @ref{Inlining of Subprograms}.
7050 @item -gnatN
7051 @cindex @option{-gnatN} (@command{gcc})
7052 This switch activates front-end inlining which also
7053 generates additional dependencies.
7055 When using a gcc-based back end (in practice this means using any version
7056 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7057 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7058 Historically front end inlining was more extensive than the gcc back end
7059 inlining, but that is no longer the case.
7060 @end table
7062 @node Auxiliary Output Control
7063 @subsection Auxiliary Output Control
7065 @table @option
7066 @item -gnatt
7067 @cindex @option{-gnatt} (@command{gcc})
7068 @cindex Writing internal trees
7069 @cindex Internal trees, writing to file
7070 Causes GNAT to write the internal tree for a unit to a file (with the
7071 extension @file{.adt}.
7072 This not normally required, but is used by separate analysis tools.
7073 Typically
7074 these tools do the necessary compilations automatically, so you should
7075 not have to specify this switch in normal operation.
7076 Note that the combination of switches @option{-gnatct}
7077 generates a tree in the form required by ASIS applications.
7079 @item -gnatu
7080 @cindex @option{-gnatu} (@command{gcc})
7081 Print a list of units required by this compilation on @file{stdout}.
7082 The listing includes all units on which the unit being compiled depends
7083 either directly or indirectly.
7085 @item -pass-exit-codes
7086 @cindex @option{-pass-exit-codes} (@command{gcc})
7087 If this switch is not used, the exit code returned by @command{gcc} when
7088 compiling multiple files indicates whether all source files have
7089 been successfully used to generate object files or not.
7091 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7092 exit status and allows an integrated development environment to better
7093 react to a compilation failure. Those exit status are:
7095 @table @asis
7096 @item 5
7097 There was an error in at least one source file.
7098 @item 3
7099 At least one source file did not generate an object file.
7100 @item 2
7101 The compiler died unexpectedly (internal error for example).
7102 @item 0
7103 An object file has been generated for every source file.
7104 @end table
7105 @end table
7107 @node Debugging Control
7108 @subsection Debugging Control
7110 @table @option
7111 @c !sort!
7112 @cindex Debugging options
7113 @item -gnatd@var{x}
7114 @cindex @option{-gnatd} (@command{gcc})
7115 Activate internal debugging switches. @var{x} is a letter or digit, or
7116 string of letters or digits, which specifies the type of debugging
7117 outputs desired. Normally these are used only for internal development
7118 or system debugging purposes. You can find full documentation for these
7119 switches in the body of the @code{Debug} unit in the compiler source
7120 file @file{debug.adb}.
7122 @item -gnatG[=nn]
7123 @cindex @option{-gnatG} (@command{gcc})
7124 This switch causes the compiler to generate auxiliary output containing
7125 a pseudo-source listing of the generated expanded code. Like most Ada
7126 compilers, GNAT works by first transforming the high level Ada code into
7127 lower level constructs. For example, tasking operations are transformed
7128 into calls to the tasking run-time routines. A unique capability of GNAT
7129 is to list this expanded code in a form very close to normal Ada source.
7130 This is very useful in understanding the implications of various Ada
7131 usage on the efficiency of the generated code. There are many cases in
7132 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7133 generate a lot of run-time code. By using @option{-gnatG} you can identify
7134 these cases, and consider whether it may be desirable to modify the coding
7135 approach to improve efficiency.
7137 The optional parameter @code{nn} if present after -gnatG specifies an
7138 alternative maximum line length that overrides the normal default of 72.
7139 This value is in the range 40-999999, values less than 40 being silently
7140 reset to 40. The equal sign is optional.
7142 The format of the output is very similar to standard Ada source, and is
7143 easily understood by an Ada programmer. The following special syntactic
7144 additions correspond to low level features used in the generated code that
7145 do not have any exact analogies in pure Ada source form. The following
7146 is a partial list of these special constructions. See the spec
7147 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7149 If the switch @option{-gnatL} is used in conjunction with
7150 @cindex @option{-gnatL} (@command{gcc})
7151 @option{-gnatG}, then the original source lines are interspersed
7152 in the expanded source (as comment lines with the original line number).
7154 @table @code
7155 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7156 Shows the storage pool being used for an allocator.
7158 @item at end @var{procedure-name};
7159 Shows the finalization (cleanup) procedure for a scope.
7161 @item (if @var{expr} then @var{expr} else @var{expr})
7162 Conditional expression equivalent to the @code{x?y:z} construction in C.
7164 @item @var{target}^(@var{source})
7165 A conversion with floating-point truncation instead of rounding.
7167 @item @var{target}?(@var{source})
7168 A conversion that bypasses normal Ada semantic checking. In particular
7169 enumeration types and fixed-point types are treated simply as integers.
7171 @item @var{target}?^(@var{source})
7172 Combines the above two cases.
7174 @item @var{x} #/ @var{y}
7175 @itemx @var{x} #mod @var{y}
7176 @itemx @var{x} #* @var{y}
7177 @itemx @var{x} #rem @var{y}
7178 A division or multiplication of fixed-point values which are treated as
7179 integers without any kind of scaling.
7181 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7182 Shows the storage pool associated with a @code{free} statement.
7184 @item [subtype or type declaration]
7185 Used to list an equivalent declaration for an internally generated
7186 type that is referenced elsewhere in the listing.
7188 @c @item freeze @var{type-name} @ovar{actions}
7189 @c Expanding @ovar macro inline (explanation in macro def comments)
7190 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7191 Shows the point at which @var{type-name} is frozen, with possible
7192 associated actions to be performed at the freeze point.
7194 @item reference @var{itype}
7195 Reference (and hence definition) to internal type @var{itype}.
7197 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7198 Intrinsic function call.
7200 @item @var{label-name} : label
7201 Declaration of label @var{labelname}.
7203 @item #$ @var{subprogram-name}
7204 An implicit call to a run-time support routine
7205 (to meet the requirement of H.3.1(9) in a
7206 convenient manner).
7208 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7209 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7210 @var{expr}, but handled more efficiently).
7212 @item [constraint_error]
7213 Raise the @code{Constraint_Error} exception.
7215 @item @var{expression}'reference
7216 A pointer to the result of evaluating @var{expression}.
7218 @item @var{target-type}!(@var{source-expression})
7219 An unchecked conversion of @var{source-expression} to @var{target-type}.
7221 @item [@var{numerator}/@var{denominator}]
7222 Used to represent internal real literals (that) have no exact
7223 representation in base 2-16 (for example, the result of compile time
7224 evaluation of the expression 1.0/27.0).
7225 @end table
7227 @item -gnatD[=nn]
7228 @cindex @option{-gnatD} (@command{gcc})
7229 When used in conjunction with @option{-gnatG}, this switch causes
7230 the expanded source, as described above for
7231 @option{-gnatG} to be written to files with names
7232 @file{xxx.dg}, where @file{xxx} is the normal file name,
7233 instead of to the standard output file. For
7234 example, if the source file name is @file{hello.adb}, then a file
7235 @file{hello.adb.dg} will be written.  The debugging
7236 information generated by the @command{gcc} @option{-g} switch
7237 will refer to the generated @file{xxx.dg} file. This allows
7238 you to do source level debugging using the generated code which is
7239 sometimes useful for complex code, for example to find out exactly
7240 which part of a complex construction raised an exception. This switch
7241 also suppress generation of cross-reference information (see
7242 @option{-gnatx}) since otherwise the cross-reference information
7243 would refer to the @file{.dg} file, which would cause
7244 confusion since this is not the original source file.
7246 Note that @option{-gnatD} actually implies @option{-gnatG}
7247 automatically, so it is not necessary to give both options.
7248 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7250 If the switch @option{-gnatL} is used in conjunction with
7251 @cindex @option{-gnatL} (@command{gcc})
7252 @option{-gnatDG}, then the original source lines are interspersed
7253 in the expanded source (as comment lines with the original line number).
7255 The optional parameter @code{nn} if present after -gnatD specifies an
7256 alternative maximum line length that overrides the normal default of 72.
7257 This value is in the range 40-999999, values less than 40 being silently
7258 reset to 40. The equal sign is optional.
7260 @item -gnatr
7261 @cindex @option{-gnatr} (@command{gcc})
7262 @cindex pragma Restrictions
7263 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7264 so that violation of restrictions causes warnings rather than illegalities.
7265 This is useful during the development process when new restrictions are added
7266 or investigated. The switch also causes pragma Profile to be treated as
7267 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7268 restriction warnings rather than restrictions.
7270 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7271 @cindex @option{-gnatR} (@command{gcc})
7272 This switch controls output from the compiler of a listing showing
7273 representation information for declared types and objects. For
7274 @option{-gnatR0}, no information is output (equivalent to omitting
7275 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7276 so @option{-gnatR} with no parameter has the same effect), size and alignment
7277 information is listed for declared array and record types. For
7278 @option{-gnatR2}, size and alignment information is listed for all
7279 declared types and objects. The @code{Linker_Section} is also listed for any
7280 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7281 latter case occurs for objects of a type for which a @code{Linker_Section}
7282 is set).
7284 Finally @option{-gnatR3} includes symbolic
7285 expressions for values that are computed at run time for
7286 variant records. These symbolic expressions have a mostly obvious
7287 format with #n being used to represent the value of the n'th
7288 discriminant. See source files @file{repinfo.ads/adb} in the
7289 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7290 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7291 the output is to a file with the name @file{file.rep} where
7292 file is the name of the corresponding source file.
7294 @item -gnatRm[s]
7295 This form of the switch controls output of subprogram conventions
7296 and parameter passing mechanisms for all subprograms. A following
7297 @code{s} means output to a file as described above.
7299 Note that it is possible for record components to have zero size. In
7300 this case, the component clause uses an obvious extension of permitted
7301 Ada syntax, for example @code{at 0 range 0 .. -1}.
7303 Representation information requires that code be generated (since it is the
7304 code generator that lays out complex data structures). If an attempt is made
7305 to output representation information when no code is generated, for example
7306 when a subunit is compiled on its own, then no information can be generated
7307 and the compiler outputs a message to this effect.
7309 @item -gnatS
7310 @cindex @option{-gnatS} (@command{gcc})
7311 The use of the switch @option{-gnatS} for an
7312 Ada compilation will cause the compiler to output a
7313 representation of package Standard in a form very
7314 close to standard Ada. It is not quite possible to
7315 do this entirely in standard Ada (since new
7316 numeric base types cannot be created in standard
7317 Ada), but the output is easily
7318 readable to any Ada programmer, and is useful to
7319 determine the characteristics of target dependent
7320 types in package Standard.
7322 @item -gnatx
7323 @cindex @option{-gnatx} (@command{gcc})
7324 Normally the compiler generates full cross-referencing information in
7325 the @file{ALI} file. This information is used by a number of tools,
7326 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7327 suppresses this information. This saves some space and may slightly
7328 speed up compilation, but means that these tools cannot be used.
7329 @end table
7331 @node Exception Handling Control
7332 @subsection Exception Handling Control
7334 @noindent
7335 GNAT uses two methods for handling exceptions at run-time. The
7336 @code{setjmp/longjmp} method saves the context when entering
7337 a frame with an exception handler. Then when an exception is
7338 raised, the context can be restored immediately, without the
7339 need for tracing stack frames. This method provides very fast
7340 exception propagation, but introduces significant overhead for
7341 the use of exception handlers, even if no exception is raised.
7343 The other approach is called ``zero cost'' exception handling.
7344 With this method, the compiler builds static tables to describe
7345 the exception ranges. No dynamic code is required when entering
7346 a frame containing an exception handler. When an exception is
7347 raised, the tables are used to control a back trace of the
7348 subprogram invocation stack to locate the required exception
7349 handler. This method has considerably poorer performance for
7350 the propagation of exceptions, but there is no overhead for
7351 exception handlers if no exception is raised. Note that in this
7352 mode and in the context of mixed Ada and C/C++ programming,
7353 to propagate an exception through a C/C++ code, the C/C++ code
7354 must be compiled with the @option{-funwind-tables} GCC's
7355 option.
7357 The following switches may be used to control which of the
7358 two exception handling methods is used.
7360 @table @option
7361 @c !sort!
7363 @item --RTS=sjlj
7364 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7365 This switch causes the setjmp/longjmp run-time (when available) to be used
7366 for exception handling. If the default
7367 mechanism for the target is zero cost exceptions, then
7368 this switch can be used to modify this default, and must be
7369 used for all units in the partition.
7370 This option is rarely used. One case in which it may be
7371 advantageous is if you have an application where exception
7372 raising is common and the overall performance of the
7373 application is improved by favoring exception propagation.
7375 @item --RTS=zcx
7376 @cindex @option{--RTS=zcx} (@command{gnatmake})
7377 @cindex Zero Cost Exceptions
7378 This switch causes the zero cost approach to be used
7379 for exception handling. If this is the default mechanism for the
7380 target (see below), then this switch is unneeded. If the default
7381 mechanism for the target is setjmp/longjmp exceptions, then
7382 this switch can be used to modify this default, and must be
7383 used for all units in the partition.
7384 This option can only be used if the zero cost approach
7385 is available for the target in use, otherwise it will generate an error.
7386 @end table
7388 @noindent
7389 The same option @option{--RTS} must be used both for @command{gcc}
7390 and @command{gnatbind}. Passing this option to @command{gnatmake}
7391 (@pxref{Switches for gnatmake}) will ensure the required consistency
7392 through the compilation and binding steps.
7394 @node Units to Sources Mapping Files
7395 @subsection Units to Sources Mapping Files
7397 @table @option
7399 @item -gnatem=@var{path}
7400 @cindex @option{-gnatem} (@command{gcc})
7401 A mapping file is a way to communicate to the compiler two mappings:
7402 from unit names to file names (without any directory information) and from
7403 file names to path names (with full directory information). These mappings
7404 are used by the compiler to short-circuit the path search.
7406 The use of mapping files is not required for correct operation of the
7407 compiler, but mapping files can improve efficiency, particularly when
7408 sources are read over a slow network connection. In normal operation,
7409 you need not be concerned with the format or use of mapping files,
7410 and the @option{-gnatem} switch is not a switch that you would use
7411 explicitly. It is intended primarily for use by automatic tools such as
7412 @command{gnatmake} running under the project file facility. The
7413 description here of the format of mapping files is provided
7414 for completeness and for possible use by other tools.
7416 A mapping file is a sequence of sets of three lines. In each set, the
7417 first line is the unit name, in lower case, with @code{%s} appended
7418 for specs and @code{%b} appended for bodies; the second line is the
7419 file name; and the third line is the path name.
7421 Example:
7422 @smallexample
7423    main%b
7424    main.2.ada
7425    /gnat/project1/sources/main.2.ada
7426 @end smallexample
7428 When the switch @option{-gnatem} is specified, the compiler will
7429 create in memory the two mappings from the specified file. If there is
7430 any problem (nonexistent file, truncated file or duplicate entries),
7431 no mapping will be created.
7433 Several @option{-gnatem} switches may be specified; however, only the
7434 last one on the command line will be taken into account.
7436 When using a project file, @command{gnatmake} creates a temporary
7437 mapping file and communicates it to the compiler using this switch.
7439 @end table
7441 @node Integrated Preprocessing
7442 @subsection Integrated Preprocessing
7444 @noindent
7445 GNAT sources may be preprocessed immediately before compilation.
7446 In this case, the actual
7447 text of the source is not the text of the source file, but is derived from it
7448 through a process called preprocessing. Integrated preprocessing is specified
7449 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7450 indicates, through a text file, the preprocessing data to be used.
7451 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7452 Note that integrated preprocessing applies only to Ada source files, it is
7453 not available for configuration pragma files.
7455 @noindent
7456 Note that when integrated preprocessing is used, the output from the
7457 preprocessor is not written to any external file. Instead it is passed
7458 internally to the compiler. If you need to preserve the result of
7459 preprocessing in a file, then you should use @command{gnatprep}
7460 to perform the desired preprocessing in stand-alone mode.
7462 @noindent
7463 It is recommended that @command{gnatmake} switch -s should be
7464 used when Integrated Preprocessing is used. The reason is that preprocessing
7465 with another Preprocessing Data file without changing the sources will
7466 not trigger recompilation without this switch.
7468 @noindent
7469 Note that @command{gnatmake} switch -m will almost
7470 always trigger recompilation for sources that are preprocessed,
7471 because @command{gnatmake} cannot compute the checksum of the source after
7472 preprocessing.
7474 @noindent
7475 The actual preprocessing function is described in details in section
7476 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7477 preprocessing is triggered and parameterized.
7479 @table @code
7481 @item -gnatep=@var{file}
7482 @cindex @option{-gnatep} (@command{gcc})
7483 This switch indicates to the compiler the file name (without directory
7484 information) of the preprocessor data file to use. The preprocessor data file
7485 should be found in the source directories. Note that when the compiler is
7486 called by a builder such as (@command{gnatmake} with a project
7487 file, if the object directory is not also a source directory, the builder needs
7488 to be called with @option{-x}.
7490 @noindent
7491 A preprocessing data file is a text file with significant lines indicating
7492 how should be preprocessed either a specific source or all sources not
7493 mentioned in other lines. A significant line is a nonempty, non-comment line.
7494 Comments are similar to Ada comments.
7496 @noindent
7497 Each significant line starts with either a literal string or the character '*'.
7498 A literal string is the file name (without directory information) of the source
7499 to preprocess. A character '*' indicates the preprocessing for all the sources
7500 that are not specified explicitly on other lines (order of the lines is not
7501 significant). It is an error to have two lines with the same file name or two
7502 lines starting with the character '*'.
7504 @noindent
7505 After the file name or the character '*', another optional literal string
7506 indicating the file name of the definition file to be used for preprocessing
7507 (@pxref{Form of Definitions File}). The definition files are found by the
7508 compiler in one of the source directories. In some cases, when compiling
7509 a source in a directory other than the current directory, if the definition
7510 file is in the current directory, it may be necessary to add the current
7511 directory as a source directory through switch -I., otherwise
7512 the compiler would not find the definition file.
7514 @noindent
7515 Then, optionally, switches similar to those of @code{gnatprep} may
7516 be found. Those switches are:
7518 @table @code
7520 @item -b
7521 Causes both preprocessor lines and the lines deleted by
7522 preprocessing to be replaced by blank lines, preserving the line number.
7523 This switch is always implied; however, if specified after @option{-c}
7524 it cancels the effect of @option{-c}.
7526 @item -c
7527 Causes both preprocessor lines and the lines deleted
7528 by preprocessing to be retained as comments marked
7529 with the special string ``@code{--! }''.
7531 @item -Dsymbol=value
7532 Define or redefine a symbol, associated with value. A symbol is an Ada
7533 identifier, or an Ada reserved word, with the exception of @code{if},
7534 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7535 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7536 word. A symbol declared with this switch replaces a symbol with the
7537 same name defined in a definition file.
7539 @item -s
7540 Causes a sorted list of symbol names and values to be
7541 listed on the standard output file.
7543 @item -u
7544 Causes undefined symbols to be treated as having the value @code{FALSE}
7545 in the context
7546 of a preprocessor test. In the absence of this option, an undefined symbol in
7547 a @code{#if} or @code{#elsif} test will be treated as an error.
7549 @end table
7551 @noindent
7552 Examples of valid lines in a preprocessor data file:
7554 @smallexample
7555   "toto.adb"  "prep.def" -u
7556   --  preprocess "toto.adb", using definition file "prep.def",
7557   --  undefined symbol are False.
7559   * -c -DVERSION=V101
7560   --  preprocess all other sources without a definition file;
7561   --  suppressed lined are commented; symbol VERSION has the value V101.
7563   "titi.adb" "prep2.def" -s
7564   --  preprocess "titi.adb", using definition file "prep2.def";
7565   --  list all symbols with their values.
7566 @end smallexample
7568 @item -gnateDsymbol@r{[}=value@r{]}
7569 @cindex @option{-gnateD} (@command{gcc})
7570 Define or redefine a preprocessing symbol, associated with value. If no value
7571 is given on the command line, then the value of the symbol is @code{True}.
7572 A symbol is an identifier, following normal Ada (case-insensitive)
7573 rules for its syntax, and value is either an arbitrary string between double
7574 quotes or any sequence (including an empty sequence) of characters from the
7575 set (letters, digits, period, underline).
7576 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7577 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7579 @noindent
7580 Examples:
7582 @smallexample
7583    -gnateDToto=Titi
7584    -gnateDFoo
7585    -gnateDFoo=\"Foo-Bar\"
7586 @end smallexample
7588 @noindent
7589 A symbol declared with this switch on the command line replaces a
7590 symbol with the same name either in a definition file or specified with a
7591 switch -D in the preprocessor data file.
7593 @noindent
7594 This switch is similar to switch @option{-D} of @code{gnatprep}.
7596 @item -gnateG
7597 When integrated preprocessing is performed and the preprocessor modifies
7598 the source text, write the result of this preprocessing into a file
7599 <source>.prep.
7601 @end table
7603 @node Code Generation Control
7604 @subsection Code Generation Control
7606 @noindent
7608 The GCC technology provides a wide range of target dependent
7609 @option{-m} switches for controlling
7610 details of code generation with respect to different versions of
7611 architectures. This includes variations in instruction sets (e.g.@:
7612 different members of the power pc family), and different requirements
7613 for optimal arrangement of instructions (e.g.@: different members of
7614 the x86 family). The list of available @option{-m} switches may be
7615 found in the GCC documentation.
7617 Use of these @option{-m} switches may in some cases result in improved
7618 code performance.
7620 The @value{EDITION} technology is tested and qualified without any
7621 @option{-m} switches,
7622 so generally the most reliable approach is to avoid the use of these
7623 switches. However, we generally expect most of these switches to work
7624 successfully with @value{EDITION}, and many customers have reported successful
7625 use of these options.
7627 Our general advice is to avoid the use of @option{-m} switches unless
7628 special needs lead to requirements in this area. In particular,
7629 there is no point in using @option{-m} switches to improve performance
7630 unless you actually see a performance improvement.
7633 @node Search Paths and the Run-Time Library (RTL)
7634 @section Search Paths and the Run-Time Library (RTL)
7636 @noindent
7637 With the GNAT source-based library system, the compiler must be able to
7638 find source files for units that are needed by the unit being compiled.
7639 Search paths are used to guide this process.
7641 The compiler compiles one source file whose name must be given
7642 explicitly on the command line. In other words, no searching is done
7643 for this file. To find all other source files that are needed (the most
7644 common being the specs of units), the compiler examines the following
7645 directories, in the following order:
7647 @enumerate
7648 @item
7649 The directory containing the source file of the main unit being compiled
7650 (the file name on the command line).
7652 @item
7653 Each directory named by an @option{-I} switch given on the
7654 @command{gcc} command line, in the order given.
7656 @item
7657 @findex ADA_PRJ_INCLUDE_FILE
7658 Each of the directories listed in the text file whose name is given
7659 by the @env{ADA_PRJ_INCLUDE_FILE} environment variable.
7661 @noindent
7662 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
7663 driver when project files are used. It should not normally be set
7664 by other means.
7666 @item
7667 @findex ADA_INCLUDE_PATH
7668 Each of the directories listed in the value of the
7669 @env{ADA_INCLUDE_PATH} environment variable.
7670 Construct this value
7671 exactly as the @env{PATH} environment variable: a list of directory
7672 names separated by colons (semicolons when working with the NT version).
7674 @item
7675 The content of the @file{ada_source_path} file which is part of the GNAT
7676 installation tree and is used to store standard libraries such as the
7677 GNAT Run Time Library (RTL) source files.
7678 @ref{Installing a library}
7679 @end enumerate
7681 @noindent
7682 Specifying the switch @option{-I-}
7683 inhibits the use of the directory
7684 containing the source file named in the command line. You can still
7685 have this directory on your search path, but in this case it must be
7686 explicitly requested with a @option{-I} switch.
7688 Specifying the switch @option{-nostdinc}
7689 inhibits the search of the default location for the GNAT Run Time
7690 Library (RTL) source files.
7692 The compiler outputs its object files and ALI files in the current
7693 working directory.
7694 Caution: The object file can be redirected with the @option{-o} switch;
7695 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7696 so the @file{ALI} file will not go to the right place. Therefore, you should
7697 avoid using the @option{-o} switch.
7699 @findex System.IO
7700 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7701 children make up the GNAT RTL, together with the simple @code{System.IO}
7702 package used in the @code{"Hello World"} example. The sources for these units
7703 are needed by the compiler and are kept together in one directory. Not
7704 all of the bodies are needed, but all of the sources are kept together
7705 anyway. In a normal installation, you need not specify these directory
7706 names when compiling or binding. Either the environment variables or
7707 the built-in defaults cause these files to be found.
7709 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7710 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7711 consisting of child units of @code{GNAT}. This is a collection of generally
7712 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7713 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7715 Besides simplifying access to the RTL, a major use of search paths is
7716 in compiling sources from multiple directories. This can make
7717 development environments much more flexible.
7719 @node Order of Compilation Issues
7720 @section Order of Compilation Issues
7722 @noindent
7723 If, in our earlier example, there was a spec for the @code{hello}
7724 procedure, it would be contained in the file @file{hello.ads}; yet this
7725 file would not have to be explicitly compiled. This is the result of the
7726 model we chose to implement library management. Some of the consequences
7727 of this model are as follows:
7729 @itemize @bullet
7730 @item
7731 There is no point in compiling specs (except for package
7732 specs with no bodies) because these are compiled as needed by clients. If
7733 you attempt a useless compilation, you will receive an error message.
7734 It is also useless to compile subunits because they are compiled as needed
7735 by the parent.
7737 @item
7738 There are no order of compilation requirements: performing a
7739 compilation never obsoletes anything. The only way you can obsolete
7740 something and require recompilations is to modify one of the
7741 source files on which it depends.
7743 @item
7744 There is no library as such, apart from the ALI files
7745 (@pxref{The Ada Library Information Files}, for information on the format
7746 of these files). For now we find it convenient to create separate ALI files,
7747 but eventually the information therein may be incorporated into the object
7748 file directly.
7750 @item
7751 When you compile a unit, the source files for the specs of all units
7752 that it @code{with}'s, all its subunits, and the bodies of any generics it
7753 instantiates must be available (reachable by the search-paths mechanism
7754 described above), or you will receive a fatal error message.
7755 @end itemize
7757 @node Examples
7758 @section Examples
7760 @noindent
7761 The following are some typical Ada compilation command line examples:
7763 @table @code
7764 @item $ gcc -c xyz.adb
7765 Compile body in file @file{xyz.adb} with all default options.
7767 @item $ gcc -c -O2 -gnata xyz-def.adb
7769 Compile the child unit package in file @file{xyz-def.adb} with extensive
7770 optimizations, and pragma @code{Assert}/@code{Debug} statements
7771 enabled.
7773 @item $ gcc -c -gnatc abc-def.adb
7774 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7775 mode.
7776 @end table
7778 @node Binding with gnatbind
7779 @chapter Binding with @code{gnatbind}
7780 @findex gnatbind
7782 @menu
7783 * Running gnatbind::
7784 * Switches for gnatbind::
7785 * Command-Line Access::
7786 * Search Paths for gnatbind::
7787 * Examples of gnatbind Usage::
7788 @end menu
7790 @noindent
7791 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7792 to bind compiled GNAT objects.
7794 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7795 driver (see @ref{The GNAT Driver and Project Files}).
7797 The @code{gnatbind} program performs four separate functions:
7799 @enumerate
7800 @item
7801 Checks that a program is consistent, in accordance with the rules in
7802 Chapter 10 of the Ada Reference Manual. In particular, error
7803 messages are generated if a program uses inconsistent versions of a
7804 given unit.
7806 @item
7807 Checks that an acceptable order of elaboration exists for the program
7808 and issues an error message if it cannot find an order of elaboration
7809 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7811 @item
7812 Generates a main program incorporating the given elaboration order.
7813 This program is a small Ada package (body and spec) that
7814 must be subsequently compiled
7815 using the GNAT compiler. The necessary compilation step is usually
7816 performed automatically by @command{gnatlink}. The two most important
7817 functions of this program
7818 are to call the elaboration routines of units in an appropriate order
7819 and to call the main program.
7821 @item
7822 Determines the set of object files required by the given main program.
7823 This information is output in the forms of comments in the generated program,
7824 to be read by the @command{gnatlink} utility used to link the Ada application.
7825 @end enumerate
7827 @node Running gnatbind
7828 @section Running @code{gnatbind}
7830 @noindent
7831 The form of the @code{gnatbind} command is
7833 @smallexample
7834 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7835 @c Expanding @ovar macro inline (explanation in macro def comments)
7836 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7837 @end smallexample
7839 @noindent
7840 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7841 unit body. @code{gnatbind} constructs an Ada
7842 package in two files whose names are
7843 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7844 For example, if given the
7845 parameter @file{hello.ali}, for a main program contained in file
7846 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7847 and @file{b~hello.adb}.
7849 When doing consistency checking, the binder takes into consideration
7850 any source files it can locate. For example, if the binder determines
7851 that the given main program requires the package @code{Pack}, whose
7852 @file{.ALI}
7853 file is @file{pack.ali} and whose corresponding source spec file is
7854 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7855 (using the same search path conventions as previously described for the
7856 @command{gcc} command). If it can locate this source file, it checks that
7857 the time stamps
7858 or source checksums of the source and its references to in @file{ALI} files
7859 match. In other words, any @file{ALI} files that mentions this spec must have
7860 resulted from compiling this version of the source file (or in the case
7861 where the source checksums match, a version close enough that the
7862 difference does not matter).
7864 @cindex Source files, use by binder
7865 The effect of this consistency checking, which includes source files, is
7866 that the binder ensures that the program is consistent with the latest
7867 version of the source files that can be located at bind time. Editing a
7868 source file without compiling files that depend on the source file cause
7869 error messages to be generated by the binder.
7871 For example, suppose you have a main program @file{hello.adb} and a
7872 package @code{P}, from file @file{p.ads} and you perform the following
7873 steps:
7875 @enumerate
7876 @item
7877 Enter @code{gcc -c hello.adb} to compile the main program.
7879 @item
7880 Enter @code{gcc -c p.ads} to compile package @code{P}.
7882 @item
7883 Edit file @file{p.ads}.
7885 @item
7886 Enter @code{gnatbind hello}.
7887 @end enumerate
7889 @noindent
7890 At this point, the file @file{p.ali} contains an out-of-date time stamp
7891 because the file @file{p.ads} has been edited. The attempt at binding
7892 fails, and the binder generates the following error messages:
7894 @smallexample
7895 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7896 error: "p.ads" has been modified and must be recompiled
7897 @end smallexample
7899 @noindent
7900 Now both files must be recompiled as indicated, and then the bind can
7901 succeed, generating a main program. You need not normally be concerned
7902 with the contents of this file, but for reference purposes a sample
7903 binder output file is given in @ref{Example of Binder Output File}.
7905 In most normal usage, the default mode of @command{gnatbind} which is to
7906 generate the main package in Ada, as described in the previous section.
7907 In particular, this means that any Ada programmer can read and understand
7908 the generated main program. It can also be debugged just like any other
7909 Ada code provided the @option{-g} switch is used for
7910 @command{gnatbind} and @command{gnatlink}.
7912 @node Switches for gnatbind
7913 @section Switches for @command{gnatbind}
7915 @noindent
7916 The following switches are available with @code{gnatbind}; details will
7917 be presented in subsequent sections.
7919 @menu
7920 * Consistency-Checking Modes::
7921 * Binder Error Message Control::
7922 * Elaboration Control::
7923 * Output Control::
7924 * Dynamic Allocation Control::
7925 * Binding with Non-Ada Main Programs::
7926 * Binding Programs with No Main Subprogram::
7927 @end menu
7929 @table @option
7930 @c !sort!
7932 @item --version
7933 @cindex @option{--version} @command{gnatbind}
7934 Display Copyright and version, then exit disregarding all other options.
7936 @item --help
7937 @cindex @option{--help} @command{gnatbind}
7938 If @option{--version} was not used, display usage, then exit disregarding
7939 all other options.
7941 @item -a
7942 @cindex @option{-a} @command{gnatbind}
7943 Indicates that, if supported by the platform, the adainit procedure should
7944 be treated as an initialisation routine by the linker (a constructor). This
7945 is intended to be used by the Project Manager to automatically initialize
7946 shared Stand-Alone Libraries.
7948 @item -aO
7949 @cindex @option{-aO} (@command{gnatbind})
7950 Specify directory to be searched for ALI files.
7952 @item -aI
7953 @cindex @option{-aI} (@command{gnatbind})
7954 Specify directory to be searched for source file.
7956 @item -A@r{[=}@var{filename}@r{]}
7957 @cindex @option{-A} (@command{gnatbind})
7958 Output ALI list (to standard output or to the named file).
7960 @item -b
7961 @cindex @option{-b} (@command{gnatbind})
7962 Generate brief messages to @file{stderr} even if verbose mode set.
7964 @item -c
7965 @cindex @option{-c} (@command{gnatbind})
7966 Check only, no generation of binder output file.
7968 @item -d@var{nn}@r{[}k@r{|}m@r{]}
7969 @cindex @option{-d@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7970 This switch can be used to change the default task stack size value
7971 to a specified size @var{nn}, which is expressed in bytes by default, or
7972 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7973 with @var{m}.
7974 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7975 in effect, to completing all task specs with
7976 @smallexample @c ada
7977    @b{pragma} Storage_Size (nn);
7978 @end smallexample
7979 When they do not already have such a pragma.
7981 @item -D@var{nn}@r{[}k@r{|}m@r{]}
7982 @cindex @option{-D} (@command{gnatbind})
7983 This switch can be used to change the default secondary stack size value
7984 to a specified size @var{nn}, which is expressed in bytes by default, or
7985 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7986 with @var{m}.
7988 The secondary stack is used to deal with functions that return a variable
7989 sized result, for example a function returning an unconstrained
7990 String. There are two ways in which this secondary stack is allocated.
7992 For most targets, the secondary stack is growing on demand and is allocated
7993 as a chain of blocks in the heap. The -D option is not very
7994 relevant. It only give some control over the size of the allocated
7995 blocks (whose size is the minimum of the default secondary stack size value,
7996 and the actual size needed for the current allocation request).
7998 For certain targets, notably VxWorks 653,
7999 the secondary stack is allocated by carving off a fixed ratio chunk of the
8000 primary task stack. The -D option is used to define the
8001 size of the environment task's secondary stack.
8003 @item -e
8004 @cindex @option{-e} (@command{gnatbind})
8005 Output complete list of elaboration-order dependencies.
8007 @item -E
8008 @cindex @option{-E} (@command{gnatbind})
8009 Store tracebacks in exception occurrences when the target supports it.
8010 @ignore
8011 @c The following may get moved to an appendix
8012 This option is currently supported on the following targets:
8013 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8014 @end ignore
8015 See also the packages @code{GNAT.Traceback} and
8016 @code{GNAT.Traceback.Symbolic} for more information.
8017 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8018 @command{gcc} option.
8020 @item -F
8021 @cindex @option{-F} (@command{gnatbind})
8022 Force the checks of elaboration flags. @command{gnatbind} does not normally
8023 generate checks of elaboration flags for the main executable, except when
8024 a Stand-Alone Library is used. However, there are cases when this cannot be
8025 detected by gnatbind. An example is importing an interface of a Stand-Alone
8026 Library through a pragma Import and only specifying through a linker switch
8027 this Stand-Alone Library. This switch is used to guarantee that elaboration
8028 flag checks are generated.
8030 @item -h
8031 @cindex @option{-h} (@command{gnatbind})
8032 Output usage (help) information
8034 @item -H32
8035 @cindex @option{-H32} (@command{gnatbind})
8036 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8037 For further details see @ref{Dynamic Allocation Control}.
8039 @item -H64
8040 @cindex @option{-H64} (@command{gnatbind})
8041 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8042 @cindex @code{__gnat_malloc}
8043 For further details see @ref{Dynamic Allocation Control}.
8045 @item -I
8046 @cindex @option{-I} (@command{gnatbind})
8047 Specify directory to be searched for source and ALI files.
8049 @item -I-
8050 @cindex @option{-I-} (@command{gnatbind})
8051 Do not look for sources in the current directory where @code{gnatbind} was
8052 invoked, and do not look for ALI files in the directory containing the
8053 ALI file named in the @code{gnatbind} command line.
8055 @item -l
8056 @cindex @option{-l} (@command{gnatbind})
8057 Output chosen elaboration order.
8059 @item -L@var{xxx}
8060 @cindex @option{-L} (@command{gnatbind})
8061 Bind the units for library building. In this case the adainit and
8062 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8063 are renamed to @var{xxx}init and
8064 @var{xxx}final.
8065 Implies -n.
8066 (@xref{GNAT and Libraries}, for more details.)
8068 @item -Mxyz
8069 @cindex @option{-M} (@command{gnatbind})
8070 Rename generated main program from main to xyz. This option is
8071 supported on cross environments only.
8073 @item -m@var{n}
8074 @cindex @option{-m} (@command{gnatbind})
8075 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8076 in the range 1..999999. The default value if no switch is
8077 given is 9999. If the number of warnings reaches this limit, then a
8078 message is output and further warnings are suppressed, the bind
8079 continues in this case. If the number of errors reaches this
8080 limit, then a message is output and the bind is abandoned.
8081 A value of zero means that no limit is enforced. The equal
8082 sign is optional.
8084 @item -n
8085 @cindex @option{-n} (@command{gnatbind})
8086 No main program.
8088 @item -nostdinc
8089 @cindex @option{-nostdinc} (@command{gnatbind})
8090 Do not look for sources in the system default directory.
8092 @item -nostdlib
8093 @cindex @option{-nostdlib} (@command{gnatbind})
8094 Do not look for library files in the system default directory.
8096 @item --RTS=@var{rts-path}
8097 @cindex @option{--RTS} (@code{gnatbind})
8098 Specifies the default location of the runtime library. Same meaning as the
8099 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8101 @item -o @var{file}
8102 @cindex @option{-o } (@command{gnatbind})
8103 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8104 Note that if this option is used, then linking must be done manually,
8105 gnatlink cannot be used.
8107 @item -O@r{[=}@var{filename}@r{]}
8108 @cindex @option{-O} (@command{gnatbind})
8109 Output object list (to standard output or to the named file).
8111 @item -p
8112 @cindex @option{-p} (@command{gnatbind})
8113 Pessimistic (worst-case) elaboration order
8115 @item -P
8116 @cindex @option{-P} (@command{gnatbind})
8117 Generate binder file suitable for CodePeer.
8119 @item -R
8120 @cindex @option{-R} (@command{gnatbind})
8121 Output closure source list, which includes all non-time-units that are
8122 included in the bind.
8124 @item -Ra
8125 @cindex @option{-Ra} (@command{gnatbind})
8126 Like @option{-R} but the list includes run-time units.
8128 @item -s
8129 @cindex @option{-s} (@command{gnatbind})
8130 Require all source files to be present.
8132 @item -S@var{xxx}
8133 @cindex @option{-S} (@command{gnatbind})
8134 Specifies the value to be used when detecting uninitialized scalar
8135 objects with pragma Initialize_Scalars.
8136 The @var{xxx} string specified with the switch is one of:
8137 @itemize @bullet
8139 @item ``@option{in}'' for an invalid value
8140 If zero is invalid for the discrete type in question,
8141 then the scalar value is set to all zero bits.
8142 For signed discrete types, the largest possible negative value of
8143 the underlying scalar is set (i.e. a one bit followed by all zero bits).
8144 For unsigned discrete types, the underlying scalar value is set to all
8145 one bits. For floating-point types, a NaN value is set
8146 (see body of package System.Scalar_Values for exact values).
8148 @item ``@option{lo}'' for low value
8149 If zero is invalid for the discrete type in question,
8150 then the scalar value is set to all zero bits.
8151 For signed discrete types, the largest possible negative value of
8152 the underlying scalar is set (i.e. a one bit followed by all zero bits).
8153 For unsigned discrete types, the underlying scalar value is set to all
8154 zero bits. For floating-point, a small value is set
8155 (see body of package System.Scalar_Values for exact values).
8157 @item ``@option{hi}'' for high value
8158 If zero is invalid for the discrete type in question,
8159 then the scalar value is set to all one bits.
8160 For signed discrete types, the largest possible positive value of
8161 the underlying scalar is set (i.e. a zero bit followed by all one bits).
8162 For unsigned discrete types, the underlying scalar value is set to all
8163 one bits. For floating-point, a large value is set
8164 (see body of package System.Scalar_Values for exact values).
8166 @item ``@option{@var{xx}}'' for hex value (two hex digits)
8167 The underlying scalar is set to a value consisting of repeated bytes, whose
8168 value corresponds to the given value. For example if @option{BF} is given,
8169 then a 32-bit scalar value will be set to the bit patterm 16#BFBFBFBF#.
8170 @end itemize
8172 In addition, you can specify @option{-Sev} to indicate that the value is
8173 to be set at run time. In this case, the program will look for an environment
8174 @cindex GNAT_INIT_SCALARS
8175 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8176 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8177 If no environment variable is found, or if it does not have a valid value,
8178 then the default is @option{in} (invalid values).
8180 @item -static
8181 @cindex @option{-static} (@code{gnatbind})
8182 Link against a static GNAT run time.
8184 @item -shared
8185 @cindex @option{-shared} (@code{gnatbind})
8186 Link against a shared GNAT run time when available.
8188 @item -t
8189 @cindex @option{-t} (@code{gnatbind})
8190 Tolerate time stamp and other consistency errors
8192 @item -T@var{n}
8193 @cindex @option{-T} (@code{gnatbind})
8194 Set the time slice value to @var{n} milliseconds. If the system supports
8195 the specification of a specific time slice value, then the indicated value
8196 is used. If the system does not support specific time slice values, but
8197 does support some general notion of round-robin scheduling, then any
8198 nonzero value will activate round-robin scheduling.
8200 A value of zero is treated specially. It turns off time
8201 slicing, and in addition, indicates to the tasking run time that the
8202 semantics should match as closely as possible the Annex D
8203 requirements of the Ada RM, and in particular sets the default
8204 scheduling policy to @code{FIFO_Within_Priorities}.
8206 @item -u@var{n}
8207 @cindex @option{-u} (@code{gnatbind})
8208 Enable dynamic stack usage, with @var{n} results stored and displayed
8209 at program termination. A result is generated when a task
8210 terminates. Results that can't be stored are displayed on the fly, at
8211 task termination. This option is currently not supported on Itanium
8212 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8214 @item -v
8215 @cindex @option{-v} (@code{gnatbind})
8216 Verbose mode. Write error messages, header, summary output to
8217 @file{stdout}.
8219 @item -w@var{x}
8220 @cindex @option{-w} (@code{gnatbind})
8221 Warning mode (@var{x}=s/e for suppress/treat as error)
8224 @item -Wx@var{e}
8225 @cindex @option{-Wx} (@code{gnatbind})
8226 Override default wide character encoding for standard Text_IO files.
8228 @item -x
8229 @cindex @option{-x} (@code{gnatbind})
8230 Exclude source files (check object consistency only).
8233 @item -X@var{nnn}
8234 @cindex @option{-X@var{nnn}} (@code{gnatbind})
8235 Set default exit status value, normally 0 for POSIX compliance.
8238 @item -y
8239 @cindex @option{-y} (@code{gnatbind})
8240 Enable leap seconds support in @code{Ada.Calendar} and its children.
8242 @item -z
8243 @cindex @option{-z} (@code{gnatbind})
8244 No main subprogram.
8245 @end table
8247 @noindent
8248 You may obtain this listing of switches by running @code{gnatbind} with
8249 no arguments.
8251 @node Consistency-Checking Modes
8252 @subsection Consistency-Checking Modes
8254 @noindent
8255 As described earlier, by default @code{gnatbind} checks
8256 that object files are consistent with one another and are consistent
8257 with any source files it can locate. The following switches control binder
8258 access to sources.
8260 @table @option
8261 @c !sort!
8262 @item -s
8263 @cindex @option{-s} (@code{gnatbind})
8264 Require source files to be present. In this mode, the binder must be
8265 able to locate all source files that are referenced, in order to check
8266 their consistency. In normal mode, if a source file cannot be located it
8267 is simply ignored. If you specify this switch, a missing source
8268 file is an error.
8270 @item -Wx@var{e}
8271 @cindex @option{-Wx} (@code{gnatbind})
8272 Override default wide character encoding for standard Text_IO files.
8273 Normally the default wide character encoding method used for standard
8274 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8275 the main source input (see description of switch
8276 @option{-gnatWx} for the compiler). The
8277 use of this switch for the binder (which has the same set of
8278 possible arguments) overrides this default as specified.
8280 @item -x
8281 @cindex @option{-x} (@code{gnatbind})
8282 Exclude source files. In this mode, the binder only checks that ALI
8283 files are consistent with one another. Source files are not accessed.
8284 The binder runs faster in this mode, and there is still a guarantee that
8285 the resulting program is self-consistent.
8286 If a source file has been edited since it was last compiled, and you
8287 specify this switch, the binder will not detect that the object
8288 file is out of date with respect to the source file. Note that this is the
8289 mode that is automatically used by @command{gnatmake} because in this
8290 case the checking against sources has already been performed by
8291 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8293 @end table
8295 @node Binder Error Message Control
8296 @subsection Binder Error Message Control
8298 @noindent
8299 The following switches provide control over the generation of error
8300 messages from the binder:
8302 @table @option
8303 @c !sort!
8304 @item -v
8305 @cindex @option{-v} (@code{gnatbind})
8306 Verbose mode. In the normal mode, brief error messages are generated to
8307 @file{stderr}. If this switch is present, a header is written
8308 to @file{stdout} and any error messages are directed to @file{stdout}.
8309 All that is written to @file{stderr} is a brief summary message.
8311 @item -b
8312 @cindex @option{-b} (@code{gnatbind})
8313 Generate brief error messages to @file{stderr} even if verbose mode is
8314 specified. This is relevant only when used with the
8315 @option{-v} switch.
8317 @item -m@var{n}
8318 @cindex @option{-m} (@code{gnatbind})
8319 Limits the number of error messages to @var{n}, a decimal integer in the
8320 range 1-999. The binder terminates immediately if this limit is reached.
8322 @item -M@var{xxx}
8323 @cindex @option{-M} (@code{gnatbind})
8324 Renames the generated main program from @code{main} to @code{xxx}.
8325 This is useful in the case of some cross-building environments, where
8326 the actual main program is separate from the one generated
8327 by @code{gnatbind}.
8329 @item -ws
8330 @cindex @option{-ws} (@code{gnatbind})
8331 @cindex Warnings
8332 Suppress all warning messages.
8334 @item -we
8335 @cindex @option{-we} (@code{gnatbind})
8336 Treat any warning messages as fatal errors.
8339 @item -t
8340 @cindex @option{-t} (@code{gnatbind})
8341 @cindex Time stamp checks, in binder
8342 @cindex Binder consistency checks
8343 @cindex Consistency checks, in binder
8344 The binder performs a number of consistency checks including:
8346 @itemize @bullet
8347 @item
8348 Check that time stamps of a given source unit are consistent
8349 @item
8350 Check that checksums of a given source unit are consistent
8351 @item
8352 Check that consistent versions of @code{GNAT} were used for compilation
8353 @item
8354 Check consistency of configuration pragmas as required
8355 @end itemize
8357 @noindent
8358 Normally failure of such checks, in accordance with the consistency
8359 requirements of the Ada Reference Manual, causes error messages to be
8360 generated which abort the binder and prevent the output of a binder
8361 file and subsequent link to obtain an executable.
8363 The @option{-t} switch converts these error messages
8364 into warnings, so that
8365 binding and linking can continue to completion even in the presence of such
8366 errors. The result may be a failed link (due to missing symbols), or a
8367 non-functional executable which has undefined semantics.
8368 @emph{This means that
8369 @option{-t} should be used only in unusual situations,
8370 with extreme care.}
8371 @end table
8373 @node Elaboration Control
8374 @subsection Elaboration Control
8376 @noindent
8377 The following switches provide additional control over the elaboration
8378 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8380 @table @option
8381 @item -p
8382 @cindex @option{-p} (@code{gnatbind})
8383 Normally the binder attempts to choose an elaboration order that is
8384 likely to minimize the likelihood of an elaboration order error resulting
8385 in raising a @code{Program_Error} exception. This switch reverses the
8386 action of the binder, and requests that it deliberately choose an order
8387 that is likely to maximize the likelihood of an elaboration error.
8388 This is useful in ensuring portability and avoiding dependence on
8389 accidental fortuitous elaboration ordering.
8391 Normally it only makes sense to use the @option{-p}
8392 switch if dynamic
8393 elaboration checking is used (@option{-gnatE} switch used for compilation).
8394 This is because in the default static elaboration mode, all necessary
8395 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8396 These implicit pragmas are still respected by the binder in
8397 @option{-p} mode, so a
8398 safe elaboration order is assured.
8400 Note that @option{-p} is not intended for
8401 production use; it is more for debugging/experimental use.
8402 @end table
8404 @node Output Control
8405 @subsection Output Control
8407 @noindent
8408 The following switches allow additional control over the output
8409 generated by the binder.
8411 @table @option
8412 @c !sort!
8414 @item -c
8415 @cindex @option{-c} (@code{gnatbind})
8416 Check only. Do not generate the binder output file. In this mode the
8417 binder performs all error checks but does not generate an output file.
8419 @item -e
8420 @cindex @option{-e} (@code{gnatbind})
8421 Output complete list of elaboration-order dependencies, showing the
8422 reason for each dependency. This output can be rather extensive but may
8423 be useful in diagnosing problems with elaboration order. The output is
8424 written to @file{stdout}.
8426 @item -h
8427 @cindex @option{-h} (@code{gnatbind})
8428 Output usage information. The output is written to @file{stdout}.
8430 @item -K
8431 @cindex @option{-K} (@code{gnatbind})
8432 Output linker options to @file{stdout}. Includes library search paths,
8433 contents of pragmas Ident and Linker_Options, and libraries added
8434 by @code{gnatbind}.
8436 @item -l
8437 @cindex @option{-l} (@code{gnatbind})
8438 Output chosen elaboration order. The output is written to @file{stdout}.
8440 @item -O
8441 @cindex @option{-O} (@code{gnatbind})
8442 Output full names of all the object files that must be linked to provide
8443 the Ada component of the program. The output is written to @file{stdout}.
8444 This list includes the files explicitly supplied and referenced by the user
8445 as well as implicitly referenced run-time unit files. The latter are
8446 omitted if the corresponding units reside in shared libraries. The
8447 directory names for the run-time units depend on the system configuration.
8449 @item -o @var{file}
8450 @cindex @option{-o} (@code{gnatbind})
8451 Set name of output file to @var{file} instead of the normal
8452 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8453 binder generated body filename.
8454 Note that if this option is used, then linking must be done manually.
8455 It is not possible to use gnatlink in this case, since it cannot locate
8456 the binder file.
8458 @item -r
8459 @cindex @option{-r} (@code{gnatbind})
8460 Generate list of @code{pragma Restrictions} that could be applied to
8461 the current unit. This is useful for code audit purposes, and also may
8462 be used to improve code generation in some cases.
8464 @end table
8466 @node Dynamic Allocation Control
8467 @subsection Dynamic Allocation Control
8469 @noindent
8470 The heap control switches -- @option{-H32} and @option{-H64} --
8471 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8472 They only affect compiler-generated allocations via @code{__gnat_malloc};
8473 explicit calls to @code{malloc} and related functions from the C
8474 run-time library are unaffected.
8476 @table @option
8477 @item -H32
8478 Allocate memory on 32-bit heap
8480 @item -H64
8481 Allocate memory on 64-bit heap.  This is the default
8482 unless explicitly overridden by a @code{'Size} clause on the access type.
8483 @end table
8485 @noindent
8486 These switches are only effective on VMS platforms.
8489 @node Binding with Non-Ada Main Programs
8490 @subsection Binding with Non-Ada Main Programs
8492 @noindent
8493 In our description so far we have assumed that the main
8494 program is in Ada, and that the task of the binder is to generate a
8495 corresponding function @code{main} that invokes this Ada main
8496 program. GNAT also supports the building of executable programs where
8497 the main program is not in Ada, but some of the called routines are
8498 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8499 The following switch is used in this situation:
8501 @table @option
8502 @item -n
8503 @cindex @option{-n} (@code{gnatbind})
8504 No main program. The main program is not in Ada.
8505 @end table
8507 @noindent
8508 In this case, most of the functions of the binder are still required,
8509 but instead of generating a main program, the binder generates a file
8510 containing the following callable routines:
8512 @table @code
8513 @item adainit
8514 @findex adainit
8515 You must call this routine to initialize the Ada part of the program by
8516 calling the necessary elaboration routines. A call to @code{adainit} is
8517 required before the first call to an Ada subprogram.
8519 Note that it is assumed that the basic execution environment must be setup
8520 to be appropriate for Ada execution at the point where the first Ada
8521 subprogram is called. In particular, if the Ada code will do any
8522 floating-point operations, then the FPU must be setup in an appropriate
8523 manner. For the case of the x86, for example, full precision mode is
8524 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8525 that the FPU is in the right state.
8527 @item adafinal
8528 @findex adafinal
8529 You must call this routine to perform any library-level finalization
8530 required by the Ada subprograms. A call to @code{adafinal} is required
8531 after the last call to an Ada subprogram, and before the program
8532 terminates.
8533 @end table
8535 @noindent
8536 If the @option{-n} switch
8537 @cindex @option{-n} (@command{gnatbind})
8538 @cindex Binder, multiple input files
8539 is given, more than one ALI file may appear on
8540 the command line for @code{gnatbind}. The normal @dfn{closure}
8541 calculation is performed for each of the specified units. Calculating
8542 the closure means finding out the set of units involved by tracing
8543 @code{with} references. The reason it is necessary to be able to
8544 specify more than one ALI file is that a given program may invoke two or
8545 more quite separate groups of Ada units.
8547 The binder takes the name of its output file from the last specified ALI
8548 file, unless overridden by the use of the @option{-o file}.
8549 @cindex @option{-o} (@command{gnatbind})
8550 The output is an Ada unit in source form that can be compiled with GNAT.
8551 This compilation occurs automatically as part of the @command{gnatlink}
8552 processing.
8554 Currently the GNAT run time requires a FPU using 80 bits mode
8555 precision. Under targets where this is not the default it is required to
8556 call GNAT.Float_Control.Reset before using floating point numbers (this
8557 include float computation, float input and output) in the Ada code. A
8558 side effect is that this could be the wrong mode for the foreign code
8559 where floating point computation could be broken after this call.
8561 @node Binding Programs with No Main Subprogram
8562 @subsection Binding Programs with No Main Subprogram
8564 @noindent
8565 It is possible to have an Ada program which does not have a main
8566 subprogram. This program will call the elaboration routines of all the
8567 packages, then the finalization routines.
8569 The following switch is used to bind programs organized in this manner:
8571 @table @option
8572 @item -z
8573 @cindex @option{-z} (@code{gnatbind})
8574 Normally the binder checks that the unit name given on the command line
8575 corresponds to a suitable main subprogram. When this switch is used,
8576 a list of ALI files can be given, and the execution of the program
8577 consists of elaboration of these units in an appropriate order. Note
8578 that the default wide character encoding method for standard Text_IO
8579 files is always set to Brackets if this switch is set (you can use
8580 the binder switch
8581 @option{-Wx} to override this default).
8582 @end table
8584 @node Command-Line Access
8585 @section Command-Line Access
8587 @noindent
8588 The package @code{Ada.Command_Line} provides access to the command-line
8589 arguments and program name. In order for this interface to operate
8590 correctly, the two variables
8592 @smallexample
8593 @group
8594 int gnat_argc;
8595 char **gnat_argv;
8596 @end group
8597 @end smallexample
8599 @noindent
8600 @findex gnat_argv
8601 @findex gnat_argc
8602 are declared in one of the GNAT library routines. These variables must
8603 be set from the actual @code{argc} and @code{argv} values passed to the
8604 main program. With no @option{n} present, @code{gnatbind}
8605 generates the C main program to automatically set these variables.
8606 If the @option{n} switch is used, there is no automatic way to
8607 set these variables. If they are not set, the procedures in
8608 @code{Ada.Command_Line} will not be available, and any attempt to use
8609 them will raise @code{Constraint_Error}. If command line access is
8610 required, your main program must set @code{gnat_argc} and
8611 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8614 @node Search Paths for gnatbind
8615 @section Search Paths for @code{gnatbind}
8617 @noindent
8618 The binder takes the name of an ALI file as its argument and needs to
8619 locate source files as well as other ALI files to verify object consistency.
8621 For source files, it follows exactly the same search rules as @command{gcc}
8622 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8623 directories searched are:
8625 @enumerate
8626 @item
8627 The directory containing the ALI file named in the command line, unless
8628 the switch @option{-I-} is specified.
8630 @item
8631 All directories specified by @option{-I}
8632 switches on the @code{gnatbind}
8633 command line, in the order given.
8635 @item
8636 @findex ADA_PRJ_OBJECTS_FILE
8637 Each of the directories listed in the text file whose name is given
8638 by the @env{ADA_PRJ_OBJECTS_FILE} environment variable.
8640 @noindent
8641 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
8642 driver when project files are used. It should not normally be set
8643 by other means.
8645 @item
8646 @findex ADA_OBJECTS_PATH
8647 Each of the directories listed in the value of the
8648 @env{ADA_OBJECTS_PATH} environment variable.
8649 Construct this value
8650 exactly as the @env{PATH} environment variable: a list of directory
8651 names separated by colons (semicolons when working with the NT version
8652 of GNAT).
8654 @item
8655 The content of the @file{ada_object_path} file which is part of the GNAT
8656 installation tree and is used to store standard libraries such as the
8657 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8658 specified.
8659 @ref{Installing a library}
8660 @end enumerate
8662 @noindent
8663 In the binder the switch @option{-I}
8664 @cindex @option{-I} (@command{gnatbind})
8665 is used to specify both source and
8666 library file paths. Use @option{-aI}
8667 @cindex @option{-aI} (@command{gnatbind})
8668 instead if you want to specify
8669 source paths only, and @option{-aO}
8670 @cindex @option{-aO} (@command{gnatbind})
8671 if you want to specify library paths
8672 only. This means that for the binder
8673 @option{-I}@var{dir} is equivalent to
8674 @option{-aI}@var{dir}
8675 @option{-aO}@var{dir}.
8676 The binder generates the bind file (a C language source file) in the
8677 current working directory.
8679 @findex Ada
8680 @findex System
8681 @findex Interfaces
8682 @findex GNAT
8683 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8684 children make up the GNAT Run-Time Library, together with the package
8685 GNAT and its children, which contain a set of useful additional
8686 library functions provided by GNAT. The sources for these units are
8687 needed by the compiler and are kept together in one directory. The ALI
8688 files and object files generated by compiling the RTL are needed by the
8689 binder and the linker and are kept together in one directory, typically
8690 different from the directory containing the sources. In a normal
8691 installation, you need not specify these directory names when compiling
8692 or binding. Either the environment variables or the built-in defaults
8693 cause these files to be found.
8695 Besides simplifying access to the RTL, a major use of search paths is
8696 in compiling sources from multiple directories. This can make
8697 development environments much more flexible.
8699 @node Examples of gnatbind Usage
8700 @section Examples of @code{gnatbind} Usage
8702 @noindent
8703 This section contains a number of examples of using the GNAT binding
8704 utility @code{gnatbind}.
8706 @table @code
8707 @item gnatbind hello
8708 The main program @code{Hello} (source program in @file{hello.adb}) is
8709 bound using the standard switch settings. The generated main program is
8710 @file{b~hello.adb}. This is the normal, default use of the binder.
8712 @item gnatbind hello -o mainprog.adb
8713 The main program @code{Hello} (source program in @file{hello.adb}) is
8714 bound using the standard switch settings. The generated main program is
8715 @file{mainprog.adb} with the associated spec in
8716 @file{mainprog.ads}. Note that you must specify the body here not the
8717 spec. Note that if this option is used, then linking must be done manually,
8718 since gnatlink will not be able to find the generated file.
8719 @end table
8721 @c ------------------------------------
8722 @node Linking with gnatlink
8723 @chapter Linking with @command{gnatlink}
8724 @c ------------------------------------
8725 @findex gnatlink
8727 @noindent
8728 This chapter discusses @command{gnatlink}, a tool that links
8729 an Ada program and builds an executable file. This utility
8730 invokes the system linker (via the @command{gcc} command)
8731 with a correct list of object files and library references.
8732 @command{gnatlink} automatically determines the list of files and
8733 references for the Ada part of a program. It uses the binder file
8734 generated by the @command{gnatbind} to determine this list.
8736 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8737 driver (see @ref{The GNAT Driver and Project Files}).
8739 @menu
8740 * Running gnatlink::
8741 * Switches for gnatlink::
8742 @end menu
8744 @node Running gnatlink
8745 @section Running @command{gnatlink}
8747 @noindent
8748 The form of the @command{gnatlink} command is
8750 @smallexample
8751 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8752 @c            @ovar{non-Ada objects} @ovar{linker options}
8753 @c Expanding @ovar macro inline (explanation in macro def comments)
8754 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8755            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8757 @end smallexample
8759 @noindent
8760 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8761 non-Ada objects
8762 or linker options) may be in any order, provided that no non-Ada object may
8763 be mistaken for a main @file{ALI} file.
8764 Any file name @file{F} without the @file{.ali}
8765 extension will be taken as the main @file{ALI} file if a file exists
8766 whose name is the concatenation of @file{F} and @file{.ali}.
8768 @noindent
8769 @file{@var{mainprog}.ali} references the ALI file of the main program.
8770 The @file{.ali} extension of this file can be omitted. From this
8771 reference, @command{gnatlink} locates the corresponding binder file
8772 @file{b~@var{mainprog}.adb} and, using the information in this file along
8773 with the list of non-Ada objects and linker options, constructs a
8774 linker command file to create the executable.
8776 The arguments other than the @command{gnatlink} switches and the main
8777 @file{ALI} file are passed to the linker uninterpreted.
8778 They typically include the names of
8779 object files for units written in other languages than Ada and any library
8780 references required to resolve references in any of these foreign language
8781 units, or in @code{Import} pragmas in any Ada units.
8783 @var{linker options} is an optional list of linker specific
8784 switches.
8785 The default linker called by gnatlink is @command{gcc} which in
8786 turn calls the appropriate system linker.
8788 One useful option for the linker is @option{-s}: it reduces the size of the
8789 executable by removing all symbol table and relocation information from the
8790 executable.
8792 Standard options for the linker such as @option{-lmy_lib} or
8793 @option{-Ldir} can be added as is.
8794 For options that are not recognized by
8795 @command{gcc} as linker options, use the @command{gcc} switches
8796 @option{-Xlinker} or @option{-Wl,}.
8798 Refer to the GCC documentation for
8799 details.
8801 Here is an example showing how to generate a linker map:
8803 @smallexample
8804 $ gnatlink my_prog -Wl,-Map,MAPFILE
8805 @end smallexample
8807 Using @var{linker options} it is possible to set the program stack and
8808 heap size.
8809 See @ref{Setting Stack Size from gnatlink} and
8810 @ref{Setting Heap Size from gnatlink}.
8812 @command{gnatlink} determines the list of objects required by the Ada
8813 program and prepends them to the list of objects passed to the linker.
8814 @command{gnatlink} also gathers any arguments set by the use of
8815 @code{pragma Linker_Options} and adds them to the list of arguments
8816 presented to the linker.
8819 @node Switches for gnatlink
8820 @section Switches for @command{gnatlink}
8822 @noindent
8823 The following switches are available with the @command{gnatlink} utility:
8825 @table @option
8826 @c !sort!
8828 @item --version
8829 @cindex @option{--version} @command{gnatlink}
8830 Display Copyright and version, then exit disregarding all other options.
8832 @item --help
8833 @cindex @option{--help} @command{gnatlink}
8834 If @option{--version} was not used, display usage, then exit disregarding
8835 all other options.
8837 @item -f
8838 @cindex Command line length
8839 @cindex @option{-f} (@command{gnatlink})
8840 On some targets, the command line length is limited, and @command{gnatlink}
8841 will generate a separate file for the linker if the list of object files
8842 is too long.
8843 The @option{-f} switch forces this file
8844 to be generated even if
8845 the limit is not exceeded. This is useful in some cases to deal with
8846 special situations where the command line length is exceeded.
8848 @item -g
8849 @cindex Debugging information, including
8850 @cindex @option{-g} (@command{gnatlink})
8851 The option to include debugging information causes the Ada bind file (in
8852 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8853 @option{-g}.
8854 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8855 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8856 Without @option{-g}, the binder removes these files by
8857 default. The same procedure apply if a C bind file was generated using
8858 @option{-C} @code{gnatbind} option, in this case the filenames
8859 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8861 @item -n
8862 @cindex @option{-n} (@command{gnatlink})
8863 Do not compile the file generated by the binder. This may be used when
8864 a link is rerun with different options, but there is no need to recompile
8865 the binder file.
8867 @item -v
8868 @cindex @option{-v} (@command{gnatlink})
8869 Causes additional information to be output, including a full list of the
8870 included object files. This switch option is most useful when you want
8871 to see what set of object files are being used in the link step.
8873 @item -v -v
8874 @cindex @option{-v -v} (@command{gnatlink})
8875 Very verbose mode. Requests that the compiler operate in verbose mode when
8876 it compiles the binder file, and that the system linker run in verbose mode.
8878 @item -o @var{exec-name}
8879 @cindex @option{-o} (@command{gnatlink})
8880 @var{exec-name} specifies an alternate name for the generated
8881 executable program. If this switch is omitted, the executable has the same
8882 name as the main unit. For example, @code{gnatlink try.ali} creates
8883 an executable called @file{try}.
8885 @item -b @var{target}
8886 @cindex @option{-b} (@command{gnatlink})
8887 Compile your program to run on @var{target}, which is the name of a
8888 system configuration. You must have a GNAT cross-compiler built if
8889 @var{target} is not the same as your host system.
8891 @item -B@var{dir}
8892 @cindex @option{-B} (@command{gnatlink})
8893 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8894 from @var{dir} instead of the default location. Only use this switch
8895 when multiple versions of the GNAT compiler are available.
8896 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8897 for further details. You would normally use the @option{-b} or
8898 @option{-V} switch instead.
8900 @item -M
8901 When linking an executable, create a map file. The name of the map file
8902 has the same name as the executable with extension ".map".
8904 @item -M=mapfile
8905 When linking an executable, create a map file. The name of the map file is
8906 "mapfile".
8908 @item --GCC=@var{compiler_name}
8909 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8910 Program used for compiling the binder file. The default is
8911 @command{gcc}. You need to use quotes around @var{compiler_name} if
8912 @code{compiler_name} contains spaces or other separator characters.
8913 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8914 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8915 inserted after your command name. Thus in the above example the compiler
8916 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8917 A limitation of this syntax is that the name and path name of the executable
8918 itself must not include any embedded spaces. If the compiler executable is
8919 different from the default one (gcc or <prefix>-gcc), then the back-end
8920 switches in the ALI file are not used to compile the binder generated source.
8921 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8922 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8923 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8924 is taken into account. However, all the additional switches are also taken
8925 into account. Thus,
8926 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8927 @option{--GCC="bar -x -y -z -t"}.
8929 @item --LINK=@var{name}
8930 @cindex @option{--LINK=} (@command{gnatlink})
8931 @var{name} is the name of the linker to be invoked. This is especially
8932 useful in mixed language programs since languages such as C++ require
8933 their own linker to be used. When this switch is omitted, the default
8934 name for the linker is @command{gcc}. When this switch is used, the
8935 specified linker is called instead of @command{gcc} with exactly the same
8936 parameters that would have been passed to @command{gcc} so if the desired
8937 linker requires different parameters it is necessary to use a wrapper
8938 script that massages the parameters before invoking the real linker. It
8939 may be useful to control the exact invocation by using the verbose
8940 switch.
8944 @end table
8946 @node The GNAT Make Program gnatmake
8947 @chapter The GNAT Make Program @command{gnatmake}
8948 @findex gnatmake
8950 @menu
8951 * Running gnatmake::
8952 * Switches for gnatmake::
8953 * Mode Switches for gnatmake::
8954 * Notes on the Command Line::
8955 * How gnatmake Works::
8956 * Examples of gnatmake Usage::
8957 @end menu
8958 @noindent
8959 A typical development cycle when working on an Ada program consists of
8960 the following steps:
8962 @enumerate
8963 @item
8964 Edit some sources to fix bugs.
8966 @item
8967 Add enhancements.
8969 @item
8970 Compile all sources affected.
8972 @item
8973 Rebind and relink.
8975 @item
8976 Test.
8977 @end enumerate
8979 @noindent
8980 The third step can be tricky, because not only do the modified files
8981 @cindex Dependency rules
8982 have to be compiled, but any files depending on these files must also be
8983 recompiled. The dependency rules in Ada can be quite complex, especially
8984 in the presence of overloading, @code{use} clauses, generics and inlined
8985 subprograms.
8987 @command{gnatmake} automatically takes care of the third and fourth steps
8988 of this process. It determines which sources need to be compiled,
8989 compiles them, and binds and links the resulting object files.
8991 Unlike some other Ada make programs, the dependencies are always
8992 accurately recomputed from the new sources. The source based approach of
8993 the GNAT compilation model makes this possible. This means that if
8994 changes to the source program cause corresponding changes in
8995 dependencies, they will always be tracked exactly correctly by
8996 @command{gnatmake}.
8998 @node Running gnatmake
8999 @section Running @command{gnatmake}
9001 @noindent
9002 The usual form of the @command{gnatmake} command is
9004 @smallexample
9005 @c $ gnatmake @ovar{switches} @var{file_name}
9006 @c       @ovar{file_names} @ovar{mode_switches}
9007 @c Expanding @ovar macro inline (explanation in macro def comments)
9008 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9009       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9010 @end smallexample
9012 @noindent
9013 The only required argument is one @var{file_name}, which specifies
9014 a compilation unit that is a main program. Several @var{file_names} can be
9015 specified: this will result in several executables being built.
9016 If @code{switches} are present, they can be placed before the first
9017 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9018 If @var{mode_switches} are present, they must always be placed after
9019 the last @var{file_name} and all @code{switches}.
9021 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9022 extension may be omitted from the @var{file_name} arguments. However, if
9023 you are using non-standard extensions, then it is required that the
9024 extension be given. A relative or absolute directory path can be
9025 specified in a @var{file_name}, in which case, the input source file will
9026 be searched for in the specified directory only. Otherwise, the input
9027 source file will first be searched in the directory where
9028 @command{gnatmake} was invoked and if it is not found, it will be search on
9029 the source path of the compiler as described in
9030 @ref{Search Paths and the Run-Time Library (RTL)}.
9032 All @command{gnatmake} output (except when you specify
9033 @option{-M}) is to
9034 @file{stderr}. The output produced by the
9035 @option{-M} switch is send to
9036 @file{stdout}.
9038 @node Switches for gnatmake
9039 @section Switches for @command{gnatmake}
9041 @noindent
9042 You may specify any of the following switches to @command{gnatmake}:
9044 @table @option
9045 @c !sort!
9047 @item --version
9048 @cindex @option{--version} @command{gnatmake}
9049 Display Copyright and version, then exit disregarding all other options.
9051 @item --help
9052 @cindex @option{--help} @command{gnatmake}
9053 If @option{--version} was not used, display usage, then exit disregarding
9054 all other options.
9056 @item --GCC=@var{compiler_name}
9057 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9058 Program used for compiling. The default is `@command{gcc}'. You need to use
9059 quotes around @var{compiler_name} if @code{compiler_name} contains
9060 spaces or other separator characters. As an example @option{--GCC="foo -x
9061 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9062 compiler. A limitation of this syntax is that the name and path name of
9063 the executable itself must not include any embedded spaces. Note that
9064 switch @option{-c} is always inserted after your command name. Thus in the
9065 above example the compiler command that will be used by @command{gnatmake}
9066 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9067 used, only the last @var{compiler_name} is taken into account. However,
9068 all the additional switches are also taken into account. Thus,
9069 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9070 @option{--GCC="bar -x -y -z -t"}.
9072 @item --GNATBIND=@var{binder_name}
9073 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9074 Program used for binding. The default is `@code{gnatbind}'. You need to
9075 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9076 or other separator characters. As an example @option{--GNATBIND="bar -x
9077 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9078 binder. Binder switches that are normally appended by @command{gnatmake}
9079 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9080 A limitation of this syntax is that the name and path name of the executable
9081 itself must not include any embedded spaces.
9083 @item --GNATLINK=@var{linker_name}
9084 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9085 Program used for linking. The default is `@command{gnatlink}'. You need to
9086 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9087 or other separator characters. As an example @option{--GNATLINK="lan -x
9088 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9089 linker. Linker switches that are normally appended by @command{gnatmake} to
9090 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9091 A limitation of this syntax is that the name and path name of the executable
9092 itself must not include any embedded spaces.
9095 @item --subdirs=subdir
9096 Actual object directory of each project file is the subdirectory subdir of the
9097 object directory specified or defaulted in the project file.
9099 @item --single-compile-per-obj-dir
9100 Disallow simultaneous compilations in the same object directory when
9101 project files are used.
9103 @item --unchecked-shared-lib-imports
9104 By default, shared library projects are not allowed to import static library
9105 projects. When this switch is used on the command line, this restriction is
9106 relaxed.
9108 @item --source-info=<source info file>
9109 Specify a source info file. This switch is active only when project files
9110 are used. If the source info file is specified as a relative path, then it is
9111 relative to the object directory of the main project. If the source info file
9112 does not exist, then after the Project Manager has successfully parsed and
9113 processed the project files and found the sources, it creates the source info
9114 file. If the source info file already exists and can be read successfully,
9115 then the Project Manager will get all the needed information about the sources
9116 from the source info file and will not look for them. This reduces the time
9117 to process the project files, especially when looking for sources that take a
9118 long time. If the source info file exists but cannot be parsed successfully,
9119 the Project Manager will attempt to recreate it. If the Project Manager fails
9120 to create the source info file, a message is issued, but gnatmake does not
9121 fail. @command{gnatmake} "trusts" the source info file. This means that
9122 if the source files have changed (addition, deletion, moving to a different
9123 source directory), then the source info file need to be deleted and recreated.
9125 @item --create-map-file
9126 When linking an executable, create a map file. The name of the map file
9127 has the same name as the executable with extension ".map".
9129 @item --create-map-file=mapfile
9130 When linking an executable, create a map file. The name of the map file is
9131 "mapfile".
9134 @item -a
9135 @cindex @option{-a} (@command{gnatmake})
9136 Consider all files in the make process, even the GNAT internal system
9137 files (for example, the predefined Ada library files), as well as any
9138 locked files. Locked files are files whose ALI file is write-protected.
9139 By default,
9140 @command{gnatmake} does not check these files,
9141 because the assumption is that the GNAT internal files are properly up
9142 to date, and also that any write protected ALI files have been properly
9143 installed. Note that if there is an installation problem, such that one
9144 of these files is not up to date, it will be properly caught by the
9145 binder.
9146 You may have to specify this switch if you are working on GNAT
9147 itself. The switch @option{-a} is also useful
9148 in conjunction with @option{-f}
9149 if you need to recompile an entire application,
9150 including run-time files, using special configuration pragmas,
9151 such as a @code{Normalize_Scalars} pragma.
9153 By default
9154 @code{gnatmake -a} compiles all GNAT
9155 internal files with
9156 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9158 @item -b
9159 @cindex @option{-b} (@command{gnatmake})
9160 Bind only. Can be combined with @option{-c} to do
9161 compilation and binding, but no link.
9162 Can be combined with @option{-l}
9163 to do binding and linking. When not combined with
9164 @option{-c}
9165 all the units in the closure of the main program must have been previously
9166 compiled and must be up to date. The root unit specified by @var{file_name}
9167 may be given without extension, with the source extension or, if no GNAT
9168 Project File is specified, with the ALI file extension.
9170 @item -c
9171 @cindex @option{-c} (@command{gnatmake})
9172 Compile only. Do not perform binding, except when @option{-b}
9173 is also specified. Do not perform linking, except if both
9174 @option{-b} and
9175 @option{-l} are also specified.
9176 If the root unit specified by @var{file_name} is not a main unit, this is the
9177 default. Otherwise @command{gnatmake} will attempt binding and linking
9178 unless all objects are up to date and the executable is more recent than
9179 the objects.
9181 @item -C
9182 @cindex @option{-C} (@command{gnatmake})
9183 Use a temporary mapping file. A mapping file is a way to communicate
9184 to the compiler two mappings: from unit names to file names (without
9185 any directory information) and from file names to path names (with
9186 full directory information). A mapping file can make the compiler's
9187 file searches faster, especially if there are many source directories,
9188 or the sources are read over a slow network connection. If
9189 @option{-P} is used, a mapping file is always used, so
9190 @option{-C} is unnecessary; in this case the mapping file
9191 is initially populated based on the project file. If
9192 @option{-C} is used without
9193 @option{-P},
9194 the mapping file is initially empty. Each invocation of the compiler
9195 will add any newly accessed sources to the mapping file.
9197 @item -C=@var{file}
9198 @cindex @option{-C=} (@command{gnatmake})
9199 Use a specific mapping file. The file, specified as a path name (absolute or
9200 relative) by this switch, should already exist, otherwise the switch is
9201 ineffective. The specified mapping file will be communicated to the compiler.
9202 This switch is not compatible with a project file
9203 (-P@var{file}) or with multiple compiling processes
9204 (-jnnn, when nnn is greater than 1).
9206 @item -d
9207 @cindex @option{-d} (@command{gnatmake})
9208 Display progress for each source, up to date or not, as a single line
9210 @smallexample
9211 completed x out of y (zz%)
9212 @end smallexample
9214 If the file needs to be compiled this is displayed after the invocation of
9215 the compiler. These lines are displayed even in quiet output mode.
9217 @item -D @var{dir}
9218 @cindex @option{-D} (@command{gnatmake})
9219 Put all object files and ALI file in directory @var{dir}.
9220 If the @option{-D} switch is not used, all object files
9221 and ALI files go in the current working directory.
9223 This switch cannot be used when using a project file.
9225 @item -eInnn
9226 @cindex @option{-eI} (@command{gnatmake})
9227 Indicates that the main source is a multi-unit source and the rank of the unit
9228 in the source file is nnn. nnn needs to be a positive number and a valid
9229 index in the source. This switch cannot be used when @command{gnatmake} is
9230 invoked for several mains.
9232 @item -eL
9233 @cindex @option{-eL} (@command{gnatmake})
9234 @cindex symbolic links
9235 Follow all symbolic links when processing project files.
9236 This should be used if your project uses symbolic links for files or
9237 directories, but is not needed in other cases.
9239 @cindex naming scheme
9240 This also assumes that no directory matches the naming scheme for files (for
9241 instance that you do not have a directory called "sources.ads" when using the
9242 default GNAT naming scheme).
9244 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9245 save a lot of system calls (several per source file and object file), which
9246 can result in a significant speed up to load and manipulate a project file,
9247 especially when using source files from a remote system.
9250 @item -eS
9251 @cindex @option{-eS} (@command{gnatmake})
9252 Output the commands for the compiler, the binder and the linker
9253 on standard output,
9254 instead of standard error.
9256 @item -f
9257 @cindex @option{-f} (@command{gnatmake})
9258 Force recompilations. Recompile all sources, even though some object
9259 files may be up to date, but don't recompile predefined or GNAT internal
9260 files or locked files (files with a write-protected ALI file),
9261 unless the @option{-a} switch is also specified.
9263 @item -F
9264 @cindex @option{-F} (@command{gnatmake})
9265 When using project files, if some errors or warnings are detected during
9266 parsing and verbose mode is not in effect (no use of switch
9267 -v), then error lines start with the full path name of the project
9268 file, rather than its simple file name.
9270 @item -g
9271 @cindex @option{-g} (@command{gnatmake})
9272 Enable debugging. This switch is simply passed to the compiler and to the
9273 linker.
9275 @item -i
9276 @cindex @option{-i} (@command{gnatmake})
9277 In normal mode, @command{gnatmake} compiles all object files and ALI files
9278 into the current directory. If the @option{-i} switch is used,
9279 then instead object files and ALI files that already exist are overwritten
9280 in place. This means that once a large project is organized into separate
9281 directories in the desired manner, then @command{gnatmake} will automatically
9282 maintain and update this organization. If no ALI files are found on the
9283 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9284 the new object and ALI files are created in the
9285 directory containing the source being compiled. If another organization
9286 is desired, where objects and sources are kept in different directories,
9287 a useful technique is to create dummy ALI files in the desired directories.
9288 When detecting such a dummy file, @command{gnatmake} will be forced to
9289 recompile the corresponding source file, and it will be put the resulting
9290 object and ALI files in the directory where it found the dummy file.
9292 @item -j@var{n}
9293 @cindex @option{-j} (@command{gnatmake})
9294 @cindex Parallel make
9295 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9296 machine compilations will occur in parallel. If @var{n} is 0, then the
9297 maximum number of parallel compilations is the number of core processors
9298 on the platform. In the event of compilation errors, messages from various
9299 compilations might get interspersed (but @command{gnatmake} will give you the
9300 full ordered list of failing compiles at the end). If this is problematic,
9301 rerun the make process with n set to 1 to get a clean list of messages.
9303 @item -k
9304 @cindex @option{-k} (@command{gnatmake})
9305 Keep going. Continue as much as possible after a compilation error. To
9306 ease the programmer's task in case of compilation errors, the list of
9307 sources for which the compile fails is given when @command{gnatmake}
9308 terminates.
9310 If @command{gnatmake} is invoked with several @file{file_names} and with this
9311 switch, if there are compilation errors when building an executable,
9312 @command{gnatmake} will not attempt to build the following executables.
9314 @item -l
9315 @cindex @option{-l} (@command{gnatmake})
9316 Link only. Can be combined with @option{-b} to binding
9317 and linking. Linking will not be performed if combined with
9318 @option{-c}
9319 but not with @option{-b}.
9320 When not combined with @option{-b}
9321 all the units in the closure of the main program must have been previously
9322 compiled and must be up to date, and the main program needs to have been bound.
9323 The root unit specified by @var{file_name}
9324 may be given without extension, with the source extension or, if no GNAT
9325 Project File is specified, with the ALI file extension.
9327 @item -m
9328 @cindex @option{-m} (@command{gnatmake})
9329 Specify that the minimum necessary amount of recompilations
9330 be performed. In this mode @command{gnatmake} ignores time
9331 stamp differences when the only
9332 modifications to a source file consist in adding/removing comments,
9333 empty lines, spaces or tabs. This means that if you have changed the
9334 comments in a source file or have simply reformatted it, using this
9335 switch will tell @command{gnatmake} not to recompile files that depend on it
9336 (provided other sources on which these files depend have undergone no
9337 semantic modifications). Note that the debugging information may be
9338 out of date with respect to the sources if the @option{-m} switch causes
9339 a compilation to be switched, so the use of this switch represents a
9340 trade-off between compilation time and accurate debugging information.
9342 @item -M
9343 @cindex Dependencies, producing list
9344 @cindex @option{-M} (@command{gnatmake})
9345 Check if all objects are up to date. If they are, output the object
9346 dependences to @file{stdout} in a form that can be directly exploited in
9347 a @file{Makefile}. By default, each source file is prefixed with its
9348 (relative or absolute) directory name. This name is whatever you
9349 specified in the various @option{-aI}
9350 and @option{-I} switches. If you use
9351 @code{gnatmake -M}
9352 @option{-q}
9353 (see below), only the source file names,
9354 without relative paths, are output. If you just specify the
9355 @option{-M}
9356 switch, dependencies of the GNAT internal system files are omitted. This
9357 is typically what you want. If you also specify
9358 the @option{-a} switch,
9359 dependencies of the GNAT internal files are also listed. Note that
9360 dependencies of the objects in external Ada libraries (see switch
9361 @option{-aL}@var{dir} in the following list)
9362 are never reported.
9364 @item -n
9365 @cindex @option{-n} (@command{gnatmake})
9366 Don't compile, bind, or link. Checks if all objects are up to date.
9367 If they are not, the full name of the first file that needs to be
9368 recompiled is printed.
9369 Repeated use of this option, followed by compiling the indicated source
9370 file, will eventually result in recompiling all required units.
9372 @item -o @var{exec_name}
9373 @cindex @option{-o} (@command{gnatmake})
9374 Output executable name. The name of the final executable program will be
9375 @var{exec_name}. If the @option{-o} switch is omitted the default
9376 name for the executable will be the name of the input file in appropriate form
9377 for an executable file on the host system.
9379 This switch cannot be used when invoking @command{gnatmake} with several
9380 @file{file_names}.
9382 @item -p or --create-missing-dirs
9383 @cindex @option{-p} (@command{gnatmake})
9384 When using project files (-P@var{project}), create
9385 automatically missing object directories, library directories and exec
9386 directories.
9388 @item -P@var{project}
9389 @cindex @option{-P} (@command{gnatmake})
9390 Use project file @var{project}. Only one such switch can be used.
9391 @xref{gnatmake and Project Files}.
9393 @item -q
9394 @cindex @option{-q} (@command{gnatmake})
9395 Quiet. When this flag is not set, the commands carried out by
9396 @command{gnatmake} are displayed.
9398 @item -s
9399 @cindex @option{-s} (@command{gnatmake})
9400 Recompile if compiler switches have changed since last compilation.
9401 All compiler switches but -I and -o are taken into account in the
9402 following way:
9403 orders between different ``first letter'' switches are ignored, but
9404 orders between same switches are taken into account. For example,
9405 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9406 is equivalent to @option{-O -g}.
9408 This switch is recommended when Integrated Preprocessing is used.
9410 @item -u
9411 @cindex @option{-u} (@command{gnatmake})
9412 Unique. Recompile at most the main files. It implies -c. Combined with
9413 -f, it is equivalent to calling the compiler directly. Note that using
9414 -u with a project file and no main has a special meaning
9415 (@pxref{Project Files and Main Subprograms}).
9417 @item -U
9418 @cindex @option{-U} (@command{gnatmake})
9419 When used without a project file or with one or several mains on the command
9420 line, is equivalent to -u. When used with a project file and no main
9421 on the command line, all sources of all project files are checked and compiled
9422 if not up to date, and libraries are rebuilt, if necessary.
9424 @item -v
9425 @cindex @option{-v} (@command{gnatmake})
9426 Verbose. Display the reason for all recompilations @command{gnatmake}
9427 decides are necessary, with the highest verbosity level.
9429 @item -vl
9430 @cindex @option{-vl} (@command{gnatmake})
9431 Verbosity level Low. Display fewer lines than in verbosity Medium.
9433 @item -vm
9434 @cindex @option{-vm} (@command{gnatmake})
9435 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9437 @item -vh
9438 @cindex @option{-vm} (@command{gnatmake})
9439 Verbosity level High. Equivalent to -v.
9441 @item -vP@emph{x}
9442 Indicate the verbosity of the parsing of GNAT project files.
9443 @xref{Switches Related to Project Files}.
9445 @item -x
9446 @cindex @option{-x} (@command{gnatmake})
9447 Indicate that sources that are not part of any Project File may be compiled.
9448 Normally, when using Project Files, only sources that are part of a Project
9449 File may be compile. When this switch is used, a source outside of all Project
9450 Files may be compiled. The ALI file and the object file will be put in the
9451 object directory of the main Project. The compilation switches used will only
9452 be those specified on the command line. Even when
9453 @option{-x} is used, mains specified on the
9454 command line need to be sources of a project file.
9456 @item -X@var{name=value}
9457 Indicate that external variable @var{name} has the value @var{value}.
9458 The Project Manager will use this value for occurrences of
9459 @code{external(name)} when parsing the project file.
9460 @xref{Switches Related to Project Files}.
9462 @item -z
9463 @cindex @option{-z} (@command{gnatmake})
9464 No main subprogram. Bind and link the program even if the unit name
9465 given on the command line is a package name. The resulting executable
9466 will execute the elaboration routines of the package and its closure,
9467 then the finalization routines.
9469 @end table
9471 @table @asis
9472 @item @command{gcc} @asis{switches}
9473 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9474 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9475 @end table
9477 @noindent
9478 Source and library search path switches:
9480 @table @option
9481 @c !sort!
9482 @item -aI@var{dir}
9483 @cindex @option{-aI} (@command{gnatmake})
9484 When looking for source files also look in directory @var{dir}.
9485 The order in which source files search is undertaken is
9486 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9488 @item -aL@var{dir}
9489 @cindex @option{-aL} (@command{gnatmake})
9490 Consider @var{dir} as being an externally provided Ada library.
9491 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9492 files have been located in directory @var{dir}. This allows you to have
9493 missing bodies for the units in @var{dir} and to ignore out of date bodies
9494 for the same units. You still need to specify
9495 the location of the specs for these units by using the switches
9496 @option{-aI@var{dir}}
9497 or @option{-I@var{dir}}.
9498 Note: this switch is provided for compatibility with previous versions
9499 of @command{gnatmake}. The easier method of causing standard libraries
9500 to be excluded from consideration is to write-protect the corresponding
9501 ALI files.
9503 @item -aO@var{dir}
9504 @cindex @option{-aO} (@command{gnatmake})
9505 When searching for library and object files, look in directory
9506 @var{dir}. The order in which library files are searched is described in
9507 @ref{Search Paths for gnatbind}.
9509 @item -A@var{dir}
9510 @cindex Search paths, for @command{gnatmake}
9511 @cindex @option{-A} (@command{gnatmake})
9512 Equivalent to @option{-aL@var{dir}
9513 -aI@var{dir}}.
9515 @item -I@var{dir}
9516 @cindex @option{-I} (@command{gnatmake})
9517 Equivalent to @option{-aO@var{dir}
9518 -aI@var{dir}}.
9520 @item -I-
9521 @cindex @option{-I-} (@command{gnatmake})
9522 @cindex Source files, suppressing search
9523 Do not look for source files in the directory containing the source
9524 file named in the command line.
9525 Do not look for ALI or object files in the directory
9526 where @command{gnatmake} was invoked.
9528 @item -L@var{dir}
9529 @cindex @option{-L} (@command{gnatmake})
9530 @cindex Linker libraries
9531 Add directory @var{dir} to the list of directories in which the linker
9532 will search for libraries. This is equivalent to
9533 @option{-largs -L}@var{dir}.
9534 Furthermore, under Windows, the sources pointed to by the libraries path
9535 set in the registry are not searched for.
9537 @item -nostdinc
9538 @cindex @option{-nostdinc} (@command{gnatmake})
9539 Do not look for source files in the system default directory.
9541 @item -nostdlib
9542 @cindex @option{-nostdlib} (@command{gnatmake})
9543 Do not look for library files in the system default directory.
9545 @item --RTS=@var{rts-path}
9546 @cindex @option{--RTS} (@command{gnatmake})
9547 Specifies the default location of the runtime library. GNAT looks for the
9548 runtime
9549 in the following directories, and stops as soon as a valid runtime is found
9550 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9551 @file{ada_object_path} present):
9553 @itemize @bullet
9554 @item <current directory>/$rts_path
9556 @item <default-search-dir>/$rts_path
9558 @item <default-search-dir>/rts-$rts_path
9559 @end itemize
9561 @noindent
9562 The selected path is handled like a normal RTS path.
9564 @end table
9566 @node Mode Switches for gnatmake
9567 @section Mode Switches for @command{gnatmake}
9569 @noindent
9570 The mode switches (referred to as @code{mode_switches}) allow the
9571 inclusion of switches that are to be passed to the compiler itself, the
9572 binder or the linker. The effect of a mode switch is to cause all
9573 subsequent switches up to the end of the switch list, or up to the next
9574 mode switch, to be interpreted as switches to be passed on to the
9575 designated component of GNAT.
9577 @table @option
9578 @c !sort!
9579 @item -cargs @var{switches}
9580 @cindex @option{-cargs} (@command{gnatmake})
9581 Compiler switches. Here @var{switches} is a list of switches
9582 that are valid switches for @command{gcc}. They will be passed on to
9583 all compile steps performed by @command{gnatmake}.
9585 @item -bargs @var{switches}
9586 @cindex @option{-bargs} (@command{gnatmake})
9587 Binder switches. Here @var{switches} is a list of switches
9588 that are valid switches for @code{gnatbind}. They will be passed on to
9589 all bind steps performed by @command{gnatmake}.
9591 @item -largs @var{switches}
9592 @cindex @option{-largs} (@command{gnatmake})
9593 Linker switches. Here @var{switches} is a list of switches
9594 that are valid switches for @command{gnatlink}. They will be passed on to
9595 all link steps performed by @command{gnatmake}.
9597 @item -margs @var{switches}
9598 @cindex @option{-margs} (@command{gnatmake})
9599 Make switches. The switches are directly interpreted by @command{gnatmake},
9600 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9601 or @option{-largs}.
9602 @end table
9604 @node Notes on the Command Line
9605 @section Notes on the Command Line
9607 @noindent
9608 This section contains some additional useful notes on the operation
9609 of the @command{gnatmake} command.
9611 @itemize @bullet
9612 @item
9613 @cindex Recompilation, by @command{gnatmake}
9614 If @command{gnatmake} finds no ALI files, it recompiles the main program
9615 and all other units required by the main program.
9616 This means that @command{gnatmake}
9617 can be used for the initial compile, as well as during subsequent steps of
9618 the development cycle.
9620 @item
9621 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9622 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9623 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9624 warning.
9626 @item
9627 In @command{gnatmake} the switch @option{-I}
9628 is used to specify both source and
9629 library file paths. Use @option{-aI}
9630 instead if you just want to specify
9631 source paths only and @option{-aO}
9632 if you want to specify library paths
9633 only.
9635 @item
9636 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9637 This may conveniently be used to exclude standard libraries from
9638 consideration and in particular it means that the use of the
9639 @option{-f} switch will not recompile these files
9640 unless @option{-a} is also specified.
9642 @item
9643 @command{gnatmake} has been designed to make the use of Ada libraries
9644 particularly convenient. Assume you have an Ada library organized
9645 as follows: @i{obj-dir} contains the objects and ALI files for
9646 of your Ada compilation units,
9647 whereas @i{include-dir} contains the
9648 specs of these units, but no bodies. Then to compile a unit
9649 stored in @code{main.adb}, which uses this Ada library you would just type
9651 @smallexample
9652 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9653 @end smallexample
9655 @item
9656 Using @command{gnatmake} along with the
9657 @option{-m (minimal recompilation)}
9658 switch provides a mechanism for avoiding unnecessary recompilations. Using
9659 this switch,
9660 you can update the comments/format of your
9661 source files without having to recompile everything. Note, however, that
9662 adding or deleting lines in a source files may render its debugging
9663 info obsolete. If the file in question is a spec, the impact is rather
9664 limited, as that debugging info will only be useful during the
9665 elaboration phase of your program. For bodies the impact can be more
9666 significant. In all events, your debugger will warn you if a source file
9667 is more recent than the corresponding object, and alert you to the fact
9668 that the debugging information may be out of date.
9669 @end itemize
9671 @node How gnatmake Works
9672 @section How @command{gnatmake} Works
9674 @noindent
9675 Generally @command{gnatmake} automatically performs all necessary
9676 recompilations and you don't need to worry about how it works. However,
9677 it may be useful to have some basic understanding of the @command{gnatmake}
9678 approach and in particular to understand how it uses the results of
9679 previous compilations without incorrectly depending on them.
9681 First a definition: an object file is considered @dfn{up to date} if the
9682 corresponding ALI file exists and if all the source files listed in the
9683 dependency section of this ALI file have time stamps matching those in
9684 the ALI file. This means that neither the source file itself nor any
9685 files that it depends on have been modified, and hence there is no need
9686 to recompile this file.
9688 @command{gnatmake} works by first checking if the specified main unit is up
9689 to date. If so, no compilations are required for the main unit. If not,
9690 @command{gnatmake} compiles the main program to build a new ALI file that
9691 reflects the latest sources. Then the ALI file of the main unit is
9692 examined to find all the source files on which the main program depends,
9693 and @command{gnatmake} recursively applies the above procedure on all these
9694 files.
9696 This process ensures that @command{gnatmake} only trusts the dependencies
9697 in an existing ALI file if they are known to be correct. Otherwise it
9698 always recompiles to determine a new, guaranteed accurate set of
9699 dependencies. As a result the program is compiled ``upside down'' from what may
9700 be more familiar as the required order of compilation in some other Ada
9701 systems. In particular, clients are compiled before the units on which
9702 they depend. The ability of GNAT to compile in any order is critical in
9703 allowing an order of compilation to be chosen that guarantees that
9704 @command{gnatmake} will recompute a correct set of new dependencies if
9705 necessary.
9707 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9708 imported by several of the executables, it will be recompiled at most once.
9710 Note: when using non-standard naming conventions
9711 (@pxref{Using Other File Names}), changing through a configuration pragmas
9712 file the version of a source and invoking @command{gnatmake} to recompile may
9713 have no effect, if the previous version of the source is still accessible
9714 by @command{gnatmake}. It may be necessary to use the switch
9717 @node Examples of gnatmake Usage
9718 @section Examples of @command{gnatmake} Usage
9720 @table @code
9721 @item gnatmake hello.adb
9722 Compile all files necessary to bind and link the main program
9723 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9724 resulting object files to generate an executable file @file{hello}.
9726 @item gnatmake main1 main2 main3
9727 Compile all files necessary to bind and link the main programs
9728 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9729 (containing unit @code{Main2}) and @file{main3.adb}
9730 (containing unit @code{Main3}) and bind and link the resulting object files
9731 to generate three executable files @file{main1},
9732 @file{main2}
9733 and @file{main3}.
9735 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9737 Compile all files necessary to bind and link the main program unit
9738 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9739 be done with optimization level 2 and the order of elaboration will be
9740 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9741 displaying commands it is executing.
9742 @end table
9744 @c *************************
9745 @node Improving Performance
9746 @chapter Improving Performance
9747 @cindex Improving performance
9749 @noindent
9750 This chapter presents several topics related to program performance.
9751 It first describes some of the tradeoffs that need to be considered
9752 and some of the techniques for making your program run faster.
9753 It then documents
9754 @ifclear FSFEDITION
9755 the @command{gnatelim} tool and
9756 @end ifclear
9757 unused subprogram/data
9758 elimination feature, which can reduce the size of program executables.
9760 @ifnottex
9761 @menu
9762 * Performance Considerations::
9763 * Text_IO Suggestions::
9764 @ifclear FSFEDITION
9765 * Reducing Size of Ada Executables with gnatelim::
9766 @end ifclear
9767 * Reducing Size of Executables with unused subprogram/data elimination::
9768 @end menu
9769 @end ifnottex
9771 @c *****************************
9772 @node Performance Considerations
9773 @section Performance Considerations
9775 @noindent
9776 The GNAT system provides a number of options that allow a trade-off
9777 between
9779 @itemize @bullet
9780 @item
9781 performance of the generated code
9783 @item
9784 speed of compilation
9786 @item
9787 minimization of dependences and recompilation
9789 @item
9790 the degree of run-time checking.
9791 @end itemize
9793 @noindent
9794 The defaults (if no options are selected) aim at improving the speed
9795 of compilation and minimizing dependences, at the expense of performance
9796 of the generated code:
9798 @itemize @bullet
9799 @item
9800 no optimization
9802 @item
9803 no inlining of subprogram calls
9805 @item
9806 all run-time checks enabled except overflow and elaboration checks
9807 @end itemize
9809 @noindent
9810 These options are suitable for most program development purposes. This
9811 chapter describes how you can modify these choices, and also provides
9812 some guidelines on debugging optimized code.
9814 @menu
9815 * Controlling Run-Time Checks::
9816 * Use of Restrictions::
9817 * Optimization Levels::
9818 * Debugging Optimized Code::
9819 * Inlining of Subprograms::
9820 * Vectorization of loops::
9821 * Other Optimization Switches::
9822 * Optimization and Strict Aliasing::
9823 * Aliased Variables and Optimization::
9824 * Atomic Variables and Optimization::
9825 * Passive Task Optimization::
9827 @end menu
9829 @node Controlling Run-Time Checks
9830 @subsection Controlling Run-Time Checks
9832 @noindent
9833 By default, GNAT generates all run-time checks, except integer overflow
9834 checks, stack overflow checks, and checks for access before elaboration on
9835 subprogram calls. The latter are not required in default mode, because all
9836 necessary checking is done at compile time.
9837 @cindex @option{-gnatp} (@command{gcc})
9838 @cindex @option{-gnato} (@command{gcc})
9839 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9840 be modified. @xref{Run-Time Checks}.
9842 Our experience is that the default is suitable for most development
9843 purposes.
9845 We treat integer overflow specially because these
9846 are quite expensive and in our experience are not as important as other
9847 run-time checks in the development process. Note that division by zero
9848 is not considered an overflow check, and divide by zero checks are
9849 generated where required by default.
9851 Elaboration checks are off by default, and also not needed by default, since
9852 GNAT uses a static elaboration analysis approach that avoids the need for
9853 run-time checking. This manual contains a full chapter discussing the issue
9854 of elaboration checks, and if the default is not satisfactory for your use,
9855 you should read this chapter.
9857 For validity checks, the minimal checks required by the Ada Reference
9858 Manual (for case statements and assignments to array elements) are on
9859 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9860 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9861 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9862 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9863 are also suppressed entirely if @option{-gnatp} is used.
9865 @cindex Overflow checks
9866 @cindex Checks, overflow
9867 @findex Suppress
9868 @findex Unsuppress
9869 @cindex pragma Suppress
9870 @cindex pragma Unsuppress
9871 Note that the setting of the switches controls the default setting of
9872 the checks. They may be modified using either @code{pragma Suppress} (to
9873 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9874 checks) in the program source.
9876 @node Use of Restrictions
9877 @subsection Use of Restrictions
9879 @noindent
9880 The use of pragma Restrictions allows you to control which features are
9881 permitted in your program. Apart from the obvious point that if you avoid
9882 relatively expensive features like finalization (enforceable by the use
9883 of pragma Restrictions (No_Finalization), the use of this pragma does not
9884 affect the generated code in most cases.
9886 One notable exception to this rule is that the possibility of task abort
9887 results in some distributed overhead, particularly if finalization or
9888 exception handlers are used. The reason is that certain sections of code
9889 have to be marked as non-abortable.
9891 If you use neither the @code{abort} statement, nor asynchronous transfer
9892 of control (@code{select @dots{} then abort}), then this distributed overhead
9893 is removed, which may have a general positive effect in improving
9894 overall performance.  Especially code involving frequent use of tasking
9895 constructs and controlled types will show much improved performance.
9896 The relevant restrictions pragmas are
9898 @smallexample @c ada
9899    @b{pragma} Restrictions (No_Abort_Statements);
9900    @b{pragma} Restrictions (Max_Asynchronous_Select_Nesting => 0);
9901 @end smallexample
9903 @noindent
9904 It is recommended that these restriction pragmas be used if possible. Note
9905 that this also means that you can write code without worrying about the
9906 possibility of an immediate abort at any point.
9908 @node Optimization Levels
9909 @subsection Optimization Levels
9910 @cindex @option{-O} (@command{gcc})
9912 @noindent
9913 Without any optimization option,
9914 the compiler's goal is to reduce the cost of
9915 compilation and to make debugging produce the expected results.
9916 Statements are independent: if you stop the program with a breakpoint between
9917 statements, you can then assign a new value to any variable or change
9918 the program counter to any other statement in the subprogram and get exactly
9919 the results you would expect from the source code.
9921 Turning on optimization makes the compiler attempt to improve the
9922 performance and/or code size at the expense of compilation time and
9923 possibly the ability to debug the program.
9925 If you use multiple
9926 -O options, with or without level numbers,
9927 the last such option is the one that is effective.
9929 @noindent
9930 The default is optimization off. This results in the fastest compile
9931 times, but GNAT makes absolutely no attempt to optimize, and the
9932 generated programs are considerably larger and slower than when
9933 optimization is enabled. You can use the
9934 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9935 @option{-O2}, @option{-O3}, and @option{-Os})
9936 to @command{gcc} to control the optimization level:
9938 @table @option
9939 @item -O0
9940 No optimization (the default);
9941 generates unoptimized code but has
9942 the fastest compilation time.
9944 Note that many other compilers do fairly extensive optimization
9945 even if ``no optimization'' is specified. With gcc, it is
9946 very unusual to use -O0 for production if
9947 execution time is of any concern, since -O0
9948 really does mean no optimization at all. This difference between
9949 gcc and other compilers should be kept in mind when doing
9950 performance comparisons.
9952 @item -O1
9953 Moderate optimization;
9954 optimizes reasonably well but does not
9955 degrade compilation time significantly.
9957 @item -O2
9958 Full optimization;
9959 generates highly optimized code and has
9960 the slowest compilation time.
9962 @item -O3
9963 Full optimization as in @option{-O2};
9964 also uses more aggressive automatic inlining of subprograms within a unit
9965 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
9967 @item -Os
9968 Optimize space usage (code and data) of resulting program.
9969 @end table
9971 @noindent
9972 Higher optimization levels perform more global transformations on the
9973 program and apply more expensive analysis algorithms in order to generate
9974 faster and more compact code. The price in compilation time, and the
9975 resulting improvement in execution time,
9976 both depend on the particular application and the hardware environment.
9977 You should experiment to find the best level for your application.
9979 Since the precise set of optimizations done at each level will vary from
9980 release to release (and sometime from target to target), it is best to think
9981 of the optimization settings in general terms.
9982 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
9983 the GNU Compiler Collection (GCC)}, for details about
9984 the @option{-O} settings and a number of @option{-f} options that
9985 individually enable or disable specific optimizations.
9987 Unlike some other compilation systems, @command{gcc} has
9988 been tested extensively at all optimization levels. There are some bugs
9989 which appear only with optimization turned on, but there have also been
9990 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9991 level of optimization does not improve the reliability of the code
9992 generator, which in practice is highly reliable at all optimization
9993 levels.
9995 Note regarding the use of @option{-O3}: The use of this optimization level
9996 is generally discouraged with GNAT, since it often results in larger
9997 executables which may run more slowly. See further discussion of this point
9998 in @ref{Inlining of Subprograms}.
10000 @node Debugging Optimized Code
10001 @subsection Debugging Optimized Code
10002 @cindex Debugging optimized code
10003 @cindex Optimization and debugging
10005 @noindent
10006 Although it is possible to do a reasonable amount of debugging at
10007 nonzero optimization levels,
10008 the higher the level the more likely that
10009 source-level constructs will have been eliminated by optimization.
10010 For example, if a loop is strength-reduced, the loop
10011 control variable may be completely eliminated and thus cannot be
10012 displayed in the debugger.
10013 This can only happen at @option{-O2} or @option{-O3}.
10014 Explicit temporary variables that you code might be eliminated at
10015 level @option{-O1} or higher.
10017 The use of the @option{-g} switch,
10018 @cindex @option{-g} (@command{gcc})
10019 which is needed for source-level debugging,
10020 affects the size of the program executable on disk,
10021 and indeed the debugging information can be quite large.
10022 However, it has no effect on the generated code (and thus does not
10023 degrade performance)
10025 Since the compiler generates debugging tables for a compilation unit before
10026 it performs optimizations, the optimizing transformations may invalidate some
10027 of the debugging data.  You therefore need to anticipate certain
10028 anomalous situations that may arise while debugging optimized code.
10029 These are the most common cases:
10031 @enumerate
10032 @item
10033 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10034 commands show
10035 the PC bouncing back and forth in the code.  This may result from any of
10036 the following optimizations:
10038 @itemize @bullet
10039 @item
10040 @i{Common subexpression elimination:} using a single instance of code for a
10041 quantity that the source computes several times.  As a result you
10042 may not be able to stop on what looks like a statement.
10044 @item
10045 @i{Invariant code motion:} moving an expression that does not change within a
10046 loop, to the beginning of the loop.
10048 @item
10049 @i{Instruction scheduling:} moving instructions so as to
10050 overlap loads and stores (typically) with other code, or in
10051 general to move computations of values closer to their uses. Often
10052 this causes you to pass an assignment statement without the assignment
10053 happening and then later bounce back to the statement when the
10054 value is actually needed.  Placing a breakpoint on a line of code
10055 and then stepping over it may, therefore, not always cause all the
10056 expected side-effects.
10057 @end itemize
10059 @item
10060 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10061 two identical pieces of code are merged and the program counter suddenly
10062 jumps to a statement that is not supposed to be executed, simply because
10063 it (and the code following) translates to the same thing as the code
10064 that @emph{was} supposed to be executed.  This effect is typically seen in
10065 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10066 a @code{break} in a C @code{switch} statement.
10068 @item
10069 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10070 There are various reasons for this effect:
10072 @itemize @bullet
10073 @item
10074 In a subprogram prologue, a parameter may not yet have been moved to its
10075 ``home''.
10077 @item
10078 A variable may be dead, and its register re-used.  This is
10079 probably the most common cause.
10081 @item
10082 As mentioned above, the assignment of a value to a variable may
10083 have been moved.
10085 @item
10086 A variable may be eliminated entirely by value propagation or
10087 other means.  In this case, GCC may incorrectly generate debugging
10088 information for the variable
10089 @end itemize
10091 @noindent
10092 In general, when an unexpected value appears for a local variable or parameter
10093 you should first ascertain if that value was actually computed by
10094 your program, as opposed to being incorrectly reported by the debugger.
10095 Record fields or
10096 array elements in an object designated by an access value
10097 are generally less of a problem, once you have ascertained that the access
10098 value is sensible.
10099 Typically, this means checking variables in the preceding code and in the
10100 calling subprogram to verify that the value observed is explainable from other
10101 values (one must apply the procedure recursively to those
10102 other values); or re-running the code and stopping a little earlier
10103 (perhaps before the call) and stepping to better see how the variable obtained
10104 the value in question; or continuing to step @emph{from} the point of the
10105 strange value to see if code motion had simply moved the variable's
10106 assignments later.
10107 @end enumerate
10109 @noindent
10110 In light of such anomalies, a recommended technique is to use @option{-O0}
10111 early in the software development cycle, when extensive debugging capabilities
10112 are most needed, and then move to @option{-O1} and later @option{-O2} as
10113 the debugger becomes less critical.
10114 Whether to use the @option{-g} switch in the release version is
10115 a release management issue.
10116 Note that if you use @option{-g} you can then use the @command{strip} program
10117 on the resulting executable,
10118 which removes both debugging information and global symbols.
10120 @node Inlining of Subprograms
10121 @subsection Inlining of Subprograms
10123 @noindent
10124 A call to a subprogram in the current unit is inlined if all the
10125 following conditions are met:
10127 @itemize @bullet
10128 @item
10129 The optimization level is at least @option{-O1}.
10131 @item
10132 The called subprogram is suitable for inlining: It must be small enough
10133 and not contain something that @command{gcc} cannot support in inlined
10134 subprograms.
10136 @item
10137 @cindex pragma Inline
10138 @findex Inline
10139 Any one of the following applies: @code{pragma Inline} is applied to the
10140 subprogram and the @option{-gnatn} switch is specified; the
10141 subprogram is local to the unit and called once from within it; the
10142 subprogram is small and optimization level @option{-O2} is specified;
10143 optimization level @option{-O3} is specified.
10144 @end itemize
10146 @noindent
10147 Calls to subprograms in @code{with}'ed units are normally not inlined.
10148 To achieve actual inlining (that is, replacement of the call by the code
10149 in the body of the subprogram), the following conditions must all be true:
10151 @itemize @bullet
10152 @item
10153 The optimization level is at least @option{-O1}.
10155 @item
10156 The called subprogram is suitable for inlining: It must be small enough
10157 and not contain something that @command{gcc} cannot support in inlined
10158 subprograms.
10160 @item
10161 The call appears in a body (not in a package spec).
10163 @item
10164 There is a @code{pragma Inline} for the subprogram.
10166 @item
10167 The @option{-gnatn} switch is used on the command line.
10168 @end itemize
10170 Even if all these conditions are met, it may not be possible for
10171 the compiler to inline the call, due to the length of the body,
10172 or features in the body that make it impossible for the compiler
10173 to do the inlining.
10175 Note that specifying the @option{-gnatn} switch causes additional
10176 compilation dependencies. Consider the following:
10178 @smallexample @c ada
10179 @cartouche
10180 @b{package} R @b{is}
10181    @b{procedure} Q;
10182    @b{pragma} Inline (Q);
10183 @b{end} R;
10184 @b{package} @b{body} R @b{is}
10185    @dots{}
10186 @b{end} R;
10188 @b{with} R;
10189 @b{procedure} Main @b{is}
10190 @b{begin}
10191    @dots{}
10192    R.Q;
10193 @b{end} Main;
10194 @end cartouche
10195 @end smallexample
10197 @noindent
10198 With the default behavior (no @option{-gnatn} switch specified), the
10199 compilation of the @code{Main} procedure depends only on its own source,
10200 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10201 means that editing the body of @code{R} does not require recompiling
10202 @code{Main}.
10204 On the other hand, the call @code{R.Q} is not inlined under these
10205 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10206 is compiled, the call will be inlined if the body of @code{Q} is small
10207 enough, but now @code{Main} depends on the body of @code{R} in
10208 @file{r.adb} as well as on the spec. This means that if this body is edited,
10209 the main program must be recompiled. Note that this extra dependency
10210 occurs whether or not the call is in fact inlined by @command{gcc}.
10212 The use of front end inlining with @option{-gnatN} generates similar
10213 additional dependencies.
10215 @cindex @option{-fno-inline} (@command{gcc})
10216 Note: The @option{-fno-inline} switch
10217 can be used to prevent
10218 all inlining. This switch overrides all other conditions and ensures
10219 that no inlining occurs. The extra dependences resulting from
10220 @option{-gnatn} will still be active, even if
10221 this switch is used to suppress the resulting inlining actions.
10223 @cindex @option{-fno-inline-functions} (@command{gcc})
10224 Note: The @option{-fno-inline-functions} switch can be used to prevent
10225 automatic inlining of subprograms if @option{-O3} is used.
10227 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10228 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10229 automatic inlining of small subprograms if @option{-O2} is used.
10231 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10232 Note: The @option{-fno-inline-functions-called-once} switch
10233 can be used to prevent inlining of subprograms local to the unit
10234 and called once from within it if @option{-O1} is used.
10236 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10237 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10238 specified in lieu of it, @option{-gnatn} being translated into one of them
10239 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10240 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10241 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10242 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10243 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
10244 effect of inlining subprograms you did not think should be inlined. We have
10245 found that the use of @option{-O3} may slow down the compilation and increase
10246 the code size by performing excessive inlining, leading to increased
10247 instruction cache pressure from the increased code size and thus minor
10248 performance improvements. So the bottom line here is that you should not
10249 automatically assume that @option{-O3} is better than @option{-O2}, and
10250 indeed you should use @option{-O3} only if tests show that it actually
10251 improves performance for your program.
10253 @node Vectorization of loops
10254 @subsection Vectorization of loops
10255 @cindex Optimization Switches
10257 You can take advantage of the auto-vectorizer present in the @command{gcc}
10258 back end to vectorize loops with GNAT.  The corresponding command line switch
10259 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10260 and other aggressive optimizations helpful for vectorization also are enabled
10261 by default at this level, using @option{-O3} directly is recommended.
10263 You also need to make sure that the target architecture features a supported
10264 SIMD instruction set.  For example, for the x86 architecture, you should at
10265 least specify @option{-msse2} to get significant vectorization (but you don't
10266 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10267 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10269 The preferred loop form for vectorization is the @code{for} iteration scheme.
10270 Loops with a @code{while} iteration scheme can also be vectorized if they are
10271 very simple, but the vectorizer will quickly give up otherwise.  With either
10272 iteration scheme, the flow of control must be straight, in particular no
10273 @code{exit} statement may appear in the loop body.  The loop may however
10274 contain a single nested loop, if it can be vectorized when considered alone:
10276 @smallexample @c ada
10277 @cartouche
10278    A : @b{array} (1..4, 1..4) @b{of} Long_Float;
10279    S : @b{array} (1..4) @b{of} Long_Float;
10281    @b{procedure} Sum @b{is}
10282    @b{begin}
10283       @b{for} I @b{in} A'Range(1) @b{loop}
10284          @b{for} J @b{in} A'Range(2) @b{loop}
10285             S (I) := S (I) + A (I, J);
10286          @b{end} @b{loop};
10287       @b{end} @b{loop};
10288    @b{end} Sum;
10289 @end cartouche
10290 @end smallexample
10292 The vectorizable operations depend on the targeted SIMD instruction set, but
10293 the adding and some of the multiplying operators are generally supported, as
10294 well as the logical operators for modular types.  Note that, in the former
10295 case, enabling overflow checks, for example with @option{-gnato}, totally
10296 disables vectorization.  The other checks are not supposed to have the same
10297 definitive effect, although compiling with @option{-gnatp} might well reveal
10298 cases where some checks do thwart vectorization.
10300 Type conversions may also prevent vectorization if they involve semantics that
10301 are not directly supported by the code generator or the SIMD instruction set.
10302 A typical example is direct conversion from floating-point to integer types.
10303 The solution in this case is to use the following idiom:
10305 @smallexample @c ada
10306    Integer (S'Truncation (F))
10307 @end smallexample
10309 @noindent
10310 if @code{S} is the subtype of floating-point object @code{F}.
10312 In most cases, the vectorizable loops are loops that iterate over arrays.
10313 All kinds of array types are supported, i.e. constrained array types with
10314 static bounds:
10316 @smallexample @c ada
10317    @b{type} Array_Type @b{is} @b{array} (1 .. 4) @b{of} Long_Float;
10318 @end smallexample
10320 @noindent
10321 constrained array types with dynamic bounds:
10323 @smallexample @c ada
10324    @b{type} Array_Type @b{is} @b{array} (1 .. Q.N) @b{of} Long_Float;
10326    @b{type} Array_Type @b{is} @b{array} (Q.K .. 4) @b{of} Long_Float;
10328    @b{type} Array_Type @b{is} @b{array} (Q.K .. Q.N) @b{of} Long_Float;
10329 @end smallexample
10331 @noindent
10332 or unconstrained array types:
10334 @smallexample @c ada
10335   @b{type} Array_Type @b{is} @b{array} (Positive @b{range} <>) @b{of} Long_Float;
10336 @end smallexample
10338 @noindent
10339 The quality of the generated code decreases when the dynamic aspect of the
10340 array type increases, the worst code being generated for unconstrained array
10341 types.  This is so because, the less information the compiler has about the
10342 bounds of the array, the more fallback code it needs to generate in order to
10343 fix things up at run time.
10345 It is possible to specify that a given loop should be subject to vectorization
10346 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10348 @smallexample @c ada
10349   @b{pragma} Loop_Optimize (Vector);
10350 @end smallexample
10352 @noindent
10353 placed immediately within the loop will convey the appropriate hint to the
10354 compiler for this loop.
10356 It is also possible to help the compiler generate better vectorized code
10357 for a given loop by asserting that there are no loop-carried dependencies
10358 in the loop.  Consider for example the procedure:
10360 @smallexample @c ada
10361   @b{type} Arr @b{is} @b{array} (1 .. 4) @b{of} Long_Float;
10363   @b{procedure} Add (X, Y : @b{not} @b{null} @b{access} Arr; R : @b{not} @b{null} @b{access} Arr) @b{is}
10364   @b{begin}
10365     @b{for} I @b{in} Arr'Range @b{loop}
10366       R(I) := X(I) + Y(I);
10367     @b{end} @b{loop};
10368   @b{end};
10369 @end smallexample
10371 @noindent
10372 By default, the compiler cannot unconditionally vectorize the loop because
10373 assigning to a component of the array designated by R in one iteration could
10374 change the value read from the components of the array designated by X or Y
10375 in a later iteration.  As a result, the compiler will generate two versions
10376 of the loop in the object code, one vectorized and the other not vectorized,
10377 as well as a test to select the appropriate version at run time.  This can
10378 be overcome by another hint:
10380 @smallexample @c ada
10381   @b{pragma} Loop_Optimize (Ivdep);
10382 @end smallexample
10384 @noindent
10385 placed immediately within the loop will tell the compiler that it can safely
10386 omit the non-vectorized version of the loop as well as the run-time test.
10388 @node Other Optimization Switches
10389 @subsection Other Optimization Switches
10390 @cindex Optimization Switches
10392 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10393 @command{gcc} optimization switches are potentially usable. These switches
10394 have not been extensively tested with GNAT but can generally be expected
10395 to work. Examples of switches in this category are @option{-funroll-loops}
10396 and the various target-specific @option{-m} options (in particular, it has
10397 been observed that @option{-march=xxx} can significantly improve performance
10398 on appropriate machines). For full details of these switches, see
10399 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10400 the GNU Compiler Collection (GCC)}.
10402 @node Optimization and Strict Aliasing
10403 @subsection Optimization and Strict Aliasing
10404 @cindex Aliasing
10405 @cindex Strict Aliasing
10406 @cindex No_Strict_Aliasing
10408 @noindent
10409 The strong typing capabilities of Ada allow an optimizer to generate
10410 efficient code in situations where other languages would be forced to
10411 make worst case assumptions preventing such optimizations. Consider
10412 the following example:
10414 @smallexample @c ada
10415 @cartouche
10416 @b{procedure} R @b{is}
10417    @b{type} Int1 @b{is} @b{new} Integer;
10418    @b{type} Int2 @b{is} @b{new} Integer;
10419    @b{type} Int1A @b{is} @b{access} Int1;
10420    @b{type} Int2A @b{is} @b{access} Int2;
10421    Int1V : Int1A;
10422    Int2V : Int2A;
10423    @dots{}
10425 @b{begin}
10426    @dots{}
10427    @b{for} J @b{in} Data'Range @b{loop}
10428       @b{if} Data (J) = Int1V.@b{all} @b{then}
10429          Int2V.@b{all} := Int2V.@b{all} + 1;
10430       @b{end} @b{if};
10431    @b{end} @b{loop};
10432    @dots{}
10433 @b{end} R;
10434 @end cartouche
10435 @end smallexample
10437 @noindent
10438 In this example, since the variable @code{Int1V} can only access objects
10439 of type @code{Int1}, and @code{Int2V} can only access objects of type
10440 @code{Int2}, there is no possibility that the assignment to
10441 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10442 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10443 for all iterations of the loop and avoid the extra memory reference
10444 required to dereference it each time through the loop.
10446 This kind of optimization, called strict aliasing analysis, is
10447 triggered by specifying an optimization level of @option{-O2} or
10448 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10449 when access values are involved.
10451 However, although this optimization is always correct in terms of
10452 the formal semantics of the Ada Reference Manual, difficulties can
10453 arise if features like @code{Unchecked_Conversion} are used to break
10454 the typing system. Consider the following complete program example:
10456 @smallexample @c ada
10457 @cartouche
10458 @b{package} p1 @b{is}
10459    @b{type} int1 @b{is} @b{new} integer;
10460    @b{type} int2 @b{is} @b{new} integer;
10461    @b{type} a1 @b{is} @b{access} int1;
10462    @b{type} a2 @b{is} @b{access} int2;
10463 @b{end} p1;
10465 @b{with} p1; @b{use} p1;
10466 @b{package} p2 @b{is}
10467    @b{function} to_a2 (Input : a1) @b{return} a2;
10468 @b{end} p2;
10470 @b{with} Unchecked_Conversion;
10471 @b{package} @b{body} p2 @b{is}
10472    @b{function} to_a2 (Input : a1) @b{return} a2 @b{is}
10473       @b{function} to_a2u @b{is}
10474         @b{new} Unchecked_Conversion (a1, a2);
10475    @b{begin}
10476       @b{return} to_a2u (Input);
10477    @b{end} to_a2;
10478 @b{end} p2;
10480 @b{with} p2; @b{use} p2;
10481 @b{with} p1; @b{use} p1;
10482 @b{with} Text_IO; @b{use} Text_IO;
10483 @b{procedure} m @b{is}
10484    v1 : a1 := @b{new} int1;
10485    v2 : a2 := to_a2 (v1);
10486 @b{begin}
10487    v1.@b{all} := 1;
10488    v2.@b{all} := 0;
10489    put_line (int1'image (v1.@b{all}));
10490 @b{end};
10491 @end cartouche
10492 @end smallexample
10494 @noindent
10495 This program prints out 0 in @option{-O0} or @option{-O1}
10496 mode, but it prints out 1 in @option{-O2} mode. That's
10497 because in strict aliasing mode, the compiler can and
10498 does assume that the assignment to @code{v2.all} could not
10499 affect the value of @code{v1.all}, since different types
10500 are involved.
10502 This behavior is not a case of non-conformance with the standard, since
10503 the Ada RM specifies that an unchecked conversion where the resulting
10504 bit pattern is not a correct value of the target type can result in an
10505 abnormal value and attempting to reference an abnormal value makes the
10506 execution of a program erroneous.  That's the case here since the result
10507 does not point to an object of type @code{int2}.  This means that the
10508 effect is entirely unpredictable.
10510 However, although that explanation may satisfy a language
10511 lawyer, in practice an applications programmer expects an
10512 unchecked conversion involving pointers to create true
10513 aliases and the behavior of printing 1 seems plain wrong.
10514 In this case, the strict aliasing optimization is unwelcome.
10516 Indeed the compiler recognizes this possibility, and the
10517 unchecked conversion generates a warning:
10519 @smallexample
10520 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10521 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10522 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10523 @end smallexample
10525 @noindent
10526 Unfortunately the problem is recognized when compiling the body of
10527 package @code{p2}, but the actual "bad" code is generated while
10528 compiling the body of @code{m} and this latter compilation does not see
10529 the suspicious @code{Unchecked_Conversion}.
10531 As implied by the warning message, there are approaches you can use to
10532 avoid the unwanted strict aliasing optimization in a case like this.
10534 One possibility is to simply avoid the use of @option{-O2}, but
10535 that is a bit drastic, since it throws away a number of useful
10536 optimizations that do not involve strict aliasing assumptions.
10538 A less drastic approach is to compile the program using the
10539 option @option{-fno-strict-aliasing}. Actually it is only the
10540 unit containing the dereferencing of the suspicious pointer
10541 that needs to be compiled. So in this case, if we compile
10542 unit @code{m} with this switch, then we get the expected
10543 value of zero printed. Analyzing which units might need
10544 the switch can be painful, so a more reasonable approach
10545 is to compile the entire program with options @option{-O2}
10546 and @option{-fno-strict-aliasing}. If the performance is
10547 satisfactory with this combination of options, then the
10548 advantage is that the entire issue of possible "wrong"
10549 optimization due to strict aliasing is avoided.
10551 To avoid the use of compiler switches, the configuration
10552 pragma @code{No_Strict_Aliasing} with no parameters may be
10553 used to specify that for all access types, the strict
10554 aliasing optimization should be suppressed.
10556 However, these approaches are still overkill, in that they causes
10557 all manipulations of all access values to be deoptimized. A more
10558 refined approach is to concentrate attention on the specific
10559 access type identified as problematic.
10561 First, if a careful analysis of uses of the pointer shows
10562 that there are no possible problematic references, then
10563 the warning can be suppressed by bracketing the
10564 instantiation of @code{Unchecked_Conversion} to turn
10565 the warning off:
10567 @smallexample @c ada
10568    @b{pragma} Warnings (Off);
10569    @b{function} to_a2u @b{is}
10570      @b{new} Unchecked_Conversion (a1, a2);
10571    @b{pragma} Warnings (On);
10572 @end smallexample
10574 @noindent
10575 Of course that approach is not appropriate for this particular
10576 example, since indeed there is a problematic reference. In this
10577 case we can take one of two other approaches.
10579 The first possibility is to move the instantiation of unchecked
10580 conversion to the unit in which the type is declared. In
10581 this example, we would move the instantiation of
10582 @code{Unchecked_Conversion} from the body of package
10583 @code{p2} to the spec of package @code{p1}. Now the
10584 warning disappears. That's because any use of the
10585 access type knows there is a suspicious unchecked
10586 conversion, and the strict aliasing optimization
10587 is automatically suppressed for the type.
10589 If it is not practical to move the unchecked conversion to the same unit
10590 in which the destination access type is declared (perhaps because the
10591 source type is not visible in that unit), you may use pragma
10592 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10593 same declarative sequence as the declaration of the access type:
10595 @smallexample @c ada
10596    @b{type} a2 @b{is} @b{access} int2;
10597    @b{pragma} No_Strict_Aliasing (a2);
10598 @end smallexample
10600 @noindent
10601 Here again, the compiler now knows that the strict aliasing optimization
10602 should be suppressed for any reference to type @code{a2} and the
10603 expected behavior is obtained.
10605 Finally, note that although the compiler can generate warnings for
10606 simple cases of unchecked conversions, there are tricker and more
10607 indirect ways of creating type incorrect aliases which the compiler
10608 cannot detect. Examples are the use of address overlays and unchecked
10609 conversions involving composite types containing access types as
10610 components. In such cases, no warnings are generated, but there can
10611 still be aliasing problems. One safe coding practice is to forbid the
10612 use of address clauses for type overlaying, and to allow unchecked
10613 conversion only for primitive types. This is not really a significant
10614 restriction since any possible desired effect can be achieved by
10615 unchecked conversion of access values.
10617 The aliasing analysis done in strict aliasing mode can certainly
10618 have significant benefits. We have seen cases of large scale
10619 application code where the time is increased by up to 5% by turning
10620 this optimization off. If you have code that includes significant
10621 usage of unchecked conversion, you might want to just stick with
10622 @option{-O1} and avoid the entire issue. If you get adequate
10623 performance at this level of optimization level, that's probably
10624 the safest approach. If tests show that you really need higher
10625 levels of optimization, then you can experiment with @option{-O2}
10626 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10627 has on size and speed of the code. If you really need to use
10628 @option{-O2} with strict aliasing in effect, then you should
10629 review any uses of unchecked conversion of access types,
10630 particularly if you are getting the warnings described above.
10632 @node Aliased Variables and Optimization
10633 @subsection Aliased Variables and Optimization
10634 @cindex Aliasing
10635 There are scenarios in which programs may
10636 use low level techniques to modify variables
10637 that otherwise might be considered to be unassigned. For example,
10638 a variable can be passed to a procedure by reference, which takes
10639 the address of the parameter and uses the address to modify the
10640 variable's value, even though it is passed as an IN parameter.
10641 Consider the following example:
10643 @smallexample @c ada
10644 @b{procedure} P @b{is}
10645    Max_Length : @b{constant} Natural := 16;
10646    @b{type} Char_Ptr @b{is} @b{access} @b{all} Character;
10648    @b{procedure} Get_String(Buffer: Char_Ptr; Size : Integer);
10649    @b{pragma} Import (C, Get_String, "get_string");
10651    Name : @b{aliased} String (1 .. Max_Length) := (@b{others} => ' ');
10652    Temp : Char_Ptr;
10654    @b{function} Addr (S : String) @b{return} Char_Ptr @b{is}
10655       @b{function} To_Char_Ptr @b{is}
10656         @b{new} Ada.Unchecked_Conversion (System.Address, Char_Ptr);
10657    @b{begin}
10658       @b{return} To_Char_Ptr (S (S'First)'Address);
10659    @b{end};
10661 @b{begin}
10662    Temp := Addr (Name);
10663    Get_String (Temp, Max_Length);
10664 @b{end};
10665 @end smallexample
10667 @noindent
10668 where Get_String is a C function that uses the address in Temp to
10669 modify the variable @code{Name}. This code is dubious, and arguably
10670 erroneous, and the compiler would be entitled to assume that
10671 @code{Name} is never modified, and generate code accordingly.
10673 However, in practice, this would cause some existing code that
10674 seems to work with no optimization to start failing at high
10675 levels of optimzization.
10677 What the compiler does for such cases is to assume that marking
10678 a variable as aliased indicates that some "funny business" may
10679 be going on. The optimizer recognizes the aliased keyword and
10680 inhibits optimizations that assume the value cannot be assigned.
10681 This means that the above example will in fact "work" reliably,
10682 that is, it will produce the expected results.
10684 @node Atomic Variables and Optimization
10685 @subsection Atomic Variables and Optimization
10686 @cindex Atomic
10687 There are two considerations with regard to performance when
10688 atomic variables are used.
10690 First, the RM only guarantees that access to atomic variables
10691 be atomic, it has nothing to say about how this is achieved,
10692 though there is a strong implication that this should not be
10693 achieved by explicit locking code. Indeed GNAT will never
10694 generate any locking code for atomic variable access (it will
10695 simply reject any attempt to make a variable or type atomic
10696 if the atomic access cannot be achieved without such locking code).
10698 That being said, it is important to understand that you cannot
10699 assume that the entire variable will always be accessed. Consider
10700 this example:
10702 @smallexample @c ada
10703 @b{type} R @b{is} @b{record}
10704    A,B,C,D : Character;
10705 @b{end} @b{record};
10706 @b{for} R'Size @b{use} 32;
10707 @b{for} R'Alignment @b{use} 4;
10709 RV : R;
10710 @b{pragma} Atomic (RV);
10711 X : Character;
10713 X := RV.B;
10714 @end smallexample
10716 @noindent
10717 You cannot assume that the reference to @code{RV.B}
10718 will read the entire 32-bit
10719 variable with a single load instruction. It is perfectly legitimate if
10720 the hardware allows it to do a byte read of just the B field. This read
10721 is still atomic, which is all the RM requires. GNAT can and does take
10722 advantage of this, depending on the architecture and optimization level.
10723 Any assumption to the contrary is non-portable and risky. Even if you
10724 examine the assembly language and see a full 32-bit load, this might
10725 change in a future version of the compiler.
10727 If your application requires that all accesses to @code{RV} in this
10728 example be full 32-bit loads, you need to make a copy for the access
10729 as in:
10731 @smallexample @c ada
10732 @b{declare}
10733    RV_Copy : @b{constant} R := RV;
10734 @b{begin}
10735    X := RV_Copy.B;
10736 @b{end};
10737 @end smallexample
10740 @noindent
10741 Now the reference to RV must read the whole variable.
10742 Actually one can imagine some compiler which figures
10743 out that the whole copy is not required (because only
10744 the B field is actually accessed), but GNAT
10745 certainly won't do that, and we don't know of any
10746 compiler that would not handle this right, and the
10747 above code will in practice work portably across
10748 all architectures (that permit the Atomic declaration).
10750 The second issue with atomic variables has to do with
10751 the possible requirement of generating synchronization
10752 code. For more details on this, consult the sections on
10753 the pragmas Enable/Disable_Atomic_Synchronization in the
10754 GNAT Reference Manual. If performance is critical, and
10755 such synchronization code is not required, it may be
10756 useful to disable it.
10758 @node Passive Task Optimization
10759 @subsection Passive Task Optimization
10760 @cindex Passive Task
10762 A passive task is one which is sufficiently simple that
10763 in theory a compiler could recognize it an implement it
10764 efficiently without creating a new thread. The original design
10765 of Ada 83 had in mind this kind of passive task optimization, but
10766 only a few Ada 83 compilers attempted it. The problem was that
10767 it was difficult to determine the exact conditions under which
10768 the optimization was possible. The result is a very fragile
10769 optimization where a very minor change in the program can
10770 suddenly silently make a task non-optimizable.
10772 With the revisiting of this issue in Ada 95, there was general
10773 agreement that this approach was fundamentally flawed, and the
10774 notion of protected types was introduced. When using protected
10775 types, the restrictions are well defined, and you KNOW that the
10776 operations will be optimized, and furthermore this optimized
10777 performance is fully portable.
10779 Although it would theoretically be possible for GNAT to attempt to
10780 do this optimization, but it really doesn't make sense in the
10781 context of Ada 95, and none of the Ada 95 compilers implement
10782 this optimization as far as we know. In particular GNAT never
10783 attempts to perform this optimization.
10785 In any new Ada 95 code that is written, you should always
10786 use protected types in place of tasks that might be able to
10787 be optimized in this manner.
10788 Of course this does not help if you have legacy Ada 83 code
10789 that depends on this optimization, but it is unusual to encounter
10790 a case where the performance gains from this optimization
10791 are significant.
10793 Your program should work correctly without this optimization. If
10794 you have performance problems, then the most practical
10795 approach is to figure out exactly where these performance problems
10796 arise, and update those particular tasks to be protected types. Note
10797 that typically clients of the tasks who call entries, will not have
10798 to be modified, only the task definition itself.
10802 @node Text_IO Suggestions
10803 @section @code{Text_IO} Suggestions
10804 @cindex @code{Text_IO} and performance
10806 @noindent
10807 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10808 the requirement of maintaining page and line counts. If performance
10809 is critical, a recommendation is to use @code{Stream_IO} instead of
10810 @code{Text_IO} for volume output, since this package has less overhead.
10812 If @code{Text_IO} must be used, note that by default output to the standard
10813 output and standard error files is unbuffered (this provides better
10814 behavior when output statements are used for debugging, or if the
10815 progress of a program is observed by tracking the output, e.g. by
10816 using the Unix @command{tail -f} command to watch redirected output.
10818 If you are generating large volumes of output with @code{Text_IO} and
10819 performance is an important factor, use a designated file instead
10820 of the standard output file, or change the standard output file to
10821 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10824 @ifclear FSFEDITION
10825 @node Reducing Size of Ada Executables with gnatelim
10826 @section Reducing Size of Ada Executables with @code{gnatelim}
10827 @findex gnatelim
10829 @noindent
10830 This section describes @command{gnatelim}, a tool which detects unused
10831 subprograms and helps the compiler to create a smaller executable for your
10832 program.
10834 @menu
10835 * About gnatelim::
10836 * Running gnatelim::
10837 * Processing Precompiled Libraries::
10838 * Correcting the List of Eliminate Pragmas::
10839 * Making Your Executables Smaller::
10840 * Summary of the gnatelim Usage Cycle::
10841 @end menu
10843 @node About gnatelim
10844 @subsection About @code{gnatelim}
10846 @noindent
10847 When a program shares a set of Ada
10848 packages with other programs, it may happen that this program uses
10849 only a fraction of the subprograms defined in these packages. The code
10850 created for these unused subprograms increases the size of the executable.
10852 @code{gnatelim} tracks unused subprograms in an Ada program and
10853 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10854 subprograms that are declared but never called. By placing the list of
10855 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10856 recompiling your program, you may decrease the size of its executable,
10857 because the compiler will not generate the code for 'eliminated' subprograms.
10858 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10859 information about this pragma.
10861 @code{gnatelim} needs as its input data the name of the main subprogram.
10863 If a set of source files is specified as @code{gnatelim} arguments, it
10864 treats these files as a complete set of sources making up a program to
10865 analyse, and analyses only these sources.
10867 After a full successful build of the main subprogram @code{gnatelim} can be
10868 called without  specifying sources to analyse, in this case it computes
10869 the source closure of the main unit from the @file{ALI} files.
10871 If the set of sources to be processed by @code{gnatelim} contains sources with
10872 preprocessing directives
10873 then the needed options should be provided to run preprocessor as a part of
10874 the @command{gnatelim} call, and the generated set of pragmas @code{Eliminate}
10875 will correspond to preprocessed sources.
10877 The following command will create the set of @file{ALI} files needed for
10878 @code{gnatelim}:
10880 @smallexample
10881 $ gnatmake -c Main_Prog
10882 @end smallexample
10884 Note that @code{gnatelim} does not need object files.
10886 @node Running gnatelim
10887 @subsection Running @code{gnatelim}
10889 @noindent
10890 @code{gnatelim} has the following command-line interface:
10892 @smallexample
10893 $ gnatelim [@var{switches}] -main=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10894 @end smallexample
10896 @noindent
10897 @var{main_unit_name} should be a name of a source file that contains the main
10898 subprogram of a program (partition).
10900 Each @var{filename} is the name (including the extension) of a source
10901 file to process. ``Wildcards'' are allowed, and
10902 the file name may contain path information.
10904 @samp{@var{gcc_switches}} is a list of switches for
10905 @command{gcc}. They will be passed on to all compiler invocations made by
10906 @command{gnatelim} to generate the ASIS trees. Here you can provide
10907 @option{-I} switches to form the source search path,
10908 use the @option{-gnatec} switch to set the configuration file,
10909 use the @option{-gnat05} switch if sources should be compiled in
10910 Ada 2005 mode etc.
10912 @code{gnatelim} has the following switches:
10914 @table @option
10915 @c !sort!
10916 @item --version
10917 @cindex @option{--version} @command{gnatelim}
10918 Display Copyright and version, then exit disregarding all other options.
10920 @item --help
10921 @cindex @option{--help} @command{gnatelim}
10922 Display usage, then exit disregarding all other options.
10924 @item -P @var{file}
10925 @cindex @option{-P} @command{gnatelim}
10926 Indicates the name of the project file that describes the set of sources
10927 to be processed.
10929 @item -X@var{name}=@var{value}
10930 @cindex @option{-X} @command{gnatelim}
10931 Indicates that external variable @var{name} in the argument project
10932 has the value @var{value}. Has no effect if no project is specified as
10933 tool argument.
10935 @item -files=@var{filename}
10936 @cindex @option{-files} (@code{gnatelim})
10937 Take the argument source files from the specified file. This file should be an
10938 ordinary text file containing file names separated by spaces or
10939 line breaks. You can use this switch more than once in the same call to
10940 @command{gnatelim}. You also can combine this switch with
10941 an explicit list of files.
10943 @item -log
10944 @cindex @option{-log} (@command{gnatelim})
10945 Duplicate all the output sent to @file{stderr} into a log file. The log file
10946 is named @file{gnatelim.log} and is located in the current directory.
10948 @ignore
10949 @item -log=@var{filename}
10950 @cindex @option{-log} (@command{gnatelim})
10951 Duplicate all the output sent to @file{stderr} into a specified log file.
10952 @end ignore
10954 @cindex @option{--no-elim-dispatch} (@command{gnatelim})
10955 @item --no-elim-dispatch
10956 Do not generate pragmas for dispatching operations.
10958 @item --ignore=@var{filename}
10959 @cindex @option{--ignore} (@command{gnatelim})
10960 Do not generate pragmas for subprograms declared in the sources
10961 listed in a specified file
10963 @cindex @option{-o} (@command{gnatelim})
10964 @item -o=@var{report_file}
10965 Put @command{gnatelim} output into a specified file. If this file already exists,
10966 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10967 into @file{stderr}
10969 @item -j@var{n}
10970 @cindex @option{-j} (@command{gnatelim})
10971 Use @var{n} processes to carry out the tree creations (internal representations
10972 of the argument sources). On a multiprocessor machine this speeds up processing
10973 of big sets of argument sources. If @var{n} is 0, then the maximum number of
10974 parallel tree creations is the number of core processors on the platform.
10976 @item -q
10977 @cindex @option{-q} (@command{gnatelim})
10978 Quiet mode: by default @code{gnatelim} outputs to the standard error
10979 stream the number of program units left to be processed. This option turns
10980 this trace off.
10982 @cindex @option{-t} (@command{gnatelim})
10983 @item -t
10984 Print out execution time.
10986 @item -v
10987 @cindex @option{-v} (@command{gnatelim})
10988 Verbose mode: @code{gnatelim} version information is printed as Ada
10989 comments to the standard output stream. Also, in addition to the number of
10990 program units left @code{gnatelim} will output the name of the current unit
10991 being processed.
10993 @item -wq
10994 @cindex @option{-wq} (@command{gnatelim})
10995 Quiet warning mode - some warnings are suppressed. In particular warnings that
10996 indicate that the analysed set of sources is incomplete to make up a
10997 partition and that some subprogram bodies are missing are not generated.
10998 @end table
11000 @noindent
11001 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11002 driver (see @ref{The GNAT Driver and Project Files}).
11004 @node Processing Precompiled Libraries
11005 @subsection Processing Precompiled Libraries
11007 @noindent
11008 If some program uses a precompiled Ada library, it can be processed by
11009 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11010 Eliminate pragma for a subprogram if the body of this subprogram has not
11011 been analysed, this is a typical case for subprograms from precompiled
11012 libraries. Switch @option{-wq} may be used to suppress
11013 warnings about missing source files and non-analyzed subprogram bodies
11014 that can be generated when processing precompiled Ada libraries.
11016 @node Correcting the List of Eliminate Pragmas
11017 @subsection Correcting the List of Eliminate Pragmas
11019 @noindent
11020 In some rare cases @code{gnatelim} may try to eliminate
11021 subprograms that are actually called in the program. In this case, the
11022 compiler will generate an error message of the form:
11024 @smallexample
11025 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11026 @end smallexample
11028 @noindent
11029 You will need to manually remove the wrong @code{Eliminate} pragmas from
11030 the configuration file indicated in the error message. You should recompile
11031 your program from scratch after that, because you need a consistent
11032 configuration file(s) during the entire compilation.
11034 @node Making Your Executables Smaller
11035 @subsection Making Your Executables Smaller
11037 @noindent
11038 In order to get a smaller executable for your program you now have to
11039 recompile the program completely with the configuration file containing
11040 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11041 @file{gnat.adc} file located in your current directory, just do:
11043 @smallexample
11044 $ gnatmake -f main_prog
11045 @end smallexample
11047 @noindent
11048 (Use the @option{-f} option for @command{gnatmake} to
11049 recompile everything
11050 with the set of pragmas @code{Eliminate} that you have obtained with
11051 @command{gnatelim}).
11053 Be aware that the set of @code{Eliminate} pragmas is specific to each
11054 program. It is not recommended to merge sets of @code{Eliminate}
11055 pragmas created for different programs in one configuration file.
11057 @node Summary of the gnatelim Usage Cycle
11058 @subsection Summary of the @code{gnatelim} Usage Cycle
11060 @noindent
11061 Here is a quick summary of the steps to be taken in order to reduce
11062 the size of your executables with @code{gnatelim}. You may use
11063 other GNAT options to control the optimization level,
11064 to produce the debugging information, to set search path, etc.
11066 @enumerate
11067 @item
11068 Create a complete set of @file{ALI} files (if the program has not been
11069 built already)
11071 @smallexample
11072 $ gnatmake -c main_prog
11073 @end smallexample
11075 @item
11076 Generate a list of @code{Eliminate} pragmas in default configuration file
11077 @file{gnat.adc} in the current directory
11078 @smallexample
11079 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11080 @end smallexample
11082 @item
11083 Recompile the application
11085 @smallexample
11086 $ gnatmake -f main_prog
11087 @end smallexample
11089 @end enumerate
11090 @end ifclear
11092 @node Reducing Size of Executables with unused subprogram/data elimination
11093 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11094 @findex unused subprogram/data elimination
11096 @noindent
11097 This section describes how you can eliminate unused subprograms and data from
11098 your executable just by setting options at compilation time.
11100 @menu
11101 * About unused subprogram/data elimination::
11102 * Compilation options::
11103 * Example of unused subprogram/data elimination::
11104 @end menu
11106 @node About unused subprogram/data elimination
11107 @subsection About unused subprogram/data elimination
11109 @noindent
11110 By default, an executable contains all code and data of its composing objects
11111 (directly linked or coming from statically linked libraries), even data or code
11112 never used by this executable.
11114 This feature will allow you to eliminate such unused code from your
11115 executable, making it smaller (in disk and in memory).
11117 This functionality is available on all Linux platforms except for the IA-64
11118 architecture and on all cross platforms using the ELF binary file format.
11119 In both cases GNU binutils version 2.16 or later are required to enable it.
11121 @node Compilation options
11122 @subsection Compilation options
11124 @noindent
11125 The operation of eliminating the unused code and data from the final executable
11126 is directly performed by the linker.
11128 In order to do this, it has to work with objects compiled with the
11129 following options:
11130 @option{-ffunction-sections} @option{-fdata-sections}.
11131 @cindex @option{-ffunction-sections} (@command{gcc})
11132 @cindex @option{-fdata-sections} (@command{gcc})
11133 These options are usable with C and Ada files.
11134 They will place respectively each
11135 function or data in a separate section in the resulting object file.
11137 Once the objects and static libraries are created with these options, the
11138 linker can perform the dead code elimination. You can do this by setting
11139 the @option{-Wl,--gc-sections} option to gcc command or in the
11140 @option{-largs} section of @command{gnatmake}. This will perform a
11141 garbage collection of code and data never referenced.
11143 If the linker performs a partial link (@option{-r} linker option), then you
11144 will need to provide the entry point using the @option{-e} / @option{--entry}
11145 linker option.
11147 Note that objects compiled without the @option{-ffunction-sections} and
11148 @option{-fdata-sections} options can still be linked with the executable.
11149 However, no dead code elimination will be performed on those objects (they will
11150 be linked as is).
11152 The GNAT static library is now compiled with -ffunction-sections and
11153 -fdata-sections on some platforms. This allows you to eliminate the unused code
11154 and data of the GNAT library from your executable.
11156 @node Example of unused subprogram/data elimination
11157 @subsection Example of unused subprogram/data elimination
11159 @noindent
11160 Here is a simple example:
11162 @smallexample @c ada
11163 @b{with} Aux;
11165 @b{procedure} Test @b{is}
11166 @b{begin}
11167    Aux.Used (10);
11168 @b{end} Test;
11170 @b{package} Aux @b{is}
11171    Used_Data   : Integer;
11172    Unused_Data : Integer;
11174    @b{procedure} Used   (Data : Integer);
11175    @b{procedure} Unused (Data : Integer);
11176 @b{end} Aux;
11178 @b{package} @b{body} Aux @b{is}
11179    @b{procedure} Used (Data : Integer) @b{is}
11180    @b{begin}
11181       Used_Data := Data;
11182    @b{end} Used;
11184    @b{procedure} Unused (Data : Integer) @b{is}
11185    @b{begin}
11186       Unused_Data := Data;
11187    @b{end} Unused;
11188 @b{end} Aux;
11189 @end smallexample
11191 @noindent
11192 @code{Unused} and @code{Unused_Data} are never referenced in this code
11193 excerpt, and hence they may be safely removed from the final executable.
11195 @smallexample
11196 $ gnatmake test
11198 $ nm test | grep used
11199 020015f0 T aux__unused
11200 02005d88 B aux__unused_data
11201 020015cc T aux__used
11202 02005d84 B aux__used_data
11204 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11205      -largs -Wl,--gc-sections
11207 $ nm test | grep used
11208 02005350 T aux__used
11209 0201ffe0 B aux__used_data
11210 @end smallexample
11212 @noindent
11213 It can be observed that the procedure @code{Unused} and the object
11214 @code{Unused_Data} are removed by the linker when using the
11215 appropriate options.
11217 @c ********************************
11218 @node Renaming Files with gnatchop
11219 @chapter Renaming Files with @code{gnatchop}
11220 @findex gnatchop
11222 @noindent
11223 This chapter discusses how to handle files with multiple units by using
11224 the @code{gnatchop} utility. This utility is also useful in renaming
11225 files to meet the standard GNAT default file naming conventions.
11227 @menu
11228 * Handling Files with Multiple Units::
11229 * Operating gnatchop in Compilation Mode::
11230 * Command Line for gnatchop::
11231 * Switches for gnatchop::
11232 * Examples of gnatchop Usage::
11233 @end menu
11235 @node Handling Files with Multiple Units
11236 @section Handling Files with Multiple Units
11238 @noindent
11239 The basic compilation model of GNAT requires that a file submitted to the
11240 compiler have only one unit and there be a strict correspondence
11241 between the file name and the unit name.
11243 The @code{gnatchop} utility allows both of these rules to be relaxed,
11244 allowing GNAT to process files which contain multiple compilation units
11245 and files with arbitrary file names. @code{gnatchop}
11246 reads the specified file and generates one or more output files,
11247 containing one unit per file. The unit and the file name correspond,
11248 as required by GNAT.
11250 If you want to permanently restructure a set of ``foreign'' files so that
11251 they match the GNAT rules, and do the remaining development using the
11252 GNAT structure, you can simply use @command{gnatchop} once, generate the
11253 new set of files and work with them from that point on.
11255 Alternatively, if you want to keep your files in the ``foreign'' format,
11256 perhaps to maintain compatibility with some other Ada compilation
11257 system, you can set up a procedure where you use @command{gnatchop} each
11258 time you compile, regarding the source files that it writes as temporary
11259 files that you throw away.
11261 Note that if your file containing multiple units starts with a byte order
11262 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11263 will each start with a copy of this BOM, meaning that they can be compiled
11264 automatically in UTF-8 mode without needing to specify an explicit encoding.
11266 @node Operating gnatchop in Compilation Mode
11267 @section Operating gnatchop in Compilation Mode
11269 @noindent
11270 The basic function of @code{gnatchop} is to take a file with multiple units
11271 and split it into separate files. The boundary between files is reasonably
11272 clear, except for the issue of comments and pragmas. In default mode, the
11273 rule is that any pragmas between units belong to the previous unit, except
11274 that configuration pragmas always belong to the following unit. Any comments
11275 belong to the following unit. These rules
11276 almost always result in the right choice of
11277 the split point without needing to mark it explicitly and most users will
11278 find this default to be what they want. In this default mode it is incorrect to
11279 submit a file containing only configuration pragmas, or one that ends in
11280 configuration pragmas, to @code{gnatchop}.
11282 However, using a special option to activate ``compilation mode'',
11283 @code{gnatchop}
11284 can perform another function, which is to provide exactly the semantics
11285 required by the RM for handling of configuration pragmas in a compilation.
11286 In the absence of configuration pragmas (at the main file level), this
11287 option has no effect, but it causes such configuration pragmas to be handled
11288 in a quite different manner.
11290 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11291 only configuration pragmas, then this file is appended to the
11292 @file{gnat.adc} file in the current directory. This behavior provides
11293 the required behavior described in the RM for the actions to be taken
11294 on submitting such a file to the compiler, namely that these pragmas
11295 should apply to all subsequent compilations in the same compilation
11296 environment. Using GNAT, the current directory, possibly containing a
11297 @file{gnat.adc} file is the representation
11298 of a compilation environment. For more information on the
11299 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11301 Second, in compilation mode, if @code{gnatchop}
11302 is given a file that starts with
11303 configuration pragmas, and contains one or more units, then these
11304 configuration pragmas are prepended to each of the chopped files. This
11305 behavior provides the required behavior described in the RM for the
11306 actions to be taken on compiling such a file, namely that the pragmas
11307 apply to all units in the compilation, but not to subsequently compiled
11308 units.
11310 Finally, if configuration pragmas appear between units, they are appended
11311 to the previous unit. This results in the previous unit being illegal,
11312 since the compiler does not accept configuration pragmas that follow
11313 a unit. This provides the required RM behavior that forbids configuration
11314 pragmas other than those preceding the first compilation unit of a
11315 compilation.
11317 For most purposes, @code{gnatchop} will be used in default mode. The
11318 compilation mode described above is used only if you need exactly
11319 accurate behavior with respect to compilations, and you have files
11320 that contain multiple units and configuration pragmas. In this
11321 circumstance the use of @code{gnatchop} with the compilation mode
11322 switch provides the required behavior, and is for example the mode
11323 in which GNAT processes the ACVC tests.
11325 @node Command Line for gnatchop
11326 @section Command Line for @code{gnatchop}
11328 @noindent
11329 The @code{gnatchop} command has the form:
11331 @smallexample
11332 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11333 @c      @ovar{directory}
11334 @c Expanding @ovar macro inline (explanation in macro def comments)
11335 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11336       @r{[}@var{directory}@r{]}
11337 @end smallexample
11339 @noindent
11340 The only required argument is the file name of the file to be chopped.
11341 There are no restrictions on the form of this file name. The file itself
11342 contains one or more Ada units, in normal GNAT format, concatenated
11343 together. As shown, more than one file may be presented to be chopped.
11345 When run in default mode, @code{gnatchop} generates one output file in
11346 the current directory for each unit in each of the files.
11348 @var{directory}, if specified, gives the name of the directory to which
11349 the output files will be written. If it is not specified, all files are
11350 written to the current directory.
11352 For example, given a
11353 file called @file{hellofiles} containing
11355 @smallexample @c ada
11356 @group
11357 @cartouche
11358 @b{procedure} hello;
11360 @b{with} Text_IO; @b{use} Text_IO;
11361 @b{procedure} hello @b{is}
11362 @b{begin}
11363    Put_Line ("Hello");
11364 @b{end} hello;
11365 @end cartouche
11366 @end group
11367 @end smallexample
11369 @noindent
11370 the command
11372 @smallexample
11373 $ gnatchop hellofiles
11374 @end smallexample
11376 @noindent
11377 generates two files in the current directory, one called
11378 @file{hello.ads} containing the single line that is the procedure spec,
11379 and the other called @file{hello.adb} containing the remaining text. The
11380 original file is not affected. The generated files can be compiled in
11381 the normal manner.
11383 @noindent
11384 When gnatchop is invoked on a file that is empty or that contains only empty
11385 lines and/or comments, gnatchop will not fail, but will not produce any
11386 new sources.
11388 For example, given a
11389 file called @file{toto.txt} containing
11391 @smallexample @c ada
11392 @group
11393 @cartouche
11394 --@i{  Just a comment}
11395 @end cartouche
11396 @end group
11397 @end smallexample
11399 @noindent
11400 the command
11402 @smallexample
11403 $ gnatchop toto.txt
11404 @end smallexample
11406 @noindent
11407 will not produce any new file and will result in the following warnings:
11409 @smallexample
11410 toto.txt:1:01: warning: empty file, contains no compilation units
11411 no compilation units found
11412 no source files written
11413 @end smallexample
11415 @node Switches for gnatchop
11416 @section Switches for @code{gnatchop}
11418 @noindent
11419 @command{gnatchop} recognizes the following switches:
11421 @table @option
11422 @c !sort!
11424 @item --version
11425 @cindex @option{--version} @command{gnatchop}
11426 Display Copyright and version, then exit disregarding all other options.
11428 @item --help
11429 @cindex @option{--help} @command{gnatchop}
11430 If @option{--version} was not used, display usage, then exit disregarding
11431 all other options.
11433 @item -c
11434 @cindex @option{-c} (@code{gnatchop})
11435 Causes @code{gnatchop} to operate in compilation mode, in which
11436 configuration pragmas are handled according to strict RM rules. See
11437 previous section for a full description of this mode.
11439 @item -gnat@var{xxx}
11440 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11441 used to parse the given file. Not all @var{xxx} options make sense,
11442 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11443 process a source file that uses Latin-2 coding for identifiers.
11445 @item -h
11446 Causes @code{gnatchop} to generate a brief help summary to the standard
11447 output file showing usage information.
11449 @item -k@var{mm}
11450 @cindex @option{-k} (@code{gnatchop})
11451 Limit generated file names to the specified number @code{mm}
11452 of characters.
11453 This is useful if the
11454 resulting set of files is required to be interoperable with systems
11455 which limit the length of file names.
11456 No space is allowed between the @option{-k} and the numeric value. The numeric
11457 value may be omitted in which case a default of @option{-k8},
11458 suitable for use
11459 with DOS-like file systems, is used. If no @option{-k} switch
11460 is present then
11461 there is no limit on the length of file names.
11463 @item -p
11464 @cindex @option{-p} (@code{gnatchop})
11465 Causes the file modification time stamp of the input file to be
11466 preserved and used for the time stamp of the output file(s). This may be
11467 useful for preserving coherency of time stamps in an environment where
11468 @code{gnatchop} is used as part of a standard build process.
11470 @item -q
11471 @cindex @option{-q} (@code{gnatchop})
11472 Causes output of informational messages indicating the set of generated
11473 files to be suppressed. Warnings and error messages are unaffected.
11475 @item -r
11476 @cindex @option{-r} (@code{gnatchop})
11477 @findex Source_Reference
11478 Generate @code{Source_Reference} pragmas. Use this switch if the output
11479 files are regarded as temporary and development is to be done in terms
11480 of the original unchopped file. This switch causes
11481 @code{Source_Reference} pragmas to be inserted into each of the
11482 generated files to refers back to the original file name and line number.
11483 The result is that all error messages refer back to the original
11484 unchopped file.
11485 In addition, the debugging information placed into the object file (when
11486 the @option{-g} switch of @command{gcc} or @command{gnatmake} is
11487 specified)
11488 also refers back to this original file so that tools like profilers and
11489 debuggers will give information in terms of the original unchopped file.
11491 If the original file to be chopped itself contains
11492 a @code{Source_Reference}
11493 pragma referencing a third file, then gnatchop respects
11494 this pragma, and the generated @code{Source_Reference} pragmas
11495 in the chopped file refer to the original file, with appropriate
11496 line numbers. This is particularly useful when @code{gnatchop}
11497 is used in conjunction with @code{gnatprep} to compile files that
11498 contain preprocessing statements and multiple units.
11500 @item -v
11501 @cindex @option{-v} (@code{gnatchop})
11502 Causes @code{gnatchop} to operate in verbose mode. The version
11503 number and copyright notice are output, as well as exact copies of
11504 the gnat1 commands spawned to obtain the chop control information.
11506 @item -w
11507 @cindex @option{-w} (@code{gnatchop})
11508 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11509 fatal error if there is already a file with the same name as a
11510 file it would otherwise output, in other words if the files to be
11511 chopped contain duplicated units. This switch bypasses this
11512 check, and causes all but the last instance of such duplicated
11513 units to be skipped.
11515 @item --GCC=@var{xxxx}
11516 @cindex @option{--GCC=} (@code{gnatchop})
11517 Specify the path of the GNAT parser to be used. When this switch is used,
11518 no attempt is made to add the prefix to the GNAT parser executable.
11519 @end table
11521 @node Examples of gnatchop Usage
11522 @section Examples of @code{gnatchop} Usage
11524 @table @code
11525 @item gnatchop -w hello_s.ada prerelease/files
11527 Chops the source file @file{hello_s.ada}. The output files will be
11528 placed in the directory @file{prerelease/files},
11529 overwriting any
11530 files with matching names in that directory (no files in the current
11531 directory are modified).
11533 @item gnatchop archive
11534 Chops the source file @file{archive}
11535 into the current directory. One
11536 useful application of @code{gnatchop} is in sending sets of sources
11537 around, for example in email messages. The required sources are simply
11538 concatenated (for example, using a Unix @code{cat}
11539 command), and then
11540 @command{gnatchop} is used at the other end to reconstitute the original
11541 file names.
11543 @item gnatchop file1 file2 file3 direc
11544 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11545 the resulting files in the directory @file{direc}. Note that if any units
11546 occur more than once anywhere within this set of files, an error message
11547 is generated, and no files are written. To override this check, use the
11548 @option{-w} switch,
11549 in which case the last occurrence in the last file will
11550 be the one that is output, and earlier duplicate occurrences for a given
11551 unit will be skipped.
11552 @end table
11554 @node Configuration Pragmas
11555 @chapter Configuration Pragmas
11556 @cindex Configuration pragmas
11557 @cindex Pragmas, configuration
11559 @menu
11560 * Handling of Configuration Pragmas::
11561 * The Configuration Pragmas Files::
11562 @end menu
11564 @noindent
11565 Configuration pragmas include those pragmas described as
11566 such in the Ada Reference Manual, as well as
11567 implementation-dependent pragmas that are configuration pragmas.
11568 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11569 for details on these additional GNAT-specific configuration pragmas.
11570 Most notably, the pragma @code{Source_File_Name}, which allows
11571 specifying non-default names for source files, is a configuration
11572 pragma. The following is a complete list of configuration pragmas
11573 recognized by GNAT:
11575 @smallexample
11576    Ada_83
11577    Ada_95
11578    Ada_05
11579    Ada_2005
11580    Ada_12
11581    Ada_2012
11582    Allow_Integer_Address
11583    Annotate
11584    Assertion_Policy
11585    Assume_No_Invalid_Values
11586    C_Pass_By_Copy
11587    Check_Name
11588    Check_Policy
11589    Compile_Time_Error
11590    Compile_Time_Warning
11591    Compiler_Unit
11592    Component_Alignment
11593    Convention_Identifier
11594    Debug_Policy
11595    Detect_Blocking
11596    Default_Storage_Pool
11597    Discard_Names
11598    Elaboration_Checks
11599    Eliminate
11600    Extend_System
11601    Extensions_Allowed
11602    External_Name_Casing
11603    Fast_Math
11604    Favor_Top_Level
11605    Float_Representation
11606    Implicit_Packing
11607    Initialize_Scalars
11608    Interrupt_State
11609    License
11610    Locking_Policy
11611    Long_Float
11612    No_Run_Time
11613    No_Strict_Aliasing
11614    Normalize_Scalars
11615    Optimize_Alignment
11616    Persistent_BSS
11617    Polling
11618    Priority_Specific_Dispatching
11619    Profile
11620    Profile_Warnings
11621    Propagate_Exceptions
11622    Queuing_Policy
11623    Ravenscar
11624    Restricted_Run_Time
11625    Restrictions
11626    Restrictions_Warnings
11627    Reviewable
11628    Short_Circuit_And_Or
11629    Source_File_Name
11630    Source_File_Name_Project
11631    SPARK_Mode
11632    Style_Checks
11633    Suppress
11634    Suppress_Exception_Locations
11635    Task_Dispatching_Policy
11636    Universal_Data
11637    Unsuppress
11638    Use_VADS_Size
11639    Validity_Checks
11640    Warnings
11641    Wide_Character_Encoding
11642 @end smallexample
11644 @node Handling of Configuration Pragmas
11645 @section Handling of Configuration Pragmas
11647 Configuration pragmas may either appear at the start of a compilation
11648 unit, or they can appear in a configuration pragma file to apply to
11649 all compilations performed in a given compilation environment.
11651 GNAT also provides the @code{gnatchop} utility to provide an automatic
11652 way to handle configuration pragmas following the semantics for
11653 compilations (that is, files with multiple units), described in the RM.
11654 See @ref{Operating gnatchop in Compilation Mode} for details.
11655 However, for most purposes, it will be more convenient to edit the
11656 @file{gnat.adc} file that contains configuration pragmas directly,
11657 as described in the following section.
11659 In the case of @code{Restrictions} pragmas appearing as configuration
11660 pragmas in individual compilation units, the exact handling depends on
11661 the type of restriction.
11663 Restrictions that require partition-wide consistency (like
11664 @code{No_Tasking}) are
11665 recognized wherever they appear
11666 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11667 unit. This makes sense since the binder will in any case insist on seeing
11668 consistent use, so any unit not conforming to any restrictions that are
11669 anywhere in the partition will be rejected, and you might as well find
11670 that out at compile time rather than at bind time.
11672 For restrictions that do not require partition-wide consistency, e.g.
11673 SPARK or No_Implementation_Attributes, in general the restriction applies
11674 only to the unit in which the pragma appears, and not to any other units.
11676 The exception is No_Elaboration_Code which always applies to the entire
11677 object file from a compilation, i.e. to the body, spec, and all subunits.
11678 This restriction can be specified in a configuration pragma file, or it
11679 can be on the body and/or the spec (in eithe case it applies to all the
11680 relevant units). It can appear on a subunit only if it has previously
11681 appeared in the body of spec.
11683 @node The Configuration Pragmas Files
11684 @section The Configuration Pragmas Files
11685 @cindex @file{gnat.adc}
11687 @noindent
11688 In GNAT a compilation environment is defined by the current
11689 directory at the time that a compile command is given. This current
11690 directory is searched for a file whose name is @file{gnat.adc}. If
11691 this file is present, it is expected to contain one or more
11692 configuration pragmas that will be applied to the current compilation.
11693 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11694 considered. When taken into account, @file{gnat.adc} is added to the
11695 dependencies, so that if @file{gnat.adc} is modified later, an invocation of
11696 @command{gnatmake} will recompile the source.
11698 Configuration pragmas may be entered into the @file{gnat.adc} file
11699 either by running @code{gnatchop} on a source file that consists only of
11700 configuration pragmas, or more conveniently by direct editing of the
11701 @file{gnat.adc} file, which is a standard format source file.
11703 In addition to @file{gnat.adc}, additional files containing configuration
11704 pragmas may be applied to the current compilation using the switch
11705 @option{-gnatec=}@var{path}. @var{path} must designate an existing file that
11706 contains only configuration pragmas. These configuration pragmas are
11707 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11708 is present and switch @option{-gnatA} is not used).
11710 It is allowable to specify several switches @option{-gnatec=}, all of which
11711 will be taken into account.
11713 Files containing configuration pragmas specified with switches
11714 @option{-gnatec=} are added to the dependencies, unless they are
11715 temporary files. A file is considered temporary if its name ends in
11716 @file{.tmp} or @file{.TMP}. Certain tools follow this naming
11717 convention because they pass information to @command{gcc} via
11718 temporary files that are immediately deleted; it doesn't make sense to
11719 depend on a file that no longer exists. Such tools include
11720 @command{gprbuild}, @command{gnatmake}, and @command{gnatcheck}.
11722 If you are using project file, a separate mechanism is provided using
11723 project attributes, see @ref{Specifying Configuration Pragmas} for more
11724 details.
11727 @node Handling Arbitrary File Naming Conventions with gnatname
11728 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
11729 @cindex Arbitrary File Naming Conventions
11731 @menu
11732 * Arbitrary File Naming Conventions::
11733 * Running gnatname::
11734 * Switches for gnatname::
11735 * Examples of gnatname Usage::
11736 @end menu
11738 @node Arbitrary File Naming Conventions
11739 @section Arbitrary File Naming Conventions
11741 @noindent
11742 The GNAT compiler must be able to know the source file name of a compilation
11743 unit.  When using the standard GNAT default file naming conventions
11744 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11745 does not need additional information.
11747 @noindent
11748 When the source file names do not follow the standard GNAT default file naming
11749 conventions, the GNAT compiler must be given additional information through
11750 a configuration pragmas file (@pxref{Configuration Pragmas})
11751 or a project file.
11752 When the non-standard file naming conventions are well-defined,
11753 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11754 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11755 if the file naming conventions are irregular or arbitrary, a number
11756 of pragma @code{Source_File_Name} for individual compilation units
11757 must be defined.
11758 To help maintain the correspondence between compilation unit names and
11759 source file names within the compiler,
11760 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11761 set of files.
11763 @node Running gnatname
11764 @section Running @code{gnatname}
11766 @noindent
11767 The usual form of the @code{gnatname} command is
11769 @smallexample
11770 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11771 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11772 @c Expanding @ovar macro inline (explanation in macro def comments)
11773 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11774       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11775 @end smallexample
11777 @noindent
11778 All of the arguments are optional. If invoked without any argument,
11779 @code{gnatname} will display its usage.
11781 @noindent
11782 When used with at least one naming pattern, @code{gnatname} will attempt to
11783 find all the compilation units in files that follow at least one of the
11784 naming patterns. To find these compilation units,
11785 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11786 regular files.
11788 @noindent
11789 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11790 Each Naming Pattern is enclosed between double quotes (or single
11791 quotes on Windows).
11792 A Naming Pattern is a regular expression similar to the wildcard patterns
11793 used in file names by the Unix shells or the DOS prompt.
11795 @noindent
11796 @code{gnatname} may be called with several sections of directories/patterns.
11797 Sections are separated by switch @code{--and}. In each section, there must be
11798 at least one pattern. If no directory is specified in a section, the current
11799 directory (or the project directory is @code{-P} is used) is implied.
11800 The options other that the directory switches and the patterns apply globally
11801 even if they are in different sections.
11803 @noindent
11804 Examples of Naming Patterns are
11806 @smallexample
11807    "*.[12].ada"
11808    "*.ad[sb]*"
11809    "body_*"    "spec_*"
11810 @end smallexample
11812 @noindent
11813 For a more complete description of the syntax of Naming Patterns,
11814 see the second kind of regular expressions described in @file{g-regexp.ads}
11815 (the ``Glob'' regular expressions).
11817 @noindent
11818 When invoked with no switch @code{-P}, @code{gnatname} will create a
11819 configuration pragmas file @file{gnat.adc} in the current working directory,
11820 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11821 unit.
11823 @node Switches for gnatname
11824 @section Switches for @code{gnatname}
11826 @noindent
11827 Switches for @code{gnatname} must precede any specified Naming Pattern.
11829 @noindent
11830 You may specify any of the following switches to @code{gnatname}:
11832 @table @option
11833 @c !sort!
11835 @item --version
11836 @cindex @option{--version} @command{gnatname}
11837 Display Copyright and version, then exit disregarding all other options.
11839 @item --help
11840 @cindex @option{--help} @command{gnatname}
11841 If @option{--version} was not used, display usage, then exit disregarding
11842 all other options.
11844 @item --subdirs=<dir>
11845 Real object, library or exec directories are subdirectories <dir> of the
11846 specified ones.
11848 @item --no-backup
11849 Do not create a backup copy of an existing project file.
11851 @item --and
11852 Start another section of directories/patterns.
11854 @item -c@file{file}
11855 @cindex @option{-c} (@code{gnatname})
11856 Create a configuration pragmas file @file{file} (instead of the default
11857 @file{gnat.adc}).
11858 There may be zero, one or more space between @option{-c} and
11859 @file{file}.
11860 @file{file} may include directory information. @file{file} must be
11861 writable. There may be only one switch @option{-c}.
11862 When a switch @option{-c} is
11863 specified, no switch @option{-P} may be specified (see below).
11865 @item -d@file{dir}
11866 @cindex @option{-d} (@code{gnatname})
11867 Look for source files in directory @file{dir}. There may be zero, one or more
11868 spaces between @option{-d} and @file{dir}.
11869 @file{dir} may end with @code{/**}, that is it may be of the form
11870 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
11871 subdirectories, recursively, have to be searched for sources.
11872 When a switch @option{-d}
11873 is specified, the current working directory will not be searched for source
11874 files, unless it is explicitly specified with a @option{-d}
11875 or @option{-D} switch.
11876 Several switches @option{-d} may be specified.
11877 If @file{dir} is a relative path, it is relative to the directory of
11878 the configuration pragmas file specified with switch
11879 @option{-c},
11880 or to the directory of the project file specified with switch
11881 @option{-P} or,
11882 if neither switch @option{-c}
11883 nor switch @option{-P} are specified, it is relative to the
11884 current working directory. The directory
11885 specified with switch @option{-d} must exist and be readable.
11887 @item -D@file{file}
11888 @cindex @option{-D} (@code{gnatname})
11889 Look for source files in all directories listed in text file @file{file}.
11890 There may be zero, one or more spaces between @option{-D}
11891 and @file{file}.
11892 @file{file} must be an existing, readable text file.
11893 Each nonempty line in @file{file} must be a directory.
11894 Specifying switch @option{-D} is equivalent to specifying as many
11895 switches @option{-d} as there are nonempty lines in
11896 @file{file}.
11898 @item -eL
11899 Follow symbolic links when processing project files.
11901 @item -f@file{pattern}
11902 @cindex @option{-f} (@code{gnatname})
11903 Foreign patterns. Using this switch, it is possible to add sources of languages
11904 other than Ada to the list of sources of a project file.
11905 It is only useful if a -P switch is used.
11906 For example,
11907 @smallexample
11908 gnatname -Pprj -f"*.c" "*.ada"
11909 @end smallexample
11910 @noindent
11911 will look for Ada units in all files with the @file{.ada} extension,
11912 and will add to the list of file for project @file{prj.gpr} the C files
11913 with extension @file{.c}.
11915 @item -h
11916 @cindex @option{-h} (@code{gnatname})
11917 Output usage (help) information. The output is written to @file{stdout}.
11919 @item -P@file{proj}
11920 @cindex @option{-P} (@code{gnatname})
11921 Create or update project file @file{proj}. There may be zero, one or more space
11922 between @option{-P} and @file{proj}. @file{proj} may include directory
11923 information. @file{proj} must be writable.
11924 There may be only one switch @option{-P}.
11925 When a switch @option{-P} is specified,
11926 no switch @option{-c} may be specified.
11927 On all platforms, except on VMS, when @code{gnatname} is invoked for an
11928 existing project file <proj>.gpr, a backup copy of the project file is created
11929 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
11930 non negative number that makes this backup copy a new file.
11932 @item -v
11933 @cindex @option{-v} (@code{gnatname})
11934 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11935 This includes name of the file written, the name of the directories to search
11936 and, for each file in those directories whose name matches at least one of
11937 the Naming Patterns, an indication of whether the file contains a unit,
11938 and if so the name of the unit.
11940 @item -v -v
11941 @cindex @option{-v -v} (@code{gnatname})
11942 Very Verbose mode. In addition to the output produced in verbose mode,
11943 for each file in the searched directories whose name matches none of
11944 the Naming Patterns, an indication is given that there is no match.
11946 @item -x@file{pattern}
11947 @cindex @option{-x} (@code{gnatname})
11948 Excluded patterns. Using this switch, it is possible to exclude some files
11949 that would match the name patterns. For example,
11950 @smallexample
11951 gnatname -x "*_nt.ada" "*.ada"
11952 @end smallexample
11953 @noindent
11954 will look for Ada units in all files with the @file{.ada} extension,
11955 except those whose names end with @file{_nt.ada}.
11957 @end table
11959 @node Examples of gnatname Usage
11960 @section Examples of @code{gnatname} Usage
11963 @smallexample
11964 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11965 @end smallexample
11967 @noindent
11968 In this example, the directory @file{/home/me} must already exist
11969 and be writable. In addition, the directory
11970 @file{/home/me/sources} (specified by
11971 @option{-d sources}) must exist and be readable.
11973 Note the optional spaces after @option{-c} and @option{-d}.
11975 @smallexample
11976 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11977   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11978 @end smallexample
11980 Note that several switches @option{-d} may be used,
11981 even in conjunction with one or several switches
11982 @option{-D}. Several Naming Patterns and one excluded pattern
11983 are used in this example.
11985 @c *****************************************
11986 @c * G N A T  P r o j e c t  M a n a g e r *
11987 @c *****************************************
11989 @c ------ macros for projects.texi
11990 @c These macros are needed when building the gprbuild documentation, but
11991 @c should have no effect in the gnat user's guide
11993 @macro CODESAMPLE{TXT}
11994 @smallexample
11995 @group
11996 \TXT\
11997 @end group
11998 @end smallexample
11999 @end macro
12001 @macro PROJECTFILE{TXT}
12002 @CODESAMPLE{\TXT\}
12003 @end macro
12005 @c simulates a newline when in a @CODESAMPLE
12006 @macro NL{}
12007 @end macro
12009 @macro TIP{TXT}
12010 @quotation
12011 @noindent
12012 \TXT\
12013 @end quotation
12014 @end macro
12016 @macro TIPHTML{TXT}
12017 \TXT\
12018 @end macro
12020 @macro IMPORTANT{TXT}
12021 @quotation
12022 @noindent
12023 \TXT\
12024 @end quotation
12026 @end macro
12028 @macro NOTE{TXT}
12029 @quotation
12030 @noindent
12031 \TXT\
12032 @end quotation
12033 @end macro
12035 @include projects.texi
12037 @c ---------------------------------------------
12038 @c Tools Supporting Project Files
12039 @c ---------------------------------------------
12041 @node Tools Supporting Project Files
12042 @chapter Tools Supporting Project Files
12044 @noindent
12046 @menu
12047 * gnatmake and Project Files::
12048 * The GNAT Driver and Project Files::
12049 @end menu
12051 @c ---------------------------------------------
12052 @node gnatmake and Project Files
12053 @section gnatmake and Project Files
12054 @c ---------------------------------------------
12056 @noindent
12057 This section covers several topics related to @command{gnatmake} and
12058 project files: defining switches for @command{gnatmake}
12059 and for the tools that it invokes; specifying configuration pragmas;
12060 the use of the @code{Main} attribute; building and rebuilding library project
12061 files.
12063 @menu
12064 * Switches Related to Project Files::
12065 * Switches and Project Files::
12066 * Specifying Configuration Pragmas::
12067 * Project Files and Main Subprograms::
12068 * Library Project Files::
12069 @end menu
12071 @c ---------------------------------------------
12072 @node Switches Related to Project Files
12073 @subsection Switches Related to Project Files
12074 @c ---------------------------------------------
12076 @noindent
12077 The following switches are used by GNAT tools that support project files:
12079 @table @option
12081 @item -P@var{project}
12082 @cindex @option{-P} (any project-aware tool)
12083 Indicates the name of a project file. This project file will be parsed with
12084 the verbosity indicated by @option{-vP@emph{x}},
12085 if any, and using the external references indicated
12086 by @option{-X} switches, if any.
12087 There may zero, one or more spaces between @option{-P} and @var{project}.
12089 There must be only one @option{-P} switch on the command line.
12091 Since the Project Manager parses the project file only after all the switches
12092 on the command line are checked, the order of the switches
12093 @option{-P},
12094 @option{-vP@emph{x}}
12095 or @option{-X} is not significant.
12097 @item -X@var{name=value}
12098 @cindex @option{-X} (any project-aware tool)
12099 Indicates that external variable @var{name} has the value @var{value}.
12100 The Project Manager will use this value for occurrences of
12101 @code{external(name)} when parsing the project file.
12103 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12104 put between quotes.
12105 @smallexample
12106   -XOS=NT
12107   -X"user=John Doe"
12108 @end smallexample
12110 Several @option{-X} switches can be used simultaneously.
12111 If several @option{-X} switches specify the same
12112 @var{name}, only the last one is used.
12114 An external variable specified with a @option{-X} switch
12115 takes precedence over the value of the same name in the environment.
12117 @item -vP@emph{x}
12118 @cindex @option{-vP} (any project-aware tool)
12119 Indicates the verbosity of the parsing of GNAT project files.
12121 @option{-vP0} means Default;
12122 @option{-vP1} means Medium;
12123 @option{-vP2} means High.
12126 The default is Default: no output for syntactically correct
12127 project files.
12128 If several @option{-vP@emph{x}} switches are present,
12129 only the last one is used.
12131 @item -aP<dir>
12132 @cindex @option{-aP} (any project-aware tool)
12133 Add directory <dir> at the beginning of the project search path, in order,
12134 after the current working directory.
12136 @item -eL
12137 @cindex @option{-eL} (any project-aware tool)
12138 Follow all symbolic links when processing project files.
12140 @item --subdirs=<subdir>
12141 @cindex @option{--subdirs=} (gnatmake and gnatclean)
12142 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12143 indicate that the real directories (except the source directories) are the
12144 subdirectories <subdir> of the directories specified in the project files.
12145 This applies in particular to object directories, library directories and
12146 exec directories. If the subdirectories do not exist, they are created
12147 automatically.
12149 @end table
12151 @c ---------------------------------------------
12152 @node Switches and Project Files
12153 @subsection Switches and Project Files
12154 @c ---------------------------------------------
12156 @noindent
12158 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12159 @code{Linker}, you can specify a @code{Default_Switches}
12160 attribute, a @code{Switches} attribute, or both;
12161 as their names imply, these switch-related
12162 attributes affect the switches that are used for each of these GNAT
12163 components when
12164 @command{gnatmake} is invoked.  As will be explained below, these
12165 component-specific switches precede
12166 the switches provided on the @command{gnatmake} command line.
12168 The @code{Default_Switches} attribute is an attribute
12169 indexed by language name (case insensitive) whose value is a string list.
12170 For example:
12172 @smallexample @c projectfile
12173 @group
12174 @b{package} Compiler @b{is}
12175   @b{for} Default_Switches ("Ada")
12176       @b{use} ("-gnaty",
12177            "-v");
12178 @b{end} Compiler;
12179 @end group
12180 @end smallexample
12182 @noindent
12183 The @code{Switches} attribute is indexed on a file name (which may or may
12184 not be case sensitive, depending
12185 on the operating system) whose value is a string list.  For example:
12187 @smallexample @c projectfile
12188 @group
12189 @b{package} Builder @b{is}
12190    @b{for} Switches ("main1.adb")
12191        @b{use} ("-O2");
12192    @b{for} Switches ("main2.adb")
12193        @b{use} ("-g");
12194 @b{end} Builder;
12195 @end group
12196 @end smallexample
12198 @noindent
12199 For the @code{Builder} package, the file names must designate source files
12200 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12201 file names must designate @file{ALI} or source files for main subprograms.
12202 In each case just the file name without an explicit extension is acceptable.
12204 For each tool used in a program build (@command{gnatmake}, the compiler, the
12205 binder, and the linker), the corresponding package @dfn{contributes} a set of
12206 switches for each file on which the tool is invoked, based on the
12207 switch-related attributes defined in the package.
12208 In particular, the switches
12209 that each of these packages contributes for a given file @var{f} comprise:
12211 @itemize @bullet
12212 @item the value of attribute @code{Switches (@var{f})},
12213   if it is specified in the package for the given file,
12214 @item otherwise, the value of @code{Default_Switches ("Ada")},
12215   if it is specified in the package.
12217 @end itemize
12219 @noindent
12220 If neither of these attributes is defined in the package, then the package does
12221 not contribute any switches for the given file.
12223 When @command{gnatmake} is invoked on a file, the switches comprise
12224 two sets, in the following order: those contributed for the file
12225 by the @code{Builder} package;
12226 and the switches passed on the command line.
12228 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12229 the switches passed to the tool comprise three sets,
12230 in the following order:
12232 @enumerate
12233 @item
12234 the applicable switches contributed for the file
12235 by the @code{Builder} package in the project file supplied on the command line;
12237 @item
12238 those contributed for the file by the package (in the relevant project file --
12239 see below) corresponding to the tool; and
12241 @item
12242 the applicable switches passed on the command line.
12243 @end enumerate
12245 The term @emph{applicable switches} reflects the fact that
12246 @command{gnatmake} switches may or may not be passed to individual
12247 tools, depending on the individual switch.
12249 @command{gnatmake} may invoke the compiler on source files from different
12250 projects. The Project Manager will use the appropriate project file to
12251 determine the @code{Compiler} package for each source file being compiled.
12252 Likewise for the @code{Binder} and @code{Linker} packages.
12254 As an example, consider the following package in a project file:
12256 @smallexample @c projectfile
12257 @group
12258 @b{project} Proj1 @b{is}
12259    @b{package} Compiler @b{is}
12260       @b{for} Default_Switches ("Ada")
12261           @b{use} ("-g");
12262       @b{for} Switches ("a.adb")
12263           @b{use} ("-O1");
12264       @b{for} Switches ("b.adb")
12265           @b{use} ("-O2",
12266                "-gnaty");
12267    @b{end} Compiler;
12268 @b{end} Proj1;
12269 @end group
12270 @end smallexample
12272 @noindent
12273 If @command{gnatmake} is invoked with this project file, and it needs to
12274 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12275 @file{a.adb} will be compiled with the switch
12276 @option{-O1},
12277 @file{b.adb} with switches
12278 @option{-O2}
12279 and @option{-gnaty},
12280 and @file{c.adb} with @option{-g}.
12282 The following example illustrates the ordering of the switches
12283 contributed by different packages:
12285 @smallexample @c projectfile
12286 @group
12287 @b{project} Proj2 @b{is}
12288    @b{package} Builder @b{is}
12289       @b{for} Switches ("main.adb")
12290           @b{use} ("-g",
12291                "-O1",
12292                "-f");
12293    @b{end} Builder;
12294 @end group
12296 @group
12297    @b{package} Compiler @b{is}
12298       @b{for} Switches ("main.adb")
12299           @b{use} ("-O2");
12300    @b{end} Compiler;
12301 @b{end} Proj2;
12302 @end group
12303 @end smallexample
12305 @noindent
12306 If you issue the command:
12308 @smallexample
12309     gnatmake -Pproj2 -O0 main
12310 @end smallexample
12312 @noindent
12313 then the compiler will be invoked on @file{main.adb} with the following
12314 sequence of switches
12316 @smallexample
12317    -g -O1 -O2 -O0
12318 @end smallexample
12320 @noindent
12321 with the last @option{-O}
12322 switch having precedence over the earlier ones;
12323 several other switches
12324 (such as @option{-c}) are added implicitly.
12326 The switches
12327 @option{-g}
12328 and @option{-O1} are contributed by package
12329 @code{Builder},  @option{-O2} is contributed
12330 by the package @code{Compiler}
12331 and @option{-O0} comes from the command line.
12333 The @option{-g}
12334 switch will also be passed in the invocation of
12335 @command{Gnatlink.}
12337 A final example illustrates switch contributions from packages in different
12338 project files:
12340 @smallexample @c projectfile
12341 @group
12342 @b{project} Proj3 @b{is}
12343    @b{for} Source_Files @b{use} ("pack.ads", "pack.adb");
12344    @b{package} Compiler @b{is}
12345       @b{for} Default_Switches ("Ada")
12346           @b{use} ("-gnata");
12347    @b{end} Compiler;
12348 @b{end} Proj3;
12349 @end group
12351 @group
12352 @b{with} "Proj3";
12353 @b{project} Proj4 @b{is}
12354    @b{for} Source_Files @b{use} ("foo_main.adb", "bar_main.adb");
12355    @b{package} Builder @b{is}
12356       @b{for} Switches ("foo_main.adb")
12357           @b{use} ("-s",
12358                "-g");
12359    @b{end} Builder;
12360 @b{end} Proj4;
12361 @end group
12363 @group
12364 --@i{ Ada source file:}
12365 @b{with} Pack;
12366 @b{procedure} Foo_Main @b{is}
12367    @dots{}
12368 @b{end} Foo_Main;
12369 @end group
12370 @end smallexample
12372 @noindent
12373 If the command is
12374 @smallexample
12375 gnatmake -PProj4 foo_main.adb -cargs -gnato
12376 @end smallexample
12378 @noindent
12379 then the switches passed to the compiler for @file{foo_main.adb} are
12380 @option{-g} (contributed by the package @code{Proj4.Builder}) and
12381 @option{-gnato} (passed on the command line).
12382 When the imported package @code{Pack} is compiled, the switches used
12383 are @option{-g} from @code{Proj4.Builder},
12384 @option{-gnata} (contributed from package @code{Proj3.Compiler},
12385 and @option{-gnato} from the command line.
12387 When using @command{gnatmake} with project files, some switches or
12388 arguments may be expressed as relative paths. As the working directory where
12389 compilation occurs may change, these relative paths are converted to absolute
12390 paths. For the switches found in a project file, the relative paths
12391 are relative to the project file directory, for the switches on the command
12392 line, they are relative to the directory where @command{gnatmake} is invoked.
12393 The switches for which this occurs are:
12397 -aO,
12398 -aL,
12399 -aI, as well as all arguments that are not switches (arguments to
12400 switch
12401 -o, object files specified in package @code{Linker} or after
12402 -largs on the command line). The exception to this rule is the switch
12403 --RTS= for which a relative path argument is never converted.
12405 @c ---------------------------------------------
12406 @node Specifying Configuration Pragmas
12407 @subsection Specifying Configuration Pragmas
12408 @c ---------------------------------------------
12410 @noindent
12411 When using @command{gnatmake} with project files, if there exists a file
12412 @file{gnat.adc} that contains configuration pragmas, this file will be
12413 ignored.
12415 Configuration pragmas can be defined by means of the following attributes in
12416 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12417 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12419 Both these attributes are single string attributes. Their values is the path
12420 name of a file containing configuration pragmas. If a path name is relative,
12421 then it is relative to the project directory of the project file where the
12422 attribute is defined.
12424 When compiling a source, the configuration pragmas used are, in order,
12425 those listed in the file designated by attribute
12426 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12427 project file, if it is specified, and those listed in the file designated by
12428 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12429 the project file of the source, if it exists.
12431 @c ---------------------------------------------
12432 @node Project Files and Main Subprograms
12433 @subsection Project Files and Main Subprograms
12434 @c ---------------------------------------------
12436 @noindent
12437 When using a project file, you can invoke @command{gnatmake}
12438 with one or several main subprograms, by specifying their source files on the
12439 command line.
12441 @smallexample
12442     gnatmake -Pprj main1.adb main2.adb main3.adb
12443 @end smallexample
12445 @noindent
12446 Each of these needs to be a source file of the same project, except
12447 when the switch -u is used.
12449 When -u is not used, all the mains need to be sources of the
12450 same project, one of the project in the tree rooted at the project specified
12451 on the command line. The package @code{Builder} of this common project, the
12452 "main project" is the one that is considered by @command{gnatmake}.
12454 When -u is used, the specified source files may be in projects
12455 imported directly or indirectly by the project specified on the command line.
12456 Note that if such a source file is not part of the project specified on the
12457 command line, the switches found in package @code{Builder} of the
12458 project specified on the command line, if any, that are transmitted
12459 to the compiler will still be used, not those found in the project file of
12460 the source file.
12462 When using a project file, you can also invoke @command{gnatmake} without
12463 explicitly specifying any main, and the effect depends on whether you have
12464 defined the @code{Main} attribute.  This attribute has a string list value,
12465 where each element in the list is the name of a source file (the file
12466 extension is optional) that contains a unit that can be a main subprogram.
12468 If the @code{Main} attribute is defined in a project file as a non-empty
12469 string list and the switch @option{-u} is not used on the command
12470 line, then invoking @command{gnatmake} with this project file but without any
12471 main on the command line is equivalent to invoking @command{gnatmake} with all
12472 the file names in the @code{Main} attribute on the command line.
12474 Example:
12475 @smallexample @c projectfile
12476 @group
12477    @b{project} Prj @b{is}
12478       @b{for} Main @b{use} ("main1.adb", "main2.adb", "main3.adb");
12479    @b{end} Prj;
12480 @end group
12481 @end smallexample
12483 @noindent
12484 With this project file, @code{"gnatmake -Pprj"}
12485 is equivalent to
12486 @code{"gnatmake -Pprj main1.adb main2.adb main3.adb"}.
12488 When the project attribute @code{Main} is not specified, or is specified
12489 as an empty string list, or when the switch @option{-u} is used on the command
12490 line, then invoking @command{gnatmake} with no main on the command line will
12491 result in all immediate sources of the project file being checked, and
12492 potentially recompiled. Depending on the presence of the switch @option{-u},
12493 sources from other project files on which the immediate sources of the main
12494 project file depend are also checked and potentially recompiled. In other
12495 words, the @option{-u} switch is applied to all of the immediate sources of the
12496 main project file.
12498 When no main is specified on the command line and attribute @code{Main} exists
12499 and includes several mains, or when several mains are specified on the
12500 command line, the default switches in package @code{Builder} will
12501 be used for all mains, even if there are specific switches
12502 specified for one or several mains.
12504 But the switches from package @code{Binder} or @code{Linker} will be
12505 the specific switches for each main, if they are specified.
12507 @c ---------------------------------------------
12508 @node Library Project Files
12509 @subsection Library Project Files
12510 @c ---------------------------------------------
12512 @noindent
12513 When @command{gnatmake} is invoked with a main project file that is a library
12514 project file, it is not allowed to specify one or more mains on the command
12515 line.
12517 When a library project file is specified, switches -b and
12518 -l have special meanings.
12520 @itemize @bullet
12521 @item -b is only allowed for stand-alone libraries. It indicates
12522   to @command{gnatmake} that @command{gnatbind} should be invoked for the
12523   library.
12525 @item -l may be used for all library projects. It indicates
12526   to @command{gnatmake} that the binder generated file should be compiled
12527   (in the case of a stand-alone library) and that the library should be built.
12528 @end itemize
12530 @c ---------------------------------------------
12531 @node The GNAT Driver and Project Files
12532 @section The GNAT Driver and Project Files
12533 @c ---------------------------------------------
12535 @noindent
12536 A number of GNAT tools, other than @command{gnatmake}
12537 can benefit from project files:
12538 (@command{gnatbind},
12539 @ifclear FSFEDITION
12540 @command{gnatcheck},
12541 @end ifclear
12542 @command{gnatclean},
12543 @ifclear FSFEDITION
12544 @command{gnatelim},
12545 @end ifclear
12546 @command{gnatfind},
12547 @command{gnatlink},
12548 @command{gnatls},
12549 @ifclear FSFEDITION
12550 @command{gnatmetric},
12551 @command{gnatpp},
12552 @command{gnatstub},
12553 @end ifclear
12554 and @command{gnatxref}). However, none of these tools can be invoked
12555 directly with a project file switch (@option{-P}).
12556 They must be invoked through the @command{gnat} driver.
12558 The @command{gnat} driver is a wrapper that accepts a number of commands and
12559 calls the corresponding tool. It was designed initially for VMS platforms (to
12560 convert VMS qualifiers to Unix-style switches), but it is now available on all
12561 GNAT platforms.
12563 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12564 (case insensitive):
12566 @itemize @bullet
12567 @item BIND to invoke @command{gnatbind}
12568 @item CHOP to invoke @command{gnatchop}
12569 @item CLEAN to invoke @command{gnatclean}
12570 @item COMP or COMPILE to invoke the compiler
12571 @ifclear FSFEDITION
12572 @item ELIM to invoke @command{gnatelim}
12573 @end ifclear
12574 @item FIND to invoke @command{gnatfind}
12575 @item KR or KRUNCH to invoke @command{gnatkr}
12576 @item LINK to invoke @command{gnatlink}
12577 @item LS or LIST to invoke @command{gnatls}
12578 @item MAKE to invoke @command{gnatmake}
12579 @item NAME to invoke @command{gnatname}
12580 @item PREP or PREPROCESS to invoke @command{gnatprep}
12581 @ifclear FSFEDITION
12582 @item PP or PRETTY to invoke @command{gnatpp}
12583 @item METRIC to invoke @command{gnatmetric}
12584 @item STUB to invoke @command{gnatstub}
12585 @end ifclear
12586 @item XREF to invoke @command{gnatxref}
12588 @end itemize
12590 @noindent
12591 (note that the compiler is invoked using the command
12592 @command{gnatmake -f -u -c}).
12594 On non-VMS platforms, between @command{gnat} and the command, two
12595 special switches may be used:
12597 @itemize @bullet
12598 @item @command{-v} to display the invocation of the tool.
12599 @item @command{-dn} to prevent the @command{gnat} driver from removing
12600   the temporary files it has created. These temporary files are
12601   configuration files and temporary file list files.
12603 @end itemize
12605 @noindent
12606 The command may be followed by switches and arguments for the invoked
12607 tool.
12609 @smallexample
12610   gnat bind -C main.ali
12611   gnat ls -a main
12612   gnat chop foo.txt
12613 @end smallexample
12615 @noindent
12616 Switches may also be put in text files, one switch per line, and the text
12617 files may be specified with their path name preceded by '@@'.
12619 @smallexample
12620    gnat bind @@args.txt main.ali
12621 @end smallexample
12623 @noindent
12624 In addition, for commands BIND, COMP or COMPILE, FIND,
12625 @ifclear FSFEDITION
12626 ELIM,
12627 @end ifclear
12628 LS or LIST, LINK,
12629 @ifclear FSFEDITION
12630 METRIC,
12631 PP or PRETTY,
12632 STUB,
12633 @end ifclear
12634 and XREF, the project file related switches
12635 (@option{-P},
12636 @option{-X} and
12637 @option{-vPx}) may be used in addition to
12638 the switches of the invoking tool.
12640 @ifclear FSFEDITION
12641 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12642 specified on the command line, it invokes @command{gnatpp} with all
12643 the immediate sources of the specified project file.
12644 @end ifclear
12646 @ifclear FSFEDITION
12647 When GNAT METRIC is used with a project file, but with no source
12648 specified on the command line, it invokes @command{gnatmetric}
12649 with all the immediate sources of the specified project file and with
12650 @option{-d} with the parameter pointing to the object directory
12651 of the project.
12652 @end ifclear
12654 @ifclear FSFEDITION
12655 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12656 a project file, no source is specified on the command line and
12657 switch -U is specified on the command line, then
12658 the underlying tool (gnatpp or
12659 gnatmetric) is invoked for all sources of all projects,
12660 not only for the immediate sources of the main project.
12661 (-U stands for Universal or Union of the project files of the project tree)
12662 @end ifclear
12664 For each of the following commands, there is optionally a corresponding
12665 package in the main project.
12667 @itemize @bullet
12668 @item package @code{Binder} for command BIND (invoking @code{gnatbind})
12670 @ifclear FSFEDITION
12671 @item package @code{Check} for command CHECK (invoking
12672   @code{gnatcheck})
12673 @end ifclear
12675 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12677 @item package @code{Cross_Reference} for command XREF (invoking
12678   @code{gnatxref})
12680 @ifclear FSFEDITION
12681 @item package @code{Eliminate} for command ELIM (invoking
12682   @code{gnatelim})
12683 @end ifclear
12685 @item package @code{Finder} for command FIND (invoking @code{gnatfind})
12687 @item package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
12689 @ifclear FSFEDITION
12690 @item package @code{Gnatstub} for command STUB
12691   (invoking @code{gnatstub})
12692 @end ifclear
12694 @item package @code{Linker} for command LINK (invoking @code{gnatlink})
12696 @ifclear FSFEDITION
12697 @item package @code{Check} for command CHECK
12698   (invoking @code{gnatcheck})
12699 @end ifclear
12701 @ifclear FSFEDITION
12702 @item package @code{Metrics} for command METRIC
12703   (invoking @code{gnatmetric})
12704 @end ifclear
12706 @ifclear FSFEDITION
12707 @item package @code{Pretty_Printer} for command PP or PRETTY
12708   (invoking @code{gnatpp})
12709 @end ifclear
12711 @end itemize
12713 @noindent
12714 Package @code{Gnatls} has a unique attribute @code{Switches},
12715 a simple variable with a string list value. It contains switches
12716 for the invocation of @code{gnatls}.
12718 @smallexample @c projectfile
12719 @group
12720 @b{project} Proj1 @b{is}
12721    @b{package} gnatls @b{is}
12722       @b{for} Switches
12723           @b{use} ("-a",
12724                "-v");
12725    @b{end} gnatls;
12726 @b{end} Proj1;
12727 @end group
12728 @end smallexample
12730 @noindent
12731 All other packages have two attribute @code{Switches} and
12732 @code{Default_Switches}.
12734 @code{Switches} is an indexed attribute, indexed by the
12735 source file name, that has a string list value: the switches to be
12736 used when the tool corresponding to the package is invoked for the specific
12737 source file.
12739 @code{Default_Switches} is an attribute,
12740 indexed by  the programming language that has a string list value.
12741 @code{Default_Switches ("Ada")} contains the
12742 switches for the invocation of the tool corresponding
12743 to the package, except if a specific @code{Switches} attribute
12744 is specified for the source file.
12746 @smallexample @c projectfile
12747 @group
12748 @b{project} Proj @b{is}
12750    @b{for} Source_Dirs @b{use} ("**");
12752    @b{package} gnatls @b{is}
12753       @b{for} Switches @b{use}
12754           ("-a",
12755            "-v");
12756    @b{end} gnatls;
12757 @end group
12758 @group
12760    @b{package} Compiler @b{is}
12761       @b{for} Default_Switches ("Ada")
12762           @b{use} ("-gnatv",
12763                "-gnatwa");
12764    @b{end} Binder;
12765 @end group
12766 @group
12768    @b{package} Binder @b{is}
12769       @b{for} Default_Switches ("Ada")
12770           @b{use} ("-C",
12771                "-e");
12772    @b{end} Binder;
12773 @end group
12774 @group
12776    @b{package} Linker @b{is}
12777       @b{for} Default_Switches ("Ada")
12778           @b{use} ("-C");
12779       @b{for} Switches ("main.adb")
12780           @b{use} ("-C",
12781                "-v",
12782                "-v");
12783    @b{end} Linker;
12784 @end group
12785 @group
12787    @b{package} Finder @b{is}
12788       @b{for} Default_Switches ("Ada")
12789            @b{use} ("-a",
12790                 "-f");
12791    @b{end} Finder;
12792 @end group
12793 @group
12795    @b{package} Cross_Reference @b{is}
12796       @b{for} Default_Switches ("Ada")
12797           @b{use} ("-a",
12798                "-f",
12799                "-d",
12800                "-u");
12801    @b{end} Cross_Reference;
12802 @b{end} Proj;
12803 @end group
12804 @end smallexample
12806 @noindent
12807 With the above project file, commands such as
12809 @smallexample
12810    gnat comp -Pproj main
12811    gnat ls -Pproj main
12812    gnat xref -Pproj main
12813    gnat bind -Pproj main.ali
12814    gnat link -Pproj main.ali
12815 @end smallexample
12817 @noindent
12818 will set up the environment properly and invoke the tool with the switches
12819 found in the package corresponding to the tool:
12820 @code{Default_Switches ("Ada")} for all tools,
12821 except @code{Switches ("main.adb")}
12822 for @code{gnatlink}.
12823 @ifclear FSFEDITION
12824 It is also possible to invoke some of the tools,
12825 (@code{gnatcheck},
12826 @code{gnatmetric},
12827 and @code{gnatpp})
12828 on a set of project units thanks to the combination of the switches
12829 @option{-P}, @option{-U} and possibly the main unit when one is interested
12830 in its closure. For instance,
12831 @smallexample
12832 gnat metric -Pproj
12833 @end smallexample
12835 @noindent
12836 will compute the metrics for all the immediate units of project
12837 @code{proj}.
12838 @smallexample
12839 gnat metric -Pproj -U
12840 @end smallexample
12842 @noindent
12843 will compute the metrics for all the units of the closure of projects
12844 rooted at @code{proj}.
12845 @smallexample
12846 gnat metric -Pproj -U main_unit
12847 @end smallexample
12849 @noindent
12850 will compute the metrics for the closure of units rooted at
12851 @code{main_unit}. This last possibility relies implicitly
12852 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
12853 tool invoked by the @command{gnat} driver are explicitly  specified
12854 either directly or through the tool @option{-files} option, then the tool
12855 is called only for these explicitly specified files.
12856 @end ifclear
12858 @c *****************************************
12859 @c * Cross-referencing tools
12860 @c *****************************************
12862 @node The Cross-Referencing Tools gnatxref and gnatfind
12863 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12864 @findex gnatxref
12865 @findex gnatfind
12867 @noindent
12868 The compiler generates cross-referencing information (unless
12869 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12870 This information indicates where in the source each entity is declared and
12871 referenced. Note that entities in package Standard are not included, but
12872 entities in all other predefined units are included in the output.
12874 Before using any of these two tools, you need to compile successfully your
12875 application, so that GNAT gets a chance to generate the cross-referencing
12876 information.
12878 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12879 information to provide the user with the capability to easily locate the
12880 declaration and references to an entity. These tools are quite similar,
12881 the difference being that @code{gnatfind} is intended for locating
12882 definitions and/or references to a specified entity or entities, whereas
12883 @code{gnatxref} is oriented to generating a full report of all
12884 cross-references.
12886 To use these tools, you must not compile your application using the
12887 @option{-gnatx} switch on the @command{gnatmake} command line
12888 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12889 information will not be generated.
12891 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12892 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12894 @menu
12895 * Switches for gnatxref::
12896 * Switches for gnatfind::
12897 * Project Files for gnatxref and gnatfind::
12898 * Regular Expressions in gnatfind and gnatxref::
12899 * Examples of gnatxref Usage::
12900 * Examples of gnatfind Usage::
12901 @end menu
12903 @node Switches for gnatxref
12904 @section @code{gnatxref} Switches
12906 @noindent
12907 The command invocation for @code{gnatxref} is:
12908 @smallexample
12909 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12910 @c Expanding @ovar macro inline (explanation in macro def comments)
12911 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12912 @end smallexample
12914 @noindent
12915 where
12917 @table @var
12918 @item sourcefile1
12919 @itemx sourcefile2
12920 identifies the source files for which a report is to be generated. The
12921 ``with''ed units will be processed too. You must provide at least one file.
12923 These file names are considered to be regular expressions, so for instance
12924 specifying @file{source*.adb} is the same as giving every file in the current
12925 directory whose name starts with @file{source} and whose extension is
12926 @file{adb}.
12928 You shouldn't specify any directory name, just base names. @command{gnatxref}
12929 and @command{gnatfind} will be able to locate these files by themselves using
12930 the source path. If you specify directories, no result is produced.
12932 @end table
12934 @noindent
12935 The switches can be:
12936 @table @option
12937 @c !sort!
12938 @item --version
12939 @cindex @option{--version} @command{gnatxref}
12940 Display Copyright and version, then exit disregarding all other options.
12942 @item --help
12943 @cindex @option{--help} @command{gnatxref}
12944 If @option{--version} was not used, display usage, then exit disregarding
12945 all other options.
12947 @item -a
12948 @cindex @option{-a} (@command{gnatxref})
12949 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12950 the read-only files found in the library search path. Otherwise, these files
12951 will be ignored. This option can be used to protect Gnat sources or your own
12952 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12953 much faster, and their output much smaller. Read-only here refers to access
12954 or permissions status in the file system for the current user.
12956 @item -aIDIR
12957 @cindex @option{-aIDIR} (@command{gnatxref})
12958 When looking for source files also look in directory DIR. The order in which
12959 source file search is undertaken is the same as for @command{gnatmake}.
12961 @item -aODIR
12962 @cindex @option{-aODIR} (@command{gnatxref})
12963 When searching for library and object files, look in directory
12964 DIR. The order in which library files are searched is the same as for
12965 @command{gnatmake}.
12967 @item -nostdinc
12968 @cindex @option{-nostdinc} (@command{gnatxref})
12969 Do not look for sources in the system default directory.
12971 @item -nostdlib
12972 @cindex @option{-nostdlib} (@command{gnatxref})
12973 Do not look for library files in the system default directory.
12975 @item --ext=@var{extension}
12976 @cindex @option{--ext} (@command{gnatxref})
12977 Specify an alternate ali file extension. The default is @code{ali} and other
12978 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
12979 may be specified via this switch. Note that if this switch overrides the
12980 default, which means that only the new extension will be considered.
12982 @item --RTS=@var{rts-path}
12983 @cindex @option{--RTS} (@command{gnatxref})
12984 Specifies the default location of the runtime library. Same meaning as the
12985 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12987 @item -d
12988 @cindex @option{-d} (@command{gnatxref})
12989 If this switch is set @code{gnatxref} will output the parent type
12990 reference for each matching derived types.
12992 @item -f
12993 @cindex @option{-f} (@command{gnatxref})
12994 If this switch is set, the output file names will be preceded by their
12995 directory (if the file was found in the search path). If this switch is
12996 not set, the directory will not be printed.
12998 @item -g
12999 @cindex @option{-g} (@command{gnatxref})
13000 If this switch is set, information is output only for library-level
13001 entities, ignoring local entities. The use of this switch may accelerate
13002 @code{gnatfind} and @code{gnatxref}.
13004 @item -IDIR
13005 @cindex @option{-IDIR} (@command{gnatxref})
13006 Equivalent to @samp{-aODIR -aIDIR}.
13008 @item -pFILE
13009 @cindex @option{-pFILE} (@command{gnatxref})
13010 Specify a project file to use @xref{GNAT Project Manager}.
13011 If you need to use the @file{.gpr}
13012 project files, you should use gnatxref through the GNAT driver
13013 (@command{gnat xref -Pproject}).
13015 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13016 project file in the current directory.
13018 If a project file is either specified or found by the tools, then the content
13019 of the source directory and object directory lines are added as if they
13020 had been specified respectively by @samp{-aI}
13021 and @samp{-aO}.
13022 @item -u
13023 Output only unused symbols. This may be really useful if you give your
13024 main compilation unit on the command line, as @code{gnatxref} will then
13025 display every unused entity and 'with'ed package.
13027 @item -v
13028 Instead of producing the default output, @code{gnatxref} will generate a
13029 @file{tags} file that can be used by vi. For examples how to use this
13030 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13031 to the standard output, thus you will have to redirect it to a file.
13033 @end table
13035 @noindent
13036 All these switches may be in any order on the command line, and may even
13037 appear after the file names. They need not be separated by spaces, thus
13038 you can say @samp{gnatxref -ag} instead of
13039 @samp{gnatxref -a -g}.
13041 @node Switches for gnatfind
13042 @section @code{gnatfind} Switches
13044 @noindent
13045 The command line for @code{gnatfind} is:
13047 @smallexample
13048 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13049 @c       @r{[}@var{file1} @var{file2} @dots{}]
13050 @c Expanding @ovar macro inline (explanation in macro def comments)
13051 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13052       @r{[}@var{file1} @var{file2} @dots{}@r{]}
13053 @end smallexample
13055 @noindent
13056 where
13058 @table @var
13059 @item pattern
13060 An entity will be output only if it matches the regular expression found
13061 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13063 Omitting the pattern is equivalent to specifying @samp{*}, which
13064 will match any entity. Note that if you do not provide a pattern, you
13065 have to provide both a sourcefile and a line.
13067 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13068 for matching purposes. At the current time there is no support for
13069 8-bit codes other than Latin-1, or for wide characters in identifiers.
13071 @item sourcefile
13072 @code{gnatfind} will look for references, bodies or declarations
13073 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13074 and column @var{column}. See @ref{Examples of gnatfind Usage}
13075 for syntax examples.
13077 @item line
13078 is a decimal integer identifying the line number containing
13079 the reference to the entity (or entities) to be located.
13081 @item column
13082 is a decimal integer identifying the exact location on the
13083 line of the first character of the identifier for the
13084 entity reference. Columns are numbered from 1.
13086 @item file1 file2 @dots{}
13087 The search will be restricted to these source files. If none are given, then
13088 the search will be done for every library file in the search path.
13089 These file must appear only after the pattern or sourcefile.
13091 These file names are considered to be regular expressions, so for instance
13092 specifying @file{source*.adb} is the same as giving every file in the current
13093 directory whose name starts with @file{source} and whose extension is
13094 @file{adb}.
13096 The location of the spec of the entity will always be displayed, even if it
13097 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
13098 occurrences of the entity in the separate units of the ones given on the
13099 command line will also be displayed.
13101 Note that if you specify at least one file in this part, @code{gnatfind} may
13102 sometimes not be able to find the body of the subprograms.
13104 @end table
13106 @noindent
13107 At least one of 'sourcefile' or 'pattern' has to be present on
13108 the command line.
13110 The following switches are available:
13111 @table @option
13112 @c !sort!
13114 @cindex @option{--version} @command{gnatfind}
13115 Display Copyright and version, then exit disregarding all other options.
13117 @item --help
13118 @cindex @option{--help} @command{gnatfind}
13119 If @option{--version} was not used, display usage, then exit disregarding
13120 all other options.
13122 @item -a
13123 @cindex @option{-a} (@command{gnatfind})
13124 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13125 the read-only files found in the library search path. Otherwise, these files
13126 will be ignored. This option can be used to protect Gnat sources or your own
13127 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13128 much faster, and their output much smaller. Read-only here refers to access
13129 or permission status in the file system for the current user.
13131 @item -aIDIR
13132 @cindex @option{-aIDIR} (@command{gnatfind})
13133 When looking for source files also look in directory DIR. The order in which
13134 source file search is undertaken is the same as for @command{gnatmake}.
13136 @item -aODIR
13137 @cindex @option{-aODIR} (@command{gnatfind})
13138 When searching for library and object files, look in directory
13139 DIR. The order in which library files are searched is the same as for
13140 @command{gnatmake}.
13142 @item -nostdinc
13143 @cindex @option{-nostdinc} (@command{gnatfind})
13144 Do not look for sources in the system default directory.
13146 @item -nostdlib
13147 @cindex @option{-nostdlib} (@command{gnatfind})
13148 Do not look for library files in the system default directory.
13150 @item --ext=@var{extension}
13151 @cindex @option{--ext} (@command{gnatfind})
13152 Specify an alternate ali file extension. The default is @code{ali} and other
13153 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13154 may be specified via this switch. Note that if this switch overrides the
13155 default, which means that only the new extension will be considered.
13157 @item --RTS=@var{rts-path}
13158 @cindex @option{--RTS} (@command{gnatfind})
13159 Specifies the default location of the runtime library. Same meaning as the
13160 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13162 @item -d
13163 @cindex @option{-d} (@code{gnatfind})
13164 If this switch is set, then @code{gnatfind} will output the parent type
13165 reference for each matching derived types.
13167 @item -e
13168 @cindex @option{-e} (@command{gnatfind})
13169 By default, @code{gnatfind} accept the simple regular expression set for
13170 @samp{pattern}. If this switch is set, then the pattern will be
13171 considered as full Unix-style regular expression.
13173 @item -f
13174 @cindex @option{-f} (@command{gnatfind})
13175 If this switch is set, the output file names will be preceded by their
13176 directory (if the file was found in the search path). If this switch is
13177 not set, the directory will not be printed.
13179 @item -g
13180 @cindex @option{-g} (@command{gnatfind})
13181 If this switch is set, information is output only for library-level
13182 entities, ignoring local entities. The use of this switch may accelerate
13183 @code{gnatfind} and @code{gnatxref}.
13185 @item -IDIR
13186 @cindex @option{-IDIR} (@command{gnatfind})
13187 Equivalent to @samp{-aODIR -aIDIR}.
13189 @item -pFILE
13190 @cindex @option{-pFILE} (@command{gnatfind})
13191 Specify a project file (@pxref{GNAT Project Manager}) to use.
13192 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13193 project file in the current directory.
13195 If a project file is either specified or found by the tools, then the content
13196 of the source directory and object directory lines are added as if they
13197 had been specified respectively by @samp{-aI} and
13198 @samp{-aO}.
13200 @item -r
13201 @cindex @option{-r} (@command{gnatfind})
13202 By default, @code{gnatfind} will output only the information about the
13203 declaration, body or type completion of the entities. If this switch is
13204 set, the @code{gnatfind} will locate every reference to the entities in
13205 the files specified on the command line (or in every file in the search
13206 path if no file is given on the command line).
13208 @item -s
13209 @cindex @option{-s} (@command{gnatfind})
13210 If this switch is set, then @code{gnatfind} will output the content
13211 of the Ada source file lines were the entity was found.
13213 @item -t
13214 @cindex @option{-t} (@command{gnatfind})
13215 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13216 the specified type. It act like -d option but recursively from parent
13217 type to parent type. When this switch is set it is not possible to
13218 specify more than one file.
13220 @end table
13222 @noindent
13223 All these switches may be in any order on the command line, and may even
13224 appear after the file names. They need not be separated by spaces, thus
13225 you can say @samp{gnatxref -ag} instead of
13226 @samp{gnatxref -a -g}.
13228 As stated previously, gnatfind will search in every directory in the
13229 search path. You can force it to look only in the current directory if
13230 you specify @code{*} at the end of the command line.
13232 @node Project Files for gnatxref and gnatfind
13233 @section Project Files for @command{gnatxref} and @command{gnatfind}
13235 @noindent
13236 Project files allow a programmer to specify how to compile its
13237 application, where to find sources, etc.  These files are used
13238 primarily by GPS, but they can also be used
13239 by the two tools
13240 @code{gnatxref} and @code{gnatfind}.
13242 A project file name must end with @file{.gpr}. If a single one is
13243 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13244 extract the information from it. If multiple project files are found, none of
13245 them is read, and you have to use the @samp{-p} switch to specify the one
13246 you want to use.
13248 The following lines can be included, even though most of them have default
13249 values which can be used in most cases.
13250 The lines can be entered in any order in the file.
13251 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13252 each line. If you have multiple instances, only the last one is taken into
13253 account.
13255 @table @code
13256 @item src_dir=DIR
13257 [default: @code{"./"}]
13258 specifies a directory where to look for source files. Multiple @code{src_dir}
13259 lines can be specified and they will be searched in the order they
13260 are specified.
13262 @item obj_dir=DIR
13263 [default: @code{"./"}]
13264 specifies a directory where to look for object and library files. Multiple
13265 @code{obj_dir} lines can be specified, and they will be searched in the order
13266 they are specified
13268 @item comp_opt=SWITCHES
13269 [default: @code{""}]
13270 creates a variable which can be referred to subsequently by using
13271 the @code{$@{comp_opt@}} notation. This is intended to store the default
13272 switches given to @command{gnatmake} and @command{gcc}.
13274 @item bind_opt=SWITCHES
13275 [default: @code{""}]
13276 creates a variable which can be referred to subsequently by using
13277 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13278 switches given to @command{gnatbind}.
13280 @item link_opt=SWITCHES
13281 [default: @code{""}]
13282 creates a variable which can be referred to subsequently by using
13283 the @samp{$@{link_opt@}} notation. This is intended to store the default
13284 switches given to @command{gnatlink}.
13286 @item main=EXECUTABLE
13287 [default: @code{""}]
13288 specifies the name of the executable for the application. This variable can
13289 be referred to in the following lines by using the @samp{$@{main@}} notation.
13291 @item comp_cmd=COMMAND
13292 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13293 specifies the command used to compile a single file in the application.
13295 @item make_cmd=COMMAND
13296 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13297 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13298 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13299 specifies the command used to recompile the whole application.
13301 @item run_cmd=COMMAND
13302 [default: @code{"$@{main@}"}]
13303 specifies the command used to run the application.
13305 @item debug_cmd=COMMAND
13306 [default: @code{"gdb $@{main@}"}]
13307 specifies the command used to debug the application
13309 @end table
13311 @noindent
13312 @command{gnatxref} and @command{gnatfind} only take into account the
13313 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13315 @node Regular Expressions in gnatfind and gnatxref
13316 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13318 @noindent
13319 As specified in the section about @command{gnatfind}, the pattern can be a
13320 regular expression. Actually, there are to set of regular expressions
13321 which are recognized by the program:
13323 @table @code
13324 @item globbing patterns
13325 These are the most usual regular expression. They are the same that you
13326 generally used in a Unix shell command line, or in a DOS session.
13328 Here is a more formal grammar:
13329 @smallexample
13330 @group
13331 @iftex
13332 @leftskip=.5cm
13333 @end iftex
13334 regexp ::= term
13335 term   ::= elmt            -- matches elmt
13336 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13337 term   ::= *               -- any string of 0 or more characters
13338 term   ::= ?               -- matches any character
13339 term   ::= [char @{char@}]   -- matches any character listed
13340 term   ::= [char - char]   -- matches any character in range
13341 @end group
13342 @end smallexample
13344 @item full regular expression
13345 The second set of regular expressions is much more powerful. This is the
13346 type of regular expressions recognized by utilities such a @file{grep}.
13348 The following is the form of a regular expression, expressed in Ada
13349 reference manual style BNF is as follows
13351 @smallexample
13352 @iftex
13353 @leftskip=.5cm
13354 @end iftex
13355 @group
13356 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
13358 term ::= item @{item@}       -- concatenation (item then item)
13360 item ::= elmt              -- match elmt
13361 item ::= elmt *            -- zero or more elmt's
13362 item ::= elmt +            -- one or more elmt's
13363 item ::= elmt ?            -- matches elmt or nothing
13364 @end group
13365 @group
13366 elmt ::= nschar            -- matches given character
13367 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13368 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
13369 elmt ::= [char - char]     -- matches chars in given range
13370 elmt ::= \ char            -- matches given character
13371 elmt ::= .                 -- matches any single character
13372 elmt ::= ( regexp )        -- parens used for grouping
13374 char ::= any character, including special characters
13375 nschar ::= any character except ()[].*+?^
13376 @end group
13377 @end smallexample
13379 Following are a few examples:
13381 @table @samp
13382 @item abcde|fghi
13383 will match any of the two strings @samp{abcde} and @samp{fghi},
13385 @item abc*d
13386 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13387 @samp{abcccd}, and so on,
13389 @item [a-z]+
13390 will match any string which has only lowercase characters in it (and at
13391 least one character.
13393 @end table
13394 @end table
13396 @node Examples of gnatxref Usage
13397 @section Examples of @code{gnatxref} Usage
13399 @subsection General Usage
13401 @noindent
13402 For the following examples, we will consider the following units:
13404 @smallexample @c ada
13405 @group
13406 @cartouche
13407 main.ads:
13408 1: @b{with} Bar;
13409 2: @b{package} Main @b{is}
13410 3:     @b{procedure} Foo (B : @b{in} Integer);
13411 4:     C : Integer;
13412 5: @b{private}
13413 6:     D : Integer;
13414 7: @b{end} Main;
13416 main.adb:
13417 1: @b{package} @b{body} Main @b{is}
13418 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13419 3:     @b{begin}
13420 4:        C := B;
13421 5:        D := B;
13422 6:        Bar.Print (B);
13423 7:        Bar.Print (C);
13424 8:     @b{end} Foo;
13425 9: @b{end} Main;
13427 bar.ads:
13428 1: @b{package} Bar @b{is}
13429 2:     @b{procedure} Print (B : Integer);
13430 3: @b{end} bar;
13431 @end cartouche
13432 @end group
13433 @end smallexample
13435 @table @code
13437 @noindent
13438 The first thing to do is to recompile your application (for instance, in
13439 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13440 the cross-referencing information.
13441 You can then issue any of the following commands:
13443 @item gnatxref main.adb
13444 @code{gnatxref} generates cross-reference information for main.adb
13445 and every unit 'with'ed by main.adb.
13447 The output would be:
13448 @smallexample
13449 @iftex
13450 @leftskip=0cm
13451 @end iftex
13452 B                                                      Type: Integer
13453   Decl: bar.ads           2:22
13454 B                                                      Type: Integer
13455   Decl: main.ads          3:20
13456   Body: main.adb          2:20
13457   Ref:  main.adb          4:13     5:13     6:19
13458 Bar                                                    Type: Unit
13459   Decl: bar.ads           1:9
13460   Ref:  main.adb          6:8      7:8
13461        main.ads           1:6
13462 C                                                      Type: Integer
13463   Decl: main.ads          4:5
13464   Modi: main.adb          4:8
13465   Ref:  main.adb          7:19
13466 D                                                      Type: Integer
13467   Decl: main.ads          6:5
13468   Modi: main.adb          5:8
13469 Foo                                                    Type: Unit
13470   Decl: main.ads          3:15
13471   Body: main.adb          2:15
13472 Main                                                    Type: Unit
13473   Decl: main.ads          2:9
13474   Body: main.adb          1:14
13475 Print                                                   Type: Unit
13476   Decl: bar.ads           2:15
13477   Ref:  main.adb          6:12     7:12
13478 @end smallexample
13480 @noindent
13481 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13482 its body is in main.adb, line 1, column 14 and is not referenced any where.
13484 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13485 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13487 @item gnatxref package1.adb package2.ads
13488 @code{gnatxref} will generates cross-reference information for
13489 package1.adb, package2.ads and any other package 'with'ed by any
13490 of these.
13492 @end table
13494 @subsection Using gnatxref with vi
13496 @code{gnatxref} can generate a tags file output, which can be used
13497 directly from @command{vi}. Note that the standard version of @command{vi}
13498 will not work properly with overloaded symbols. Consider using another
13499 free implementation of @command{vi}, such as @command{vim}.
13501 @smallexample
13502 $ gnatxref -v gnatfind.adb > tags
13503 @end smallexample
13505 @noindent
13506 will generate the tags file for @code{gnatfind} itself (if the sources
13507 are in the search path!).
13509 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13510 (replacing @var{entity} by whatever you are looking for), and vi will
13511 display a new file with the corresponding declaration of entity.
13513 @node Examples of gnatfind Usage
13514 @section Examples of @code{gnatfind} Usage
13516 @table @code
13518 @item gnatfind -f xyz:main.adb
13519 Find declarations for all entities xyz referenced at least once in
13520 main.adb. The references are search in every library file in the search
13521 path.
13523 The directories will be printed as well (as the @samp{-f}
13524 switch is set)
13526 The output will look like:
13527 @smallexample
13528 directory/main.ads:106:14: xyz <= declaration
13529 directory/main.adb:24:10: xyz <= body
13530 directory/foo.ads:45:23: xyz <= declaration
13531 @end smallexample
13533 @noindent
13534 that is to say, one of the entities xyz found in main.adb is declared at
13535 line 12 of main.ads (and its body is in main.adb), and another one is
13536 declared at line 45 of foo.ads
13538 @item gnatfind -fs xyz:main.adb
13539 This is the same command as the previous one, instead @code{gnatfind} will
13540 display the content of the Ada source file lines.
13542 The output will look like:
13544 @smallexample
13545 directory/main.ads:106:14: xyz <= declaration
13546    procedure xyz;
13547 directory/main.adb:24:10: xyz <= body
13548    procedure xyz is
13549 directory/foo.ads:45:23: xyz <= declaration
13550    xyz : Integer;
13551 @end smallexample
13553 @noindent
13554 This can make it easier to find exactly the location your are looking
13555 for.
13557 @item gnatfind -r "*x*":main.ads:123 foo.adb
13558 Find references to all entities containing an x that are
13559 referenced on line 123 of main.ads.
13560 The references will be searched only in main.ads and foo.adb.
13562 @item gnatfind main.ads:123
13563 Find declarations and bodies for all entities that are referenced on
13564 line 123 of main.ads.
13566 This is the same as @code{gnatfind "*":main.adb:123}.
13568 @item gnatfind mydir/main.adb:123:45
13569 Find the declaration for the entity referenced at column 45 in
13570 line 123 of file main.adb in directory mydir. Note that it
13571 is usual to omit the identifier name when the column is given,
13572 since the column position identifies a unique reference.
13574 The column has to be the beginning of the identifier, and should not
13575 point to any character in the middle of the identifier.
13577 @end table
13579 @ifclear FSFEDITION
13580 @c *********************************
13581 @node The GNAT Pretty-Printer gnatpp
13582 @chapter The GNAT Pretty-Printer @command{gnatpp}
13583 @findex gnatpp
13584 @cindex Pretty-Printer
13586 @menu
13587 * Switches for gnatpp::
13588 * Formatting Rules::
13589 @end menu
13591 @noindent
13592 The @command{gnatpp} tool is an ASIS-based utility
13593 for source reformatting / pretty-printing.
13594 It takes an Ada source file as input and generates a reformatted
13595 version as output.
13596 You can specify various style directives via switches; e.g.,
13597 identifier case conventions, rules of indentation, and comment layout.
13599 Note: A newly-redesigned set of formatting algorithms used by gnatpp
13600 is now available.
13601 To invoke the old formatting algorithms, use the @option{--pp-old} switch.
13602 Support for @option{--pp-old} will be removed in some future version.
13604 To produce a reformatted file, @command{gnatpp} invokes the Ada
13605 compiler and generates and uses the ASIS tree for the input source;
13606 thus the input must be legal Ada code, and the tool should have all the
13607 information needed to compile the input source. To provide this information,
13608 you may specify as a tool parameter the project file the input source belongs to
13609 (or you may call @command{gnatpp}
13610 through the @command{gnat} driver (see @ref{The GNAT Driver and
13611 Project Files}). Another possibility is to specify the source search
13612 path and needed configuration files in @option{-cargs} section of @command{gnatpp}
13613 call, see the description of the @command{gnatpp} switches below.
13615 @command{gnatpp} cannot process sources that contain
13616 preprocessing directives.
13618 The @command{gnatpp} command has the form
13620 @smallexample
13621 @c $ gnatpp @ovar{switches} @var{filename}
13622 @c Expanding @ovar macro inline (explanation in macro def comments)
13623 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13624 @end smallexample
13626 @noindent
13627 where
13628 @itemize @bullet
13629 @item
13630 @var{switches} is an optional sequence of switches defining such properties as
13631 the formatting rules, the source search path, and the destination for the
13632 output source file
13634 @item
13635 @var{filename} is the name (including the extension) of the source file to
13636 reformat; wildcards or several file names on the same gnatpp command are
13637 allowed. The file name may contain path information; it does not have to
13638 follow the GNAT file naming rules
13640 @item
13641 @samp{@var{gcc_switches}} is a list of switches for
13642 @command{gcc}. They will be passed on to all compiler invocations made by
13643 @command{gnatpp} to generate the ASIS trees. Here you can provide
13644 @option{-I} switches to form the source search path,
13645 use the @option{-gnatec} switch to set the configuration file, etc.
13646 @end itemize
13648 @node Switches for gnatpp
13649 @section Switches for @command{gnatpp}
13651 @noindent
13652 The following subsections describe the various switches accepted by
13653 @command{gnatpp}, organized by category.
13655 You specify a switch by supplying a name and generally also a value.
13656 In many cases the values for a switch with a given name are incompatible with
13657 each other
13658 (for example the switch that controls the casing of a reserved word may have
13659 exactly one value: upper case, lower case, or
13660 mixed case) and thus exactly one such switch can be in effect for an
13661 invocation of @command{gnatpp}.
13662 If more than one is supplied, the last one is used.
13663 However, some values for the same switch are mutually compatible.
13664 You may supply several such switches to @command{gnatpp}, but then
13665 each must be specified in full, with both the name and the value.
13666 Abbreviated forms (the name appearing once, followed by each value) are
13667 not permitted.
13670 @menu
13671 * Alignment Control::
13672 * Casing Control::
13673 * General Text Layout Control::
13674 * Other Formatting Options::
13675 * Setting the Source Search Path::
13676 * Output File Control::
13677 * Other gnatpp Switches::
13678 @end menu
13680 @node Alignment Control
13681 @subsection Alignment Control
13682 @cindex Alignment control in @command{gnatpp}
13684 @noindent
13685 Programs can be easier to read if certain constructs are vertically aligned.
13686 By default alignment of the following constructs is set ON:
13687 @code{:} in declarations, @code{:=} in initializations in declarations
13688 @code{:=} in assignment statements, @code{=>} in associations, and
13689 @code{at} keywords in the component clauses in record
13690 representation clauses.
13692 @table @option
13693 @cindex @option{-A@var{n}} (@command{gnatpp})
13695 @item -A0
13696 Set alignment to OFF
13698 @item -A1
13699 Set alignment to ON
13700 @end table
13702 @node Casing Control
13703 @subsection Casing Control
13704 @cindex Casing control in @command{gnatpp}
13706 @noindent
13707 @command{gnatpp} allows you to specify the casing for reserved words,
13708 pragma names, attribute designators and identifiers.
13709 For identifiers you may define a
13710 general rule for name casing but also override this rule
13711 via a set of dictionary files.
13713 Three types of casing are supported: lower case, upper case, and mixed case.
13714 ``Mixed case'' means that the first letter, and also each letter immediately
13715 following an underscore, are converted to their uppercase forms;
13716 all the other letters are converted to their lowercase forms.
13718 @table @option
13719 @cindex @option{-a@var{x}} (@command{gnatpp})
13720 @item -aL
13721 Attribute designators are lower case
13723 @item -aU
13724 Attribute designators are upper case
13726 @item -aM
13727 Attribute designators are mixed case (this is the default)
13729 @cindex @option{-k@var{x}} (@command{gnatpp})
13730 @item -kL
13731 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13732 lower case (this is the default)
13734 @item -kU
13735 Keywords are upper case
13737 @cindex @option{-n@var{x}} (@command{gnatpp})
13738 @item -nD
13739 Name casing for defining occurrences are as they appear in the source file
13740 (this is the default)
13742 @item -nU
13743 Names are in upper case
13745 @item -nL
13746 Names are in lower case
13748 @item -nM
13749 Names are in mixed case
13751 @cindex @option{-ne@var{x}} (@command{gnatpp})
13752 @item -neD
13753 Enumeration literal casing for defining occurrences are as they appear in the
13754 source file. Overrides -n casing setting.
13756 @item -neU
13757 Enumeration literals are in upper case.  Overrides -n casing
13758 setting.
13760 @item -neL
13761 Enumeration literals are in lower case. Overrides -n casing
13762 setting.
13764 @item -neM
13765 Enumeration literals are in mixed case. Overrides -n casing
13766 setting.
13768 @cindex @option{-nt@var{x}} (@command{gnatpp})
13769 @item -neD
13770 Names introduced by type and subtype declarations are always
13771 cased as they appear in the declaration in the source file.
13772 Overrides -n casing setting.
13774 @item -ntU
13775 Names introduced by type and subtype declarations are always in
13776 upper case. Overrides -n casing setting.
13778 @item -ntL
13779 Names introduced by type and subtype declarations are always in
13780 lower case. Overrides -n casing setting.
13782 @item -ntM
13783 Names introduced by type and subtype declarations are always in
13784 mixed case. Overrides -n casing setting.
13786 @item -nnU
13787 Names introduced by number declarations are always in
13788 upper case. Overrides -n casing setting.
13790 @item -nnL
13791 Names introduced by number declarations are always in
13792 lower case. Overrides -n casing setting.
13794 @item -nnM
13795 Names introduced by number declarations are always in
13796 mixed case. Overrides -n casing setting.
13798 @cindex @option{-p@var{x}} (@command{gnatpp})
13799 @item -pL
13800 Pragma names are lower case
13802 @item -pU
13803 Pragma names are upper case
13805 @item -pM
13806 Pragma names are mixed case (this is the default)
13808 @item -D@var{file}
13809 @cindex @option{-D} (@command{gnatpp})
13810 Use @var{file} as a @emph{dictionary file} that defines
13811 the casing for a set of specified names,
13812 thereby overriding the effect on these names by
13813 any explicit or implicit
13814 -n switch.
13815 To supply more than one dictionary file,
13816 use several @option{-D} switches.
13818 @noindent
13819 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13820 to define the casing for the Ada predefined names and
13821 the names declared in the GNAT libraries.
13823 @item -D-
13824 @cindex @option{-D-} (@command{gnatpp})
13825 Do not use the default dictionary file;
13826 instead, use the casing
13827 defined by a @option{-n} switch and any explicit
13828 dictionary file(s)
13829 @end table
13831 @noindent
13832 The structure of a dictionary file, and details on the conventions
13833 used in the default dictionary file, are defined in @ref{Name Casing}.
13835 The @option{-D-} and
13836 @option{-D@var{file}} switches are mutually
13837 compatible.
13839 @noindent
13840 This group of @command{gnatpp} switches controls the layout of comments and
13841 complex syntactic constructs.  See @ref{Formatting Comments} for details
13842 on their effect.
13844 @table @option
13845 @cindex @option{-c@var{n}} (@command{gnatpp})
13846 @item -c0
13847 All comments remain unchanged.
13849 @item -c1
13850 GNAT-style comment line indentation.
13851 This is the default.
13853 @item -c3
13854 GNAT-style comment beginning.
13856 @item -c4
13857 Fill comment blocks.
13859 @item -c5
13860 Keep unchanged special form comments.
13861 This is the default.
13863 @item --comments-only
13864 @cindex @option{--comments-only} @command{gnatpp}
13865 Format just the comments.
13867 @cindex @option{--no-separate-is} (@command{gnatpp})
13868 @item --no-separate-is
13869 Do not place the keyword @code{is} on a separate line in a subprogram body in
13870 case if the spec occupies more than one line.
13872 @cindex @option{--separate-loop-then} (@command{gnatpp})
13873 @item --separate-loop-then
13874 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13875 keyword @code{then} in IF statements on a separate line.
13877 @cindex @option{--no-separate-loop-then} (@command{gnatpp})
13878 @item --no-separate-loop-then
13879 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13880 keyword @code{then} in IF statements on a separate line. This option is
13881 incompatible with @option{--separate-loop-then} option.
13883 @cindex @option{--use-on-new-line} (@command{gnatpp})
13884 @item --use-on-new-line
13885 Start each USE clause in a context clause from a separate line.
13887 @cindex @option{--insert-blank-lines} (@command{gnatpp})
13888 @item --insert-blank-lines
13889 Insert blank lines where appropriate (between bodies and other large
13890 constructs).
13892 @cindex @option{--preserve-blank-lines} (@command{gnatpp})
13893 @item --preserve-blank-lines
13894 Preserve blank lines in the input. By default, gnatpp will squeeze
13895 multiple blank lines down to one.
13897 @end table
13899 @noindent
13900 The @option{-c} switches are compatible with one another, except that
13901 the @option{-c0} switch disables all other comment formatting
13902 switches.
13905 @node General Text Layout Control
13906 @subsection General Text Layout Control
13908 @noindent
13909 These switches allow control over line length and indentation.
13911 @table @option
13912 @item -M@var{nnn}
13913 @cindex @option{-M} (@command{gnatpp})
13914 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13916 @item -i@var{nnn}
13917 @cindex @option{-i} (@command{gnatpp})
13918 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13920 @item -cl@var{nnn}
13921 @cindex @option{-cl} (@command{gnatpp})
13922 Indentation level for continuation lines (relative to the line being
13923 continued), @var{nnn} from 1@dots{}9.
13924 The default
13925 value is one less than the (normal) indentation level, unless the
13926 indentation is set to 1 (in which case the default value for continuation
13927 line indentation is also 1)
13928 @end table
13930 @node Other Formatting Options
13931 @subsection Other Formatting Options
13933 @noindent
13934 These switches control other formatting not listed above.
13936 @table @option
13937 @item --decimal-grouping=@var{n}
13938 @cindex @option{--decimal-grouping} @command{gnatpp}
13939 Put underscores in decimal literals (numeric literals without a base)
13940 every @var{n} characters. If a literal already has one or more
13941 underscores, it is not modified. For example, with
13942 @code{--decimal-grouping=3}, @code{1000000} will be changed to
13943 @code{1_000_000}.
13945 @item --based-grouping=@var{n}
13946 @cindex @option{--based-grouping} @command{gnatpp}
13947 Same as @code{--decimal-grouping}, but for based literals. For
13948 example, with @code{--based-grouping=4}, @code{16#0001FFFE#} will be
13949 changed to @code{16#0001_FFFE#}.
13951 @item --RM-style-spacing
13952 @cindex @option{--RM-style-spacing} (@command{gnatpp})
13953 Do not insert an extra blank before various occurrences of
13954 `(' and `:'. This also turns off alignment.
13956 @item -ff
13957 @cindex @option{-ff} (@command{gnatpp})
13958 Insert a Form Feed character after a pragma Page.
13960 @item --call_threshold=@var{nnn}
13961 @cindex @option{--call_threshold} (@command{gnatpp})
13962 If the number of parameter associations is greater than @var{nnn} and if at
13963 least one association uses named notation, start each association from
13964 a new line. If @var{nnn} is 0, no check for the number of associations
13965 is made; this is the default.
13967 @item --par_threshold=@var{nnn}
13968 @cindex @option{--par_threshold} (@command{gnatpp})
13969 If the number of parameter specifications is greater than @var{nnn}
13970 (or equal to @var{nnn} in case of a function), start each specification from
13971 a new line. This feature is disabled by default.
13972 @end table
13974 @node Setting the Source Search Path
13975 @subsection Setting the Source Search Path
13977 @noindent
13978 To define the search path for the input source file, @command{gnatpp}
13979 uses the same switches as the GNAT compiler, with the same effects:
13981 @table @option
13982 @item -I@var{dir}
13983 @cindex @option{-I} (@command{gnatpp})
13985 @item -I-
13986 @cindex @option{-I-} (@command{gnatpp})
13988 @item -gnatec=@var{path}
13989 @cindex @option{-gnatec} (@command{gnatpp})
13991 @item --RTS=@var{path}
13992 @cindex @option{--RTS} (@command{gnatpp})
13994 @end table
13996 @node Output File Control
13997 @subsection Output File Control
13999 @noindent
14000 By default the output is sent to a file whose name is obtained by appending
14001 the @file{.pp} suffix to the name of the input file.
14002 If the file with this name already exists, it is overwritten.
14003 Thus if the input file is @file{my_ada_proc.adb} then
14004 @command{gnatpp} will produce @file{my_ada_proc.adb.pp}
14005 as output file.
14006 The output may be redirected by the following switches:
14008 @table @option
14009 @item --output-dir=@var{dir}
14010 @cindex @option{--output-dir} (@command{gnatpp})
14011 Generate output file in directory @file{dir} with the same name as the input
14012 file. If @file{dir} is the same as the directory containing the input file,
14013 the input file is not processed; use @option{-rnb}
14014 if you want to update the input file in place.
14016 @item -pipe
14017 @cindex @option{-pipe} (@command{gnatpp})
14018 Send the output to @code{Standard_Output}
14020 @item -o @var{output_file}
14021 @cindex @option{-o} (@code{gnatpp})
14022 Write the output into @var{output_file}.
14023 If @var{output_file} already exists, @command{gnatpp} terminates without
14024 reading or processing the input file.
14026 @item -of @var{output_file}
14027 @cindex @option{-of} (@command{gnatpp})
14028 Write the output into @var{output_file}, overwriting the existing file
14029 (if one is present).
14031 @item -r
14032 @cindex @option{-r} (@command{gnatpp})
14033 Replace the input source file with the reformatted output, and copy the
14034 original input source into the file whose name is obtained by appending the
14035 @file{.npp} suffix to the name of the input file.
14036 If a file with this name already exists, @command{gnatpp} terminates without
14037 reading or processing the input file.
14039 @item -rf
14040 @cindex @option{-rf} (@code{gnatpp})
14041 Like @option{-r} except that if the file with the specified name
14042 already exists, it is overwritten.
14044 @item -rnb
14045 @cindex @option{-rnb} (@command{gnatpp})
14046 Replace the input source file with the reformatted output without
14047 creating any backup copy of the input source.
14049 @item --eol=@var{xxx}
14050 @cindex @option{--eol} (@code{gnatpp})
14051 Specifies the line-ending style of the reformatted output file. The @var{xxx}
14052 string specified with the switch may be:
14053 @itemize @bullet
14054 @item ``@option{dos}'' MS DOS style, lines end with CR LF characters
14055 @item ``@option{crlf}''
14056 the same as @option{dos}
14057 @item ``@option{unix}'' UNIX style, lines end with LF character
14058 @item ``@option{lf}''
14059 the same as @option{unix}
14060 @end itemize
14062 @item -W@var{e}
14063 @cindex @option{-W} (@command{gnatpp})
14064 Specify the wide character encoding method for the input and output files.
14065 @var{e} is one of the following:
14067 @itemize @bullet
14069 @item h
14070 Hex encoding
14072 @item u
14073 Upper half encoding
14075 @item s
14076 Shift/JIS encoding
14078 @item e
14079 EUC encoding
14081 @item 8
14082 UTF-8 encoding
14084 @item b
14085 Brackets encoding (default value)
14086 @end itemize
14088 @end table
14090 @noindent
14091 Options @option{-o} and
14092 @option{-of} are allowed only if the call to gnatpp
14093 contains only one file to reformat.
14094 Option
14095 @option{--eol}
14097 @option{-W}
14098 cannot be used together
14099 with @option{-pipe} option.
14101 @node Other gnatpp Switches
14102 @subsection Other @code{gnatpp} Switches
14104 @noindent
14105 The additional @command{gnatpp} switches are defined in this subsection.
14107 @table @option
14108 @item --version
14109 @cindex @option{--version} @command{gnatpp}
14110 Display copyright and version, then exit disregarding all other options.
14112 @item --help
14113 @cindex @option{--help} @command{gnatpp}
14114 Display usage, then exit disregarding all other options.
14116 @item -P @var{file}
14117 @cindex @option{-P} @command{gnatpp}
14118 Indicates the name of the project file that describes the set of sources
14119 to be processed. The exact set of argument sources depends on other options
14120 specified; see below.
14122 @item -U
14123 @cindex @option{-U} @command{gnatpp}
14124 If a project file is specified and no argument source is explicitly
14125 specified (either directly or by means of @option{-files} option), process
14126 all the units of the closure of the argument project. Otherwise this option
14127 has no effect.
14129 @item -U @var{main_unit}
14130 If a project file is specified and no argument source is explicitly
14131 specified (either directly or by means of @option{-files} option), process
14132 the closure of units rooted at @var{main_unit}. Otherwise this option
14133 has no effect.
14135 @item -X@var{name}=@var{value}
14136 @cindex @option{-X} @command{gnatpp}
14137 Indicates that external variable @var{name} in the argument project
14138 has the value @var{value}. Has no effect if no project is specified as
14139 tool argument.
14141 @item --incremental
14142 @cindex @option{--incremental} @command{gnatpp}
14143 Incremental processing on a per-file basis. Source files are only
14144 processed if they have been modified, or if files they depend on have
14145 been modified. This is similar to the way gnatmake/gprbuild only
14146 compiles files that need to be recompiled. A project file is required
14147 in this mode, and the gnat driver (as in @command{gnat pretty}) is not
14148 supported.
14150 @item --pp-off=@var{xxx}
14151 @cindex @option{--pp-off} @command{gnatpp}
14152 Use @code{--xxx} as the command to turn off pretty printing, instead
14153 of the default @code{--!pp off}.
14155 @item --pp-on=@var{xxx}
14156 @cindex @option{--pp-on} @command{gnatpp}
14157 Use @code{--xxx} as the command to turn pretty printing back on, instead
14158 of the default @code{--!pp on}.
14160 @item --pp-old
14161 @cindex @option{--pp-old} @command{gnatpp}
14162 Use the old formatting algorithms.
14164 @item -files @var{filename}
14165 @cindex @option{-files} (@code{gnatpp})
14166 Take the argument source files from the specified file. This file should be an
14167 ordinary text file containing file names separated by spaces or
14168 line breaks. You can use this switch more than once in the same call to
14169 @command{gnatpp}. You also can combine this switch with an explicit list of
14170 files.
14172 @item -j@var{n}
14173 @cindex @option{-j} (@command{gnatpp})
14174 Without @option{--incremental}, use @var{n} processes to carry out the
14175 tree creations (internal representations of the argument sources). On
14176 a multiprocessor machine this speeds up processing of big sets of
14177 argument sources. If @var{n} is 0, then the maximum number of parallel
14178 tree creations is the number of core processors on the platform. This
14179 option cannot be used together with @option{-r},
14180 @option{-rf} or
14181 @option{-rnb} option.
14183 With @option{--incremental}, use @var{n} @command{gnatpp} processes to
14184 perform pretty-printing in parallel. @var{n} = 0 means the same as
14185 above. In this case, @option{-r},
14186 @option{-rf} or
14187 @option{-rnb} options are allowed.
14189 @cindex @option{-t} (@command{gnatpp})
14190 @item -t
14191 Print out execution time.
14193 @item -v
14194 @cindex @option{-v} (@command{gnatpp})
14195 Verbose mode
14197 @item -q
14198 @cindex @option{-q} (@command{gnatpp})
14199 Quiet mode
14200 @end table
14202 @noindent
14203 If a project file is specified and no argument source is explicitly
14204 specified (either directly or by means of @option{-files} option), and no
14205 @option{-U} is specified, then the set of processed sources is
14206 all the immediate units of the argument project.
14209 @node Formatting Rules
14210 @section Formatting Rules
14212 @noindent
14213 The following subsections show how @command{gnatpp} treats white space,
14214 comments, program layout, and name casing.
14215 They provide detailed descriptions of the switches shown above.
14217 @menu
14218 * Disabling Pretty Printing::
14219 * White Space and Empty Lines::
14220 * Formatting Comments::
14221 * Name Casing::
14222 @end menu
14224 @node Disabling Pretty Printing
14225 @subsection Disabling Pretty Printing
14227 @noindent
14228 Pretty printing is highly heuristic in nature, and sometimes doesn't
14229 do exactly what you want. If you wish to format a certain region of
14230 code by hand, you can turn off pretty printing in that region by
14231 surrounding it with special comments that start with @code{--!pp off}
14232 and @code{--!pp on}. The text in that region will then be reproduced
14233 verbatim in the output with no formatting.
14235 To disable pretty printing for the whole file, put @code{--!pp off} at
14236 the top, with no following @code{--!pp on}.
14238 The comments must appear on a line by themselves, with nothing
14239 preceding except spaces. The initial text of the comment must be
14240 exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14241 be followed by arbitrary additional text. For example:
14243 @smallexample @c ada
14244 @cartouche
14245 @b{package} Interrupts @b{is}
14246    --@i{!pp off -- turn off pretty printing so "Interrupt_Kind" lines up}
14247    @b{type}            Interrupt_Kind @b{is}
14248      (Asynchronous_Interrupt_Kind,
14249        Synchronous_Interrupt_Kind,
14250              Green_Interrupt_Kind);
14251    --@i{!pp on -- reenable pretty printing}
14253    ...
14254 @end cartouche
14255 @end smallexample
14257 You can specify different comment strings using the @code{--pp-off}
14258 and @code{--pp-on} switches. For example, if you say @code{gnatpp
14259 --pp-off=' pp-' *.ad?} then gnatpp will recognize comments of the form
14260 @code{-- pp-} instead of @code{--!pp off} for disabling pretty
14261 printing. Note that the leading @code{--} of the comment is not
14262 included in the argument to these switches.
14264 @node White Space and Empty Lines
14265 @subsection White Space and Empty Lines
14267 @noindent
14268 @command{gnatpp} does not have an option to control space characters.
14269 It will add or remove spaces according to the style illustrated by the
14270 examples in the @cite{Ada Reference Manual}.
14271 The output file will contain no lines with trailing white space.
14273 By default, a sequence of one or more blank lines in the input is
14274 converted to a single blank line in the output; multiple blank lines
14275 are squeezed down to one.
14276 The @option{--preserve-blank-lines} option
14277 turns off the squeezing; each blank line in the input is copied
14278 to the output.
14279 The @option{--insert-blank-lines} option
14280 causes additional blank lines to be inserted if not already
14281 present in the input (e.g. between bodies).
14283 @node Formatting Comments
14284 @subsection Formatting Comments
14286 @noindent
14287 Comments in Ada code are of two kinds:
14288 @itemize @bullet
14289 @item
14290 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14291 white space) on a line
14293 @item
14294 an @emph{end-of-line comment}, which follows some other Ada code on
14295 the same line.
14296 @end itemize
14298 @noindent
14299 A whole-line comment is indented according to the surrounding code,
14300 with some exceptions.
14301 Comments that start in column 1 are kept there.
14302 If possible, comments are not moved so far to the right that the maximum
14303 line length is exceeded.
14304 The @option{-c0} option
14305 turns off comment formatting.
14306 Special-form comments such as SPARK-style @code{--#...} are left alone.
14308 For an end-of-line comment, @command{gnatpp} tries to leave the same
14309 number of spaces between the end of the preceding Ada code and the
14310 beginning of the comment as appear in the original source.
14312 @noindent
14313 The @option{-c3} switch
14314 (GNAT style comment beginning) has the following
14315 effect:
14317 @itemize @bullet
14318 @item
14319 For each whole-line comment that does not end with two hyphens,
14320 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14321 to ensure that there are at least two spaces between these hyphens and the
14322 first non-blank character of the comment.
14323 @end itemize
14325 @noindent
14326 The @option{-c4} switch specifies that
14327 whole-line comments that form a paragraph will be filled in typical
14328 word processor style (that is, moving words between lines to make the
14329 lines other than the last similar in length ).
14331 @noindent
14332 The @option{--comments-only} switch specifies that only the comments
14333 are formatted; the rest of the program text is left alone. The
14334 comments are formatted according to the -c3 and -c4 switches; other
14335 formatting switches are ignored. For example, @option{--comments-only
14336 -c4} means to fill comment paragraphs, and do nothing else. Likewise,
14337 @option{--comments-only -c3} ensures comments start with at least two
14338 spaces after @code{--}, and @option{--comments-only -c3 -c4} does
14339 both. If @option{--comments-only} is given without @option{-c3} or
14340 @option{-c4}, then gnatpp doesn't format anything.
14342 @node Name Casing
14343 @subsection Name Casing
14345 @noindent
14346 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14347 the same casing as the corresponding defining identifier.
14349 You control the casing for defining occurrences via the
14350 @option{-n} switch.
14351 With @option{-nD} (``as declared'', which is the default),
14352 defining occurrences appear exactly as in the source file
14353 where they are declared.
14354 The other values for this switch ---
14355 @option{-nU},
14356 @option{-nL},
14357 @option{-nM} ---
14358 result in
14359 upper, lower, or mixed case, respectively.
14360 If @command{gnatpp} changes the casing of a defining
14361 occurrence, it analogously changes the casing of all the
14362 usage occurrences of this name.
14364 If the defining occurrence of a name is not in the source compilation unit
14365 currently being processed by @command{gnatpp}, the casing of each reference to
14366 this name is changed according to the value of the @option{-n}
14367 switch (subject to the dictionary file mechanism described below).
14368 Thus @command{gnatpp} acts as though the @option{-n} switch
14369 had affected the
14370 casing for the defining occurrence of the name.
14372 The options
14373 @option{-a@var{x}},
14374 @option{-k@var{x}},
14375 @option{-ne@var{x}},
14376 @option{-nt@var{x}},
14377 @option{-nn@var{x}}, and
14378 @option{-p@var{x}}
14379 allow finer-grained control over casing for
14380 attributes, keywords, enumeration literals,
14381 types, named numbers and pragmas, respectively.
14382 @option{-nt@var{x}} covers subtypes and
14383 task and protected bodies as well.
14385 Some names may need to be spelled with casing conventions that are not
14386 covered by the upper-, lower-, and mixed-case transformations.
14387 You can arrange correct casing by placing such names in a
14388 @emph{dictionary file},
14389 and then supplying a @option{-D} switch.
14390 The casing of names from dictionary files overrides
14391 any @option{-n} switch.
14393 To handle the casing of Ada predefined names and the names from GNAT libraries,
14394 @command{gnatpp} assumes a default dictionary file.
14395 The name of each predefined entity is spelled with the same casing as is used
14396 for the entity in the @cite{Ada Reference Manual} (usually mixed case).
14397 The name of each entity in the GNAT libraries is spelled with the same casing
14398 as is used in the declaration of that entity.
14400 The @w{@option{-D-}} switch suppresses the use of
14401 the default dictionary file. Instead, the casing for predefined and
14402 GNAT-defined names will be established by the
14403 @option{-n} switch or explicit dictionary files. For
14404 example, by default the names @code{Ada.Text_IO} and
14405 @code{GNAT.OS_Lib} will appear as just shown, even in the presence of
14406 a @option{-nU} switch.  To ensure that even
14407 such names are rendered in uppercase, additionally supply the
14408 @w{@option{-D-}} switch (or else place these names
14409 in upper case in a dictionary file).
14411 A dictionary file is a plain text file; each line in this file can be
14412 either a blank line (containing only space characters), an Ada comment
14413 line, or the specification of exactly one @emph{casing schema}.
14415 A casing schema is a string that has the following syntax:
14417 @smallexample
14418 @cartouche
14419   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14421   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14422 @end cartouche
14423 @end smallexample
14425 @noindent
14426 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14427 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14429 The casing schema string can be followed by white space and/or an Ada-style
14430 comment; any amount of white space is allowed before the string.
14432 If a dictionary file is passed as
14433 the value of a @option{-D@var{file}} switch
14434 then for every
14435 simple name and every identifier, @command{gnatpp} checks if the dictionary
14436 defines the casing for the name or for some of its parts (the term ``subword''
14437 is used below to denote the part of a name which is delimited by ``_'' or by
14438 the beginning or end of the word and which does not contain any ``_'' inside):
14440 @itemize @bullet
14441 @item
14442 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14443 the casing defined by the dictionary; no subwords are checked for this word
14445 @item
14446 for every subword @command{gnatpp} checks if the dictionary contains the
14447 corresponding string of the form @code{*@var{simple_identifier}*},
14448 and if it does, the casing of this @var{simple_identifier} is used
14449 for this subword
14451 @item
14452 if the whole name does not contain any ``_'' inside, and if for this name
14453 the dictionary contains two entries - one of the form @var{identifier},
14454 and another - of the form *@var{simple_identifier}*, then the first one
14455 is applied to define the casing of this name
14457 @item
14458 if more than one dictionary file is passed as @command{gnatpp} switches, each
14459 dictionary adds new casing exceptions and overrides all the existing casing
14460 exceptions set by the previous dictionaries
14462 @item
14463 when @command{gnatpp} checks if the word or subword is in the dictionary,
14464 this check is not case sensitive
14465 @end itemize
14467 @noindent
14468 For example, suppose we have the following source to reformat:
14470 @smallexample @c ada
14471 @cartouche
14472 @b{procedure} test @b{is}
14473    name1 : integer := 1;
14474    name4_name3_name2 : integer := 2;
14475    name2_name3_name4 : Boolean;
14476    name1_var : Float;
14477 @b{begin}
14478    name2_name3_name4 := name4_name3_name2 > name1;
14479 @b{end};
14480 @end cartouche
14481 @end smallexample
14483 @noindent
14484 And suppose we have two dictionaries:
14486 @smallexample
14487 @cartouche
14488 @i{dict1:}
14489    NAME1
14490    *NaMe3*
14491    *Name1*
14492 @end cartouche
14494 @cartouche
14495 @i{dict2:}
14496   *NAME3*
14497 @end cartouche
14498 @end smallexample
14500 @noindent
14501 If @command{gnatpp} is called with the following switches:
14503 @smallexample
14504 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14505 @end smallexample
14507 @noindent
14508 then we will get the following name casing in the @command{gnatpp} output:
14510 @smallexample @c ada
14511 @cartouche
14512 @b{procedure} Test @b{is}
14513    NAME1             : Integer := 1;
14514    Name4_NAME3_Name2 : Integer := 2;
14515    Name2_NAME3_Name4 : Boolean;
14516    Name1_Var         : Float;
14517 @b{begin}
14518    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14519 @b{end} Test;
14520 @end cartouche
14521 @end smallexample
14522 @end ifclear
14524 @ifclear FSFEDITION
14525 @c *********************************
14526 @node The Ada-to-XML converter gnat2xml
14527 @chapter The Ada-to-XML converter @command{gnat2xml}
14528 @findex gnat2xml
14529 @cindex XML generation
14531 @noindent
14532 The @command{gnat2xml} tool is an ASIS-based utility that converts
14533 Ada source code into XML.
14535 @menu
14536 * Switches for gnat2xml::
14537 * Other Programs::
14538 * Structure of the XML::
14539 * Generating Representation Clauses::
14540 @end menu
14542 @node Switches for gnat2xml
14543 @section Switches for @command{gnat2xml}
14545 @noindent
14546 @command{gnat2xml} takes Ada source code as input, and produces XML
14547 that conforms to the schema.
14549 Usage:
14551 @smallexample
14552 gnat2xml [options] filenames [-files filename] [-cargs gcc_switches]
14553 @end smallexample
14555 @noindent
14556 options:
14557 @smallexample
14559 --help -- generate usage information and quit, ignoring all other options
14560 --version -- print version and quit, ignoring all other options
14562 -P @file{file} -- indicates the name of the project file that describes
14563       the set of sources to be processed. The exact set of argument
14564       sources depends on other options specified, see below.
14566 -U -- if a project file is specified and no argument source is explicitly
14567       specified, process all the units of the closure of the argument project.
14568       Otherwise this option has no effect.
14570 -U @var{main_unit} -- if a project file is specified and no argument source
14571       is explicitly specified (either directly or by means of @option{-files}
14572       option), process the closure of units rooted at @var{main_unit}.
14573       Otherwise this option has no effect.
14575 -X@var{name}=@var{value} -- indicates that external variable @var{name} in
14576       the argument project has the value @var{value}. Has no effect if no
14577       project is specified as tool argument.
14579 --incremental -- incremental processing on a per-file basis. Source files are
14580       only processed if they have been modified, or if files they depend
14581       on have been modified. This is similar to the way gnatmake/gprbuild
14582       only compiles files that need to be recompiled. A project file
14583       is required in this mode.
14585 -j@var{n} -- In @option{--incremental} mode, use @var{n} @command{gnat2xml}
14586       processes to perform XML generation in parallel. If @var{n} is 0, then
14587       the maximum number of parallel tree creations is the number of core
14588       processors on the platform.
14590 --output-dir=@var{dir} -- generate one .xml file for each Ada source file, in
14591       directory @file{dir}. (Default is to generate the XML to standard
14592       output.)
14594 -I <include-dir>
14595       directories to search for dependencies
14596       You can also set the ADA_INCLUDE_PATH environment variable for this.
14598 --compact -- debugging version, with interspersed source, and a more
14599       compact representation of "sloc". This version does not conform
14600       to any schema.
14602 --rep-clauses -- generate representation clauses (see ``Generating
14603       Representation Clauses'' below).
14605 -files=filename - the name of a text file containing a list
14606                   of Ada source files to process
14608 -q -- quiet
14609 -v -- verbose
14611 -cargs ... -- options to pass to gcc
14612 @end smallexample
14614 @noindent
14615 If a project file is specified and no argument source is explicitly
14616 specified, and no @option{-U} is specified, then the set of processed
14617 sources is all the immediate units of the argument project.
14619 Example:
14621 @smallexample
14622 gnat2xml -v -output-dir=xml-files *.ad[sb]
14623 @end smallexample
14625 @noindent
14626 The above will create *.xml files in the @file{xml-files} subdirectory.
14627 For example, if there is an Ada package Mumble.Dumble, whose spec and
14628 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
14629 the above will produce xml-files/mumble-dumble.ads.xml and
14630 xml-files/mumble-dumble.adb.xml.
14632 @node Other Programs
14633 @section Other Programs
14635 @noindent
14636 The distribution includes two other programs that are related to
14637 @command{gnat2xml}:
14639 @command{gnat2xsd} is the schema generator, which generates the schema
14640 to standard output, based on the structure of Ada as encoded by
14641 ASIS. You don't need to run @command{gnat2xsd} in order to use
14642 @command{gnat2xml}. To generate the schema, type:
14644 @smallexample
14645 gnat2xsd > ada-schema.xsd
14646 @end smallexample
14648 @noindent
14649 @command{gnat2xml} generates XML files that will validate against
14650 @file{ada-schema.xsd}.
14652 @command{xml2gnat} is a back-translator that translates the XML back
14653 into Ada source code. The Ada generated by @command{xml2gnat} has
14654 identical semantics to the original Ada code passed to
14655 @command{gnat2xml}. It is not textually identical, however --- for
14656 example, no attempt is made to preserve the original indentation.
14658 @node Structure of the XML
14659 @section Structure of the XML
14661 @noindent
14662 The primary documentation for the structure of the XML generated by
14663 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
14664 following documentation gives additional details needed to understand
14665 the schema and therefore the XML.
14667 The elements listed under Defining Occurrences, Usage Occurrences, and
14668 Other Elements represent the syntactic structure of the Ada program.
14669 Element names are given in lower case, with the corresponding element
14670 type Capitalized_Like_This. The element and element type names are
14671 derived directly from the ASIS enumeration type Flat_Element_Kinds,
14672 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
14673 removed. For example, the ASIS enumeration literal
14674 An_Assignment_Statement corresponds to the XML element
14675 assignment_statement of XML type Assignment_Statement.
14677 To understand the details of the schema and the corresponding XML, it is
14678 necessary to understand the ASIS standard, as well as the GNAT-specific
14679 extension to ASIS.
14681 A defining occurrence is an identifier (or character literal or operator
14682 symbol) declared by a declaration. A usage occurrence is an identifier
14683 (or ...) that references such a declared entity. For example, in:
14685 @smallexample
14686 type T is range 1..10;
14687 X, Y : constant T := 1;
14688 @end smallexample
14690 @noindent
14691 The first ``T'' is the defining occurrence of a type. The ``X'' is the
14692 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
14693 a usage occurrence referring to the defining occurrence of T.
14695 Each element has a 'sloc' (source location), and subelements for each
14696 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
14697 The types of subelements are as defined in the ASIS standard. For
14698 example, for the right-hand side of an assignment_statement we have
14699 the following comment in asis-statements.ads:
14701 @smallexample
14702 ------------------------------------------------------------------------------
14703 --  18.3  function Assignment_Expression
14704 ------------------------------------------------------------------------------
14706    function Assignment_Expression
14707      (Statement : Asis.Statement)
14708       return      Asis.Expression;
14710 ------------------------------------------------------------------------------
14712 --  Returns the expression from the right hand side of the assignment.
14714 --  Returns Element_Kinds:
14715 --       An_Expression
14716 @end smallexample
14718 @noindent
14719 The corresponding sub-element of type Assignment_Statement is:
14721 @smallexample
14722 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
14723 @end smallexample
14725 @noindent
14726 where Expression_Class is defined by an xsd:choice of all the
14727 various kinds of expression.
14729 The 'sloc' of each element indicates the starting and ending line and
14730 column numbers. Column numbers are character counts; that is, a tab
14731 counts as 1, not as however many spaces it might expand to.
14733 Subelements of type Element have names ending in ``_q'' (for ASIS
14734 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
14735 List'').
14737 Some subelements are ``Boolean''. For example, Private_Type_Definition
14738 has has_abstract_q and has_limited_q, to indicate whether those
14739 keywords are present, as in @code{type T is abstract limited
14740 private;}. False is represented by a Nil_Element. True is represented
14741 by an element type specific to that query (for example, Abstract and
14742 Limited).
14744 The root of the tree is a Compilation_Unit, with attributes:
14746 @itemize @bullet
14747 @item
14748 unit_kind, unit_class, and unit_origin. These are strings that match the
14749 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
14750 in package Asis.
14752 @item
14753 unit_full_name is the full expanded name of the unit, starting from a
14754 root library unit. So for @code{package P.Q.R is ...},
14755 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
14757 @item
14758 def_name is the same as unit_full_name for library units; for subunits,
14759 it is just the simple name.
14761 @item
14762 source_file is the name of the Ada source file. For example, for
14763 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
14764 interpret the source locations --- the ``sloc'' of all elements
14765 within this Compilation_Unit refers to line and column numbers
14766 within the named file.
14767 @end itemize
14769 @noindent
14770 Defining occurrences have these attributes:
14772 @itemize @bullet
14773 @item
14774 def_name is the simple name of the declared entity, as written in the Ada
14775 source code.
14777 @item
14778 def is a unique URI of the form:
14780  ada://kind/fully/qualified/name
14782 where:
14784  kind indicates the kind of Ada entity being declared (see below), and
14786  fully/qualified/name, is the fully qualified name of the Ada
14787  entity, with each of ``fully'', ``qualified'', and ``name'' being
14788  mangled for uniqueness. We do not document the mangling
14789  algorithm, which is subject to change; we just guarantee that the
14790  names are unique in the face of overloading.
14792 @item
14793 type is the type of the declared object, or @code{null} for
14794 declarations of things other than objects.
14795 @end itemize
14797 @noindent
14798 Usage occurrences have these attributes:
14800 @itemize @bullet
14801 @item
14802 ref_name is the same as the def_name of the corresponding defining
14803 occurrence. This attribute is not of much use, because of
14804 overloading; use ref for lookups, instead.
14806 @item
14807 ref is the same as the def of the corresponding defining
14808 occurrence.
14809 @end itemize
14811 @noindent
14812 In summary, @code{def_name} and @code{ref_name} are as in the source
14813 code of the declaration, possibly overloaded, whereas @code{def} and
14814 @code{ref} are unique-ified.
14816 Literal elements have this attribute:
14818 @itemize @bullet
14819 @item
14820 lit_val is the value of the literal as written in the source text,
14821 appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
14822 only to numeric and string literals. Enumeration literals in Ada are
14823 not really "literals" in the usual sense; they are usage occurrences,
14824 and have ref_name and ref as described above. Note also that string
14825 literals used as operator symbols are treated as defining or usage
14826 occurrences, not as literals.
14827 @end itemize
14829 @noindent
14830 Elements that can syntactically represent names and expressions (which
14831 includes usage occurrences, plus function calls and so forth) have this
14832 attribute:
14834 @itemize @bullet
14835 @item
14836 type. If the element represents an expression or the name of an object,
14837 'type' is the 'def' for the defining occurrence of the type of that
14838 expression or name. Names of other kinds of entities, such as package
14839 names and type names, do not have a type in Ada; these have type="null"
14840 in the XML.
14841 @end itemize
14843 @noindent
14844 Pragma elements have this attribute:
14846 @itemize @bullet
14847 @item
14848 pragma_name is the name of the pragma. For language-defined pragmas, the
14849 pragma name is redundant with the element kind (for example, an
14850 assert_pragma element necessarily has pragma_name="Assert"). However, all
14851 implementation-defined pragmas are lumped together in ASIS as a single
14852 element kind (for example, the GNAT-specific pragma Unreferenced is
14853 represented by an implementation_defined_pragma element with
14854 pragma_name="Unreferenced").
14855 @end itemize
14857 @noindent
14858 Defining occurrences of formal parameters and generic formal objects have this
14859 attribute:
14861 @itemize @bullet
14862 @item
14863 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
14864 @end itemize
14866 @noindent
14867 All elements other than Not_An_Element have this attribute:
14869 @itemize @bullet
14870 @item
14871 checks is a comma-separated list of run-time checks that are needed
14872 for that element. The possible checks are: do_accessibility_check,
14873 do_discriminant_check,do_division_check,do_length_check,
14874 do_overflow_check,do_range_check,do_storage_check,do_tag_check.
14875 @end itemize
14877 @noindent
14878 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
14879 enumeration type Flat_Declaration_Kinds, declared in
14880 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
14881 any trailing "_Declaration" or "_Specification" removed. Thus, the
14882 possible kinds are as follows:
14884 @smallexample
14885 ordinary_type
14886 task_type
14887 protected_type
14888 incomplete_type
14889 tagged_incomplete_type
14890 private_type
14891 private_extension
14892 subtype
14893 variable
14894 constant
14895 deferred_constant
14896 single_task
14897 single_protected
14898 integer_number
14899 real_number
14900 enumeration_literal
14901 discriminant
14902 component
14903 loop_parameter
14904 generalized_iterator
14905 element_iterator
14906 procedure
14907 function
14908 parameter
14909 procedure_body
14910 function_body
14911 return_variable
14912 return_constant
14913 null_procedure
14914 expression_function
14915 package
14916 package_body
14917 object_renaming
14918 exception_renaming
14919 package_renaming
14920 procedure_renaming
14921 function_renaming
14922 generic_package_renaming
14923 generic_procedure_renaming
14924 generic_function_renaming
14925 task_body
14926 protected_body
14927 entry
14928 entry_body
14929 entry_index
14930 procedure_body_stub
14931 function_body_stub
14932 package_body_stub
14933 task_body_stub
14934 protected_body_stub
14935 exception
14936 choice_parameter
14937 generic_procedure
14938 generic_function
14939 generic_package
14940 package_instantiation
14941 procedure_instantiation
14942 function_instantiation
14943 formal_object
14944 formal_type
14945 formal_incomplete_type
14946 formal_procedure
14947 formal_function
14948 formal_package
14949 formal_package_declaration_with_box
14950 @end smallexample
14952 @node Generating Representation Clauses
14953 @section Generating Representation Clauses
14955 @noindent
14956 If the @option{--rep-clauses} switch is given, @command{gnat2xml} will
14957 generate representation clauses for certain types showing the
14958 representation chosen by the compiler. The information is produced by
14959 the ASIS ``Data Decomposition'' facility --- see the
14960 @code{Asis.Data_Decomposition} package for details.
14962 Not all types are supported. For example, @code{Type_Model_Kind} must
14963 be @code{A_Simple_Static_Model}. Types declared within generic units
14964 have no representation. The clauses that are generated include
14965 @code{attribute_definition_clauses} for @code{Size} and
14966 @code{Component_Size}, as well as
14967 @code{record_representation_clauses}.
14969 There is no guarantee that the generated representation clauses could
14970 have actually come from legal Ada code; Ada has some restrictions that
14971 are not necessarily obeyed by the generated clauses.
14973 The representation clauses are surrounded by comment elements to
14974 indicate that they are automatically generated, something like this:
14976 @smallexample
14977 <comment text="--gen+">
14979 <attribute_definition_clause>
14981 <comment text="--gen-">
14983 @end smallexample
14985 @end ifclear
14987 @ifclear FSFEDITION
14988 @c *********************************
14989 @node The GNAT Metrics Tool gnatmetric
14990 @chapter The GNAT Metrics Tool @command{gnatmetric}
14991 @findex gnatmetric
14992 @cindex Metric tool
14994 @noindent
14995 The @command{gnatmetric} tool is an ASIS-based utility
14996 for computing various program metrics.
14997 It takes an Ada source file as input and generates a file containing the
14998 metrics data as output. Various switches control which
14999 metrics are computed and output.
15001 @menu
15002 * Switches for gnatmetric::
15003 @end menu
15005 To compute program metrics, @command{gnatmetric} invokes the Ada
15006 compiler and generates and uses the ASIS tree for the input source;
15007 thus the input must be legal Ada code, and the tool should have all the
15008 information needed to compile the input source. To provide this information,
15009 you may specify as a tool parameter the project file the input source belongs to
15010 (or you may call @command{gnatmetric}
15011 through the @command{gnat} driver (see @ref{The GNAT Driver and
15012 Project Files}). Another possibility is to specify the source search
15013 path and needed configuration files in @option{-cargs} section of @command{gnatmetric}
15014 call, see the description of the @command{gnatmetric} switches below.
15016 If the set of sources to be processed by @code{gnatmetric} contains sources with
15017 preprocessing directives
15018 then the needed options should be provided to run preprocessor as a part of
15019 the @command{gnatmetric} call, and the computed metrics
15020 will correspond to preprocessed sources.
15023 The @command{gnatmetric} command has the form
15025 @smallexample
15026 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15027 @c Expanding @ovar macro inline (explanation in macro def comments)
15028 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15029 @end smallexample
15031 @noindent
15032 where
15033 @itemize @bullet
15034 @item
15035 @var{switches} specify the metrics to compute and define the destination for
15036 the output
15038 @item
15039 Each @var{filename} is the name (including the extension) of a source
15040 file to process. ``Wildcards'' are allowed, and
15041 the file name may contain path information.
15042 If no @var{filename} is supplied, then the @var{switches} list must contain
15043 at least one
15044 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15045 Including both a @option{-files} switch and one or more
15046 @var{filename} arguments is permitted.
15048 @item
15049 @samp{@var{gcc_switches}} is a list of switches for
15050 @command{gcc}. They will be passed on to all compiler invocations made by
15051 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15052 @option{-I} switches to form the source search path,
15053 and use the @option{-gnatec} switch to set the configuration file,
15054 use the @option{-gnat05} switch if sources should be compiled in
15055 Ada 2005 mode etc.
15056 @end itemize
15058 @node Switches for gnatmetric
15059 @section Switches for @command{gnatmetric}
15061 @noindent
15062 The following subsections describe the various switches accepted by
15063 @command{gnatmetric}, organized by category.
15065 @menu
15066 * Output Files Control::
15067 * Disable Metrics For Local Units::
15068 * Specifying a set of metrics to compute::
15069 * Other gnatmetric Switches::
15070 @ignore
15071 * Generate project-wide metrics::
15072 @end ignore
15073 @end menu
15075 @node Output Files Control
15076 @subsection Output File Control
15077 @cindex Output file control in @command{gnatmetric}
15079 @noindent
15080 @command{gnatmetric} has two output formats. It can generate a
15081 textual (human-readable) form, and also XML. By default only textual
15082 output is generated.
15084 When generating the output in textual form, @command{gnatmetric} creates
15085 for each Ada source file a corresponding text file
15086 containing the computed metrics, except for the case when the set of metrics
15087 specified by gnatmetric parameters consists only of metrics that are computed
15088 for the whole set of analyzed sources, but not for each Ada source.
15089 By default, the name of the file containing metric information for a source
15090 is obtained by appending the @file{.metrix} suffix to the
15091 name of the input source file. If not otherwise specified and no project file
15092 is specified as @command{gnatmetric} option this file is placed in the same
15093 directory as where the source file is located. If @command{gnatmetric} has a
15094 project  file as its parameter, it places all the generated files in the
15095 object directory of the project (or in the project source directory if the
15096 project does not define an objects directory), if @option{--subdirs} option
15097 is specified, the files are placed in the subrirectory of this directory
15098 specified by this option.
15100 All the output information generated in XML format is placed in a single
15101 file. By default the name of this file is @file{metrix.xml}.
15102 If not otherwise specified and if no project file is specified
15103 as @command{gnatmetric} option  this file is placed in the
15104 current directory.
15106 Some of the computed metrics are summed over the units passed to
15107 @command{gnatmetric}; for example, the total number of lines of code.
15108 By default this information is sent to @file{stdout}, but a file
15109 can be specified with the @option{-og} switch.
15111 The following switches control the @command{gnatmetric} output:
15113 @table @option
15114 @cindex @option{-x} (@command{gnatmetric})
15115 @item -x
15116 Generate the XML output
15118 @cindex @option{-xs} (@command{gnatmetric})
15119 @item -xs
15120 Generate the XML output and the XML schema file that describes the structure
15121 of the XML metric report, this schema is assigned to the XML file. The schema
15122 file has the same name as the XML output file with @file{.xml} suffix replaced
15123 with @file{.xsd}
15125 @cindex @option{-nt} (@command{gnatmetric})
15126 @item -nt
15127 Do not generate the output in text form (implies @option{-x})
15129 @cindex @option{-d} (@command{gnatmetric})
15130 @item -d @var{output_dir}
15131 Put text files with detailed metrics into @var{output_dir}
15133 @cindex @option{-o} (@command{gnatmetric})
15134 @item -o @var{file_suffix}
15135 Use @var{file_suffix}, instead of @file{.metrix}
15136 in the name of the output file.
15138 @cindex @option{-og} (@command{gnatmetric})
15139 @item -og @var{file_name}
15140 Put global metrics into @var{file_name}
15142 @cindex @option{-ox} (@command{gnatmetric})
15143 @item -ox @var{file_name}
15144 Put the XML output into @var{file_name} (also implies @option{-x})
15146 @cindex @option{-sfn} (@command{gnatmetric})
15147 @item -sfn
15148 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15149 output includes the name(s) of the Ada source file(s) from which the metrics
15150 are computed.  By default each name includes the absolute path. The
15151 @option{-sfn} switch causes @command{gnatmetric}
15152 to exclude all directory information from the file names that are output.)
15154 @end table
15156 @node Disable Metrics For Local Units
15157 @subsection Disable Metrics For Local Units
15158 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15160 @noindent
15161 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15162 one compilation
15163 unit per one source file. It computes line metrics for the whole source
15164 file, and it also computes syntax
15165 and complexity metrics for the file's outermost unit.
15167 By default, @command{gnatmetric} will also compute all metrics for certain
15168 kinds of locally declared program units:
15170 @itemize @bullet
15171 @item
15172 subprogram (and generic subprogram) bodies;
15174 @item
15175 package (and generic package) specs and bodies;
15177 @item
15178 task object and type specifications and bodies;
15180 @item
15181 protected object and type specifications and bodies.
15182 @end itemize
15184 @noindent
15185 These kinds of entities will be referred to as
15186 @emph{eligible local program units}, or simply @emph{eligible local units},
15187 @cindex Eligible local unit (for @command{gnatmetric})
15188 in the discussion below.
15190 Note that a subprogram declaration, generic instantiation,
15191 or renaming declaration only receives metrics
15192 computation when it appear as the outermost entity
15193 in a source file.
15195 Suppression of metrics computation for eligible local units can be
15196 obtained via the following switch:
15198 @table @option
15199 @cindex @option{-nolocal} (@command{gnatmetric})
15200 @item -nolocal
15201 Do not compute detailed metrics for eligible local program units
15203 @end table
15205 @node Specifying a set of metrics to compute
15206 @subsection Specifying a set of metrics to compute
15208 @noindent
15209 By default all the metrics are computed and reported. The switches
15210 described in this subsection allow you to control, on an individual
15211 basis, whether metrics are computed and
15212 reported. If at least one positive metric
15213 switch is specified (that is, a switch that defines that a given
15214 metric or set of metrics is to be computed), then only
15215 explicitly specified metrics are reported.
15217 @menu
15218 * Line Metrics Control::
15219 * Syntax Metrics Control::
15220 * Complexity Metrics Control::
15221 * Coupling Metrics Control::
15222 @end menu
15224 @node Line Metrics Control
15225 @subsubsection Line Metrics Control
15226 @cindex Line metrics control in @command{gnatmetric}
15228 @noindent
15229 For any (legal) source file, and for each of its
15230 eligible local program units, @command{gnatmetric} computes the following
15231 metrics:
15233 @itemize @bullet
15234 @item
15235 the total number of lines;
15237 @item
15238 the total number of code lines (i.e., non-blank lines that are not comments)
15240 @item
15241 the number of comment lines
15243 @item
15244 the number of code lines containing end-of-line comments;
15246 @item
15247 the comment percentage: the ratio between the number of lines that contain
15248 comments and the number of all non-blank lines, expressed as a percentage;
15250 @item
15251 the number of empty lines and lines containing only space characters and/or
15252 format effectors (blank lines)
15254 @item
15255 the average number of code lines in subprogram bodies, task bodies, entry
15256 bodies and statement sequences in package bodies (this metric is only computed
15257 across the whole set of the analyzed units)
15259 @end itemize
15261 @noindent
15262 @command{gnatmetric} sums the values of the line metrics for all the
15263 files being processed and then generates the cumulative results. The tool
15264 also computes for all the files being processed the average number of code
15265 lines in bodies.
15267 You can use the following switches to select the specific line metrics
15268 to be computed and reported.
15270 @table @option
15271 @cindex @option{--lines@var{x}} (@command{gnatmetric})
15273 @cindex @option{--no-lines@var{x}}
15275 @item --lines-all
15276 Report all the line metrics
15278 @item --no-lines-all
15279 Do not report any of line metrics
15281 @item --lines
15282 Report the number of all lines
15284 @item --no-lines
15285 Do not report the number of all lines
15287 @item --lines-code
15288 Report the number of code lines
15290 @item --no-lines-code
15291 Do not report the number of code lines
15293 @item --lines-comment
15294 Report the number of comment lines
15296 @item --no-lines-comment
15297 Do not report the number of comment lines
15299 @item --lines-eol-comment
15300 Report the number of code lines containing
15301 end-of-line comments
15303 @item --no-lines-eol-comment
15304 Do not report the number of code lines containing
15305 end-of-line comments
15307 @item --lines-ratio
15308 Report the comment percentage in the program text
15310 @item --no-lines-ratio
15311 Do not report the comment percentage in the program text
15313 @item --lines-blank
15314 Report the number of blank lines
15316 @item --no-lines-blank
15317 Do not report the number of blank lines
15319 @item --lines-average
15320 Report the average number of code lines in subprogram bodies, task bodies,
15321 entry bodies and statement sequences in package bodies. The metric is computed
15322 and reported for the whole set of processed Ada sources only.
15324 @item --no-lines-average
15325 Do not report the average number of code lines in subprogram bodies,
15326 task bodies, entry bodies and statement sequences in package bodies.
15328 @end table
15330 @node Syntax Metrics Control
15331 @subsubsection Syntax Metrics Control
15332 @cindex Syntax metrics control in @command{gnatmetric}
15334 @noindent
15335 @command{gnatmetric} computes various syntactic metrics for the
15336 outermost unit and for each eligible local unit:
15338 @table @emph
15339 @item LSLOC (``Logical Source Lines Of Code'')
15340 The total number of declarations and the total number of statements. Note
15341 that the definition of declarations is the one given in the reference
15342 manual:
15344 @noindent
15345 ``Each of the following is defined to be a declaration: any basic_declaration;
15346 an enumeration_literal_specification; a discriminant_specification;
15347 a component_declaration; a loop_parameter_specification; a
15348 parameter_specification; a subprogram_body; an entry_declaration;
15349 an entry_index_specification; a choice_parameter_specification;
15350 a generic_formal_parameter_declaration.''
15352 This means for example that each enumeration literal adds one to the count,
15353 as well as each subprogram parameter.
15355 Thus the results from this metric will be significantly greater than might
15356 be expected from a naive view of counting semicolons.
15358 @item Maximal static nesting level of inner program units
15359 According to
15360 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15361 package, a task unit, a protected unit, a
15362 protected entry, a generic unit, or an explicitly declared subprogram other
15363 than an enumeration literal.''
15365 @item Maximal nesting level of composite syntactic constructs
15366 This corresponds to the notion of the
15367 maximum nesting level in the GNAT built-in style checks
15368 (@pxref{Style Checking})
15369 @end table
15371 @noindent
15372 For the outermost unit in the file, @command{gnatmetric} additionally computes
15373 the following metrics:
15375 @table @emph
15376 @item Public subprograms
15377 This metric is computed for package specs. It is the
15378 number of subprograms and generic subprograms declared in the visible
15379 part (including the visible part of nested packages, protected objects, and
15380 protected types).
15382 @item All subprograms
15383 This metric is computed for bodies and subunits. The
15384 metric is equal to a total number of subprogram bodies in the compilation
15385 unit.
15386 Neither generic instantiations nor renamings-as-a-body nor body stubs
15387 are counted. Any subprogram body is counted, independently of its nesting
15388 level and enclosing constructs. Generic bodies and bodies of protected
15389 subprograms are counted in the same way as ``usual'' subprogram bodies.
15391 @item Public types
15392 This metric is computed for package specs and
15393 generic package declarations. It is the total number of types
15394 that can be referenced from outside this compilation unit, plus the
15395 number of types from all the visible parts of all the visible generic
15396 packages. Generic formal types are not counted.  Only types, not subtypes,
15397 are included.
15399 @noindent
15400 Along with the total number of public types, the following
15401 types are counted and reported separately:
15403 @itemize @bullet
15404 @item
15405 Abstract types
15407 @item
15408 Root tagged types (abstract, non-abstract, private, non-private). Type
15409 extensions are @emph{not} counted
15411 @item
15412 Private types (including private extensions)
15414 @item
15415 Task types
15417 @item
15418 Protected types
15420 @end itemize
15422 @item All types
15423 This metric is computed for any compilation unit. It is equal to the total
15424 number of the declarations of different types given in the compilation unit.
15425 The private and the corresponding full type declaration are counted as one
15426 type declaration. Incomplete type declarations and generic formal types
15427 are not counted.
15428 No distinction is made among different kinds of types (abstract,
15429 private etc.); the total number of types is computed and reported.
15431 @end table
15433 @noindent
15434 By default, all the syntax metrics are computed and reported. You can use the
15435 following switches to select specific syntax metrics.
15437 @table @option
15439 @cindex @option{--syntax@var{x}} (@command{gnatmetric})
15441 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15443 @item --syntax-all
15444 Report all the syntax metrics
15446 @item --no-syntax-all
15447 Do not report any of syntax metrics
15449 @item --declarations
15450 Report the total number of declarations
15452 @item --no-declarations
15453 Do not report the total number of declarations
15455 @item --statements
15456 Report the total number of statements
15458 @item --no-statements
15459 Do not report the total number of statements
15461 @item --public-subprograms
15462 Report the number of public subprograms in a compilation unit
15464 @item --no-public-subprograms
15465 Do not report the number of public subprograms in a compilation unit
15467 @item --all-subprograms
15468 Report the number of all the subprograms in a compilation unit
15470 @item --no-all-subprograms
15471 Do not report the number of all the subprograms in a compilation unit
15473 @item --public-types
15474 Report the number of public types in a compilation unit
15476 @item --no-public-types
15477 Do not report the number of public types in a compilation unit
15479 @item --all-types
15480 Report the number of all the types in a compilation unit
15482 @item --no-all-types
15483 Do not report the number of all the types in a compilation unit
15485 @item --unit-nesting
15486 Report the maximal program unit nesting level
15488 @item --no-unit-nesting
15489 Do not report the maximal program unit nesting level
15491 @item --construct-nesting
15492 Report the maximal construct nesting level
15494 @item --no-construct-nesting
15495 Do not report the maximal construct nesting level
15497 @end table
15499 @node Complexity Metrics Control
15500 @subsubsection Complexity Metrics Control
15501 @cindex Complexity metrics control in @command{gnatmetric}
15503 @noindent
15504 For a program unit that is an executable body (a subprogram body (including
15505 generic bodies), task body, entry body or a package body containing
15506 its own statement sequence) @command{gnatmetric} computes the following
15507 complexity metrics:
15509 @itemize @bullet
15510 @item
15511 McCabe cyclomatic complexity;
15513 @item
15514 McCabe essential complexity;
15516 @item
15517 maximal loop nesting level;
15519 @item
15520 extra exit points (for subprograms);
15521 @end itemize
15523 @noindent
15524 The McCabe cyclomatic complexity metric is defined
15525 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15527 According to McCabe, both control statements and short-circuit control forms
15528 should be taken into account when computing cyclomatic complexity.
15529 For Ada 2012 we have also take into account conditional expressions
15530 and quantified expressions. For each body, we compute three metric values:
15532 @itemize @bullet
15533 @item
15534 the complexity introduced by control
15535 statements only, without taking into account short-circuit forms
15536 (referred as @code{statement complexity} in @command{gnatmetric} output),
15538 @item
15539 the complexity introduced by short-circuit control forms only
15540 (referred as @code{expression complexity} in @command{gnatmetric} output), and
15542 @item
15543 the total
15544 cyclomatic complexity, which is the sum of these two values
15545 (referred as @code{cyclomatic complexity} in @command{gnatmetric} output).
15546 @end itemize
15548 @noindent
15550 The cyclomatic complexity is also computed for Ada 2012 expression functions.
15551 An expression function cannot have statements as its components, so only one
15552 metric value is computed as a cyclomatic complexity of an expression function.
15554 The origin of cyclomatic complexity metric is the need to estimate the number
15555 of independent paths in the control flow graph that in turn gives the number
15556 of tests needed to satisfy paths coverage testing completeness criterion.
15557 Considered from the testing point of view, a static Ada @code{loop} (that is,
15558 the @code{loop} statement having static subtype in loop parameter
15559 specification) does not add to cyclomatic complexity. By providing
15560 @option{--no-static-loop} option a user
15561 may specify that such loops should not be counted when computing the
15562 cyclomatic complexity metric
15564 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
15565 counted for the code that is reduced by excluding all the pure structural Ada
15566 control statements. An compound statement is considered as a non-structural
15567 if it contains a @code{raise} or @code{return} statement as it subcomponent,
15568 or if it contains a @code{goto} statement that transfers the control outside
15569 the operator. A selective accept statement with @code{terminate} alternative
15570 is considered as non-structural statement. When computing this metric,
15571 @code{exit} statements are treated in the same way as @code{goto}
15572 statements unless @option{-ne} option is specified.
15574 The Ada essential complexity metric defined here is intended to quantify
15575 the extent to which the software is unstructured. It is adapted from
15576 the McCabe essential complexity metric defined in
15577 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
15578 suitable for typical Ada usage. For example, short circuit forms
15579 are not penalized as unstructured in the Ada essential complexity metric.
15581 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15582 the code in the exception handlers and in all the nested program units. The
15583 code of assertions and predicates (that is, subprogram preconditions and
15584 postconditions, subtype predicates and type invariants) is also skipped.
15586 By default, all the complexity metrics are computed and reported.
15587 For more fine-grained control you can use
15588 the following switches:
15590 @table @option
15591 @cindex @option{-complexity@var{x}} (@command{gnatmetric})
15593 @cindex @option{--no-complexity@var{x}}
15595 @item --complexity-all
15596 Report all the complexity metrics
15598 @item --no-complexity-all
15599 Do not report any of complexity metrics
15601 @item --complexity-cyclomatic
15602 Report the McCabe Cyclomatic Complexity
15604 @item --no-complexity-cyclomatic
15605 Do not report the McCabe Cyclomatic Complexity
15607 @item --complexity-essential
15608 Report the Essential Complexity
15610 @item --no-complexity-essential
15611 Do not report the Essential Complexity
15613 @item --loop-nesting
15614 Report maximal loop nesting level
15616 @item --no-loop-nesting
15617 Do not report maximal loop nesting level
15619 @item --complexity-average
15620 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15621 task bodies, entry bodies and statement sequences in package bodies.
15622 The metric is computed and reported for whole set of processed Ada sources
15623 only.
15625 @item --no-complexity-average
15626 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15627 bodies, task bodies, entry bodies and statement sequences in package bodies
15629 @cindex @option{-ne} (@command{gnatmetric})
15630 @item -ne
15631 Do not consider @code{exit} statements as @code{goto}s when
15632 computing Essential Complexity
15634 @cindex @option{--no-static-loop} (@command{gnatmetric})
15635 @item --no-static-loop
15636 Do not consider static loops when computing cyclomatic complexity
15638 @item --extra-exit-points
15639 Report the extra exit points for subprogram bodies. As an exit point, this
15640 metric counts @code{return} statements and raise statements in case when the
15641 raised exception is not handled in the same body. In case of a function this
15642 metric subtracts 1 from the number of exit points, because a function body
15643 must contain at least one @code{return} statement.
15645 @item --no-extra-exit-points
15646 Do not report the extra exit points for subprogram bodies
15647 @end table
15650 @node Coupling Metrics Control
15651 @subsubsection Coupling Metrics Control
15652 @cindex Coupling metrics control in @command{gnatmetric}
15654 @noindent
15655 @cindex Coupling metrics (in @command{gnatmetric})
15656 Coupling metrics measure the dependencies between a given entity and other
15657 entities in the program. This information is useful since high coupling
15658 may signal potential issues with maintainability as the program evolves.
15660 @command{gnatmetric} computes the following coupling metrics:
15662 @itemize @bullet
15664 @item
15665 @emph{object-oriented coupling}, for classes in traditional object-oriented
15666 sense;
15668 @item
15669 @emph{unit coupling}, for all the program units making up a program;
15671 @item
15672 @emph{control coupling}, reflecting dependencies between a unit and
15673 other units that contain subprograms.
15674 @end itemize
15676 @noindent
15677 Two kinds of coupling metrics are computed:
15679 @itemize @bullet
15680 @item fan-out coupling (``efferent coupling''):
15681 @cindex fan-out coupling
15682 @cindex efferent coupling
15683 the number of entities the given entity depends upon. This metric
15684 reflects how the given entity depends on the changes in the
15685 ``external world''.
15687 @item fan-in coupling (``afferent'' coupling):
15688 @cindex fan-in coupling
15689 @cindex afferent coupling
15690 the number of entities that depend on a given entity.
15691 This metric reflects how the ``external world'' depends on the changes in a
15692 given entity.
15693 @end itemize
15695 @noindent
15696 Object-oriented coupling metrics measure the dependencies
15697 between a given class (or a group of classes) and the other classes in the
15698 program. In this subsection the term ``class'' is used in its traditional
15699 object-oriented programming sense (an instantiable module that contains data
15700 and/or method members). A @emph{category} (of classes) is a group of closely
15701 related classes that are reused and/or modified together.
15703 A class @code{K}'s fan-out coupling is the number of classes
15704 that @code{K} depends upon.
15705 A category's fan-out coupling is the number of classes outside the
15706 category that the classes inside the category depend upon.
15708 A class @code{K}'s fan-in coupling is the number of classes
15709 that depend upon @code{K}.
15710 A category's fan-in coupling is the number of classes outside the
15711 category that depend on classes belonging to the category.
15713 Ada's object-oriented paradigm separates the instantiable entity
15714 (type) from the module (package), so the definition of the coupling
15715 metrics for Ada maps the class and class category notions
15716 onto Ada constructs.
15718 For the coupling metrics, several kinds of modules that define a tagged type
15719 or an interface type  -- library packages, library generic packages, and
15720 library generic package instantiations -- are considered to be classes.
15721 A category consists of a library package (or
15722 a library generic package) that defines a tagged or an interface type,
15723 together with all its descendant (generic) packages that define tagged
15724 or interface types. Thus a
15725 category is an Ada hierarchy of library-level program units. Class
15726 coupling in Ada is referred to as ``tagged coupling'', and category coupling
15727 is referred to as ``hierarchy coupling''.
15729 For any package serving as a class, its body and subunits (if any) are
15730 considered together with its spec when computing dependencies, and coupling
15731 metrics are reported for spec units only. Dependencies between classes
15732 mean Ada semantic dependencies. For object-oriented coupling
15733 metrics, only dependencies on units treated as classes are
15734 considered.
15736 Similarly, for unit and control coupling an entity is considered to be the
15737 conceptual construct consisting of the entity's specification, body, and
15738 any subunits (transitively).
15739 @command{gnatmetric} computes
15740 the dependencies of all these units as a whole, but
15741 metrics are only reported for spec
15742 units (or for a subprogram body unit in case if there is no
15743 separate spec for the given subprogram).
15745 For unit coupling, dependencies are computed between all kinds of program
15746 units. For control coupling, the dependencies of a given unit are limited to
15747 those units that define subprograms. Thus control fan-out coupling is reported
15748 for all units, but control fan-in coupling is only reported for units
15749 that define subprograms.
15751 The following simple example illustrates the difference between unit coupling
15752 and control coupling metrics:
15754 @smallexample @c ada
15755 @group
15756 @b{package} Lib_1 @b{is}
15757     @b{function} F_1 (I : Integer) @b{return} Integer;
15758 @b{end} Lib_1;
15759 @end group
15761 @group
15762 @b{package} Lib_2 @b{is}
15763     @b{type} T_2 @b{is} @b{new} Integer;
15764 @b{end} Lib_2;
15765 @end group
15767 @group
15768 @b{package} @b{body} Lib_1 @b{is}
15769     @b{function} F_1 (I : Integer) @b{return} Integer @b{is}
15770     @b{begin}
15771        @b{return} I + 1;
15772     @b{end} F_1;
15773 @b{end} Lib_1;
15774 @end group
15776 @group
15777 @b{with} Lib_2; @b{use} Lib_2;
15778 @b{package} Pack @b{is}
15779     Var : T_2;
15780     @b{function} Fun (I : Integer) @b{return} Integer;
15781 @b{end} Pack;
15782 @end group
15784 @group
15785 @b{with} Lib_1; @b{use} Lib_1;
15786 @b{package} @b{body} Pack @b{is}
15787     @b{function} Fun (I : Integer) @b{return} Integer @b{is}
15788     @b{begin}
15789        @b{return} F_1 (I);
15790     @b{end} Fun;
15791 @b{end} Pack;
15792 @end group
15793 @end smallexample
15795 @noindent
15796 If we apply @command{gnatmetric} with the @option{--coupling-all} option to
15797 these units, the result will be:
15799 @smallexample
15800 @group
15801 Coupling metrics:
15802 =================
15803     Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
15804        control fan-out coupling  : 0
15805        control fan-in coupling   : 1
15806        unit fan-out coupling     : 0
15807        unit fan-in coupling      : 1
15808 @end group
15810 @group
15811     Unit Pack (C:\customers\662\L406-007\pack.ads)
15812        control fan-out coupling  : 1
15813        control fan-in coupling   : 0
15814        unit fan-out coupling     : 2
15815        unit fan-in coupling      : 0
15816 @end group
15818 @group
15819     Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
15820        control fan-out coupling  : 0
15821        unit fan-out coupling     : 0
15822        unit fan-in coupling      : 1
15823 @end group
15824 @end smallexample
15826 @noindent
15827 The result does not contain values for object-oriented
15828 coupling because none of the argument units contains a tagged type and
15829 therefore none of these units can be treated as a class.
15831 The @code{Pack} package (spec and body) depends on two
15832 units -- @code{Lib_1} @code{and Lib_2} -- and so its unit fan-out coupling
15833 is 2. Since nothing depends on it, its unit fan-in coupling is 0, as
15834 is its control fan-in coupling. Only one of the units @code{Pack} depends
15835 upon defines a subprogram, so its control fan-out coupling is 1.
15837 @code{Lib_2} depends on nothing, so its fan-out metrics are 0. It does
15838 not define any subprograms, so it has no control fan-in metric.
15839 One unit (@code{Pack}) depends on it , so its unit fan-in coupling is 1.
15841 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
15842 Its control fan-in coupling is 1 (because there is one unit
15843 depending on it).
15845 When computing coupling metrics, @command{gnatmetric} counts only
15846 dependencies between units that are arguments of the @command{gnatmetric}
15847 invocation. Coupling metrics are program-wide (or project-wide) metrics, so
15848 you should invoke @command{gnatmetric} for
15849 the complete set of sources comprising your program. This can be done
15850 by invoking @command{gnatmetric} with the corresponding project file
15851 and with the @option{-U} option.
15853 By default, all the coupling metrics are disabled. You can use the following
15854 switches to specify the coupling metrics to be computed and reported:
15856 @table @option
15858 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
15859 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
15860 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
15861 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
15864 @item --coupling-all
15865 Report all the coupling metrics
15867 @item --tagged-coupling-out
15868 Report tagged (class) fan-out coupling
15870 @item --tagged-coupling-in
15871 Report tagged (class) fan-in coupling
15873 @item --hierarchy-coupling-out
15874 Report hierarchy (category) fan-out coupling
15876 @item --hierarchy-coupling-in
15877 Report hierarchy (category) fan-in coupling
15879 @item --unit-coupling-out
15880 Report unit fan-out coupling
15882 @item --unit-coupling-in
15883 Report unit fan-in coupling
15885 @item --control-coupling-out
15886 Report control fan-out coupling
15888 @item --control-coupling-in
15889 Report control fan-in coupling
15890 @end table
15892 @node Other gnatmetric Switches
15893 @subsection Other @code{gnatmetric} Switches
15895 @noindent
15896 Additional @command{gnatmetric} switches are as follows:
15898 @table @option
15899 @item --version
15900 @cindex @option{--version} @command{gnatmetric}
15901 Display Copyright and version, then exit disregarding all other options.
15903 @item --help
15904 @cindex @option{--help} @command{gnatmetric}
15905 Display usage, then exit disregarding all other options.
15907 @item -P @var{file}
15908 @cindex @option{-P} @command{gnatmetric}
15909 Indicates the name of the project file that describes the set of sources
15910 to be processed. The exact set of argument sources depends on other options
15911 specified, see below.
15913 @item -U
15914 @cindex @option{-U} @command{gnatmetric}
15915 If a project file is specified and no argument source is explicitly
15916 specified (either directly or by means of @option{-files} option), process
15917 all the units of the closure of the argument project. Otherwise this option
15918 has no effect.
15920 @item -U @var{main_unit}
15921 If a project file is specified and no argument source is explicitly
15922 specified (either directly or by means of @option{-files} option), process
15923 the closure of units rooted at @var{main_unit}. Otherwise this option
15924 has no effect.
15926 @item -X@var{name}=@var{value}
15927 @cindex @option{-X} @command{gnatmetric}
15928 Indicates that external variable @var{name} in the argument project
15929 has the value @var{value}. Has no effect if no project is specified as
15930 tool argument.
15932 @item --subdirs=@var{dir}
15933 @cindex @option{--subdirs=@var{dir}} @command{gnatmetric}
15934 Use the specified subdirectory of the project objects file (or of the
15935 project file directory if the project does not specify an object directory)
15936 for tool output files. Has no effect if no project is specified as
15937 tool argument r if @option{--no_objects_dir} is specified.
15939 @item --no_objects_dir
15940 @cindex @option{--no_objects_dir} @command{gnatmetric}
15941 Place all the result files into the current directory instead of
15942 project objects directory. This corresponds to the @command{gnatcheck}
15943 behavior when it is called with the project file from the
15944 GNAT driver. Has no effect if no project is specified.
15946 @item -files @var{filename}
15947 @cindex @option{-files} (@code{gnatmetric})
15948 Take the argument source files from the specified file. This file should be an
15949 ordinary text file containing file names separated by spaces or
15950 line breaks. You can use this switch more than once in the same call to
15951 @command{gnatmetric}. You also can combine this switch with
15952 an explicit list of files.
15954 @item -j@var{n}
15955 @cindex @option{-j} (@command{gnatmetric})
15956 Use @var{n} processes to carry out the tree creations (internal representations
15957 of the argument sources). On a multiprocessor machine this speeds up processing
15958 of big sets of argument sources. If @var{n} is 0, then the maximum number of
15959 parallel tree creations is the number of core processors on the platform.
15961 @cindex @option{-t} (@command{gnatmetric})
15962 @item -t
15963 Print out execution time.
15965 @item -v
15966 @cindex @option{-v} (@command{gnatmetric})
15967 Verbose mode;
15968 @command{gnatmetric} generates version information and then
15969 a trace of sources being processed.
15971 @item -q
15972 @cindex @option{-q} (@command{gnatmetric})
15973 Quiet mode.
15974 @end table
15976 @noindent
15977 If a project file is specified and no argument source is explicitly
15978 specified (either directly or by means of @option{-files} option), and no
15979 @option{-U} is specified, then the set of processed sources is
15980 all the immediate units of the argument project.
15983 @ignore
15984 @node Generate project-wide metrics
15985 @subsection Generate project-wide metrics
15987 In order to compute metrics on all units of a given project, you can use
15988 the @command{gnat} driver along with the @option{-P} option:
15989 @smallexample
15990    gnat metric -Pproj
15991 @end smallexample
15993 @noindent
15994 If the project @code{proj} depends upon other projects, you can compute
15995 the metrics on the project closure using the @option{-U} option:
15996 @smallexample
15997    gnat metric -Pproj -U
15998 @end smallexample
16000 @noindent
16001 Finally, if not all the units are relevant to a particular main
16002 program in the project closure, you can generate metrics for the set
16003 of units needed to create a given main program (unit closure) using
16004 the @option{-U} option followed by the name of the main unit:
16005 @smallexample
16006    gnat metric -Pproj -U main
16007 @end smallexample
16008 @end ignore
16009 @end ifclear
16012 @c ***********************************
16013 @node File Name Krunching with gnatkr
16014 @chapter File Name Krunching with @code{gnatkr}
16015 @findex gnatkr
16017 @noindent
16018 This chapter discusses the method used by the compiler to shorten
16019 the default file names chosen for Ada units so that they do not
16020 exceed the maximum length permitted. It also describes the
16021 @code{gnatkr} utility that can be used to determine the result of
16022 applying this shortening.
16023 @menu
16024 * About gnatkr::
16025 * Using gnatkr::
16026 * Krunching Method::
16027 * Examples of gnatkr Usage::
16028 @end menu
16030 @node About gnatkr
16031 @section About @code{gnatkr}
16033 @noindent
16034 The default file naming rule in GNAT
16035 is that the file name must be derived from
16036 the unit name. The exact default rule is as follows:
16037 @itemize @bullet
16038 @item
16039 Take the unit name and replace all dots by hyphens.
16040 @item
16041 If such a replacement occurs in the
16042 second character position of a name, and the first character is
16043 @samp{a}, @samp{g}, @samp{s}, or @samp{i},
16044 then replace the dot by the character
16045 @samp{~} (tilde)
16046 instead of a minus.
16047 @end itemize
16048 The reason for this exception is to avoid clashes
16049 with the standard names for children of System, Ada, Interfaces,
16050 and GNAT, which use the prefixes
16051 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
16052 respectively.
16054 The @option{-gnatk@var{nn}}
16055 switch of the compiler activates a ``krunching''
16056 circuit that limits file names to nn characters (where nn is a decimal
16057 integer). For example, using OpenVMS,
16058 where the maximum file name length is
16059 39, the value of nn is usually set to 39, but if you want to generate
16060 a set of files that would be usable if ported to a system with some
16061 different maximum file length, then a different value can be specified.
16062 The default value of 39 for OpenVMS need not be specified.
16064 The @code{gnatkr} utility can be used to determine the krunched name for
16065 a given file, when krunched to a specified maximum length.
16067 @node Using gnatkr
16068 @section Using @code{gnatkr}
16070 @noindent
16071 The @code{gnatkr} command has the form
16073 @smallexample
16074 @c $ gnatkr @var{name} @ovar{length}
16075 @c Expanding @ovar macro inline (explanation in macro def comments)
16076 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16077 @end smallexample
16080 @noindent
16081 @var{name} is the uncrunched file name, derived from the name of the unit
16082 in the standard manner described in the previous section (i.e., in particular
16083 all dots are replaced by hyphens). The file name may or may not have an
16084 extension (defined as a suffix of the form period followed by arbitrary
16085 characters other than period). If an extension is present then it will
16086 be preserved in the output. For example, when krunching @file{hellofile.ads}
16087 to eight characters, the result will be hellofil.ads.
16089 Note: for compatibility with previous versions of @code{gnatkr} dots may
16090 appear in the name instead of hyphens, but the last dot will always be
16091 taken as the start of an extension. So if @code{gnatkr} is given an argument
16092 such as @file{Hello.World.adb} it will be treated exactly as if the first
16093 period had been a hyphen, and for example krunching to eight characters
16094 gives the result @file{hellworl.adb}.
16096 Note that the result is always all lower case (except on OpenVMS where it is
16097 all upper case). Characters of the other case are folded as required.
16099 @var{length} represents the length of the krunched name. The default
16100 when no argument is given is 8 characters. A length of zero stands for
16101 unlimited, in other words do not chop except for system files where the
16102 implied crunching length is always eight characters.
16104 @noindent
16105 The output is the krunched name. The output has an extension only if the
16106 original argument was a file name with an extension.
16108 @node Krunching Method
16109 @section Krunching Method
16111 @noindent
16112 The initial file name is determined by the name of the unit that the file
16113 contains. The name is formed by taking the full expanded name of the
16114 unit and replacing the separating dots with hyphens and
16115 using lowercase
16116 for all letters, except that a hyphen in the second character position is
16117 replaced by a tilde if the first character is
16118 @samp{a}, @samp{i}, @samp{g}, or @samp{s}.
16119 The extension is @code{.ads} for a
16120 spec and @code{.adb} for a body.
16121 Krunching does not affect the extension, but the file name is shortened to
16122 the specified length by following these rules:
16124 @itemize @bullet
16125 @item
16126 The name is divided into segments separated by hyphens, tildes or
16127 underscores and all hyphens, tildes, and underscores are
16128 eliminated. If this leaves the name short enough, we are done.
16130 @item
16131 If the name is too long, the longest segment is located (left-most
16132 if there are two of equal length), and shortened by dropping
16133 its last character. This is repeated until the name is short enough.
16135 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16136 to fit the name into 8 characters as required by some operating systems.
16138 @smallexample
16139 our-strings-wide_fixed 22
16140 our strings wide fixed 19
16141 our string  wide fixed 18
16142 our strin   wide fixed 17
16143 our stri    wide fixed 16
16144 our stri    wide fixe  15
16145 our str     wide fixe  14
16146 our str     wid  fixe  13
16147 our str     wid  fix   12
16148 ou  str     wid  fix   11
16149 ou  st      wid  fix   10
16150 ou  st      wi   fix   9
16151 ou  st      wi   fi    8
16152 Final file name: oustwifi.adb
16153 @end smallexample
16155 @item
16156 The file names for all predefined units are always krunched to eight
16157 characters. The krunching of these predefined units uses the following
16158 special prefix replacements:
16160 @table @file
16161 @item ada-
16162 replaced by @file{a-}
16164 @item gnat-
16165 replaced by @file{g-}
16167 @item interfaces-
16168 replaced by @file{i-}
16170 @item system-
16171 replaced by @file{s-}
16172 @end table
16174 These system files have a hyphen in the second character position. That
16175 is why normal user files replace such a character with a
16176 tilde, to
16177 avoid confusion with system file names.
16179 As an example of this special rule, consider
16180 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16182 @smallexample
16183 ada-strings-wide_fixed 22
16184 a-  strings wide fixed 18
16185 a-  string  wide fixed 17
16186 a-  strin   wide fixed 16
16187 a-  stri    wide fixed 15
16188 a-  stri    wide fixe  14
16189 a-  str     wide fixe  13
16190 a-  str     wid  fixe  12
16191 a-  str     wid  fix   11
16192 a-  st      wid  fix   10
16193 a-  st      wi   fix   9
16194 a-  st      wi   fi    8
16195 Final file name: a-stwifi.adb
16196 @end smallexample
16197 @end itemize
16199 Of course no file shortening algorithm can guarantee uniqueness over all
16200 possible unit names, and if file name krunching is used then it is your
16201 responsibility to ensure that no name clashes occur. The utility
16202 program @code{gnatkr} is supplied for conveniently determining the
16203 krunched name of a file.
16205 @node Examples of gnatkr Usage
16206 @section Examples of @code{gnatkr} Usage
16208 @smallexample
16209 @iftex
16210 @leftskip=0cm
16211 @end iftex
16212 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16213 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16214 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16215 $ gnatkr grandparent-parent-child     --> grparchi
16216 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16217 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16218 @end smallexample
16220 @node Preprocessing with gnatprep
16221 @chapter Preprocessing with @code{gnatprep}
16222 @findex gnatprep
16224 @noindent
16225 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16226 preprocessing.
16227 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16228 special GNAT features.
16229 For further discussion of conditional compilation in general, see
16230 @ref{Conditional Compilation}.
16232 @menu
16233 * Preprocessing Symbols::
16234 * Using gnatprep::
16235 * Switches for gnatprep::
16236 * Form of Definitions File::
16237 * Form of Input Text for gnatprep::
16238 @end menu
16240 @node Preprocessing Symbols
16241 @section Preprocessing Symbols
16243 @noindent
16244 Preprocessing symbols are defined in definition files and referred to in
16245 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16246 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16247 all characters need to be in the ASCII set (no accented letters).
16249 @node Using gnatprep
16250 @section Using @code{gnatprep}
16252 @noindent
16253 To call @code{gnatprep} use
16255 @smallexample
16256 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16257 @c Expanding @ovar macro inline (explanation in macro def comments)
16258 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16259 @end smallexample
16261 @noindent
16262 where
16263 @table @var
16264 @item switches
16265 is an optional sequence of switches as described in the next section.
16267 @item infile
16268 is the full name of the input file, which is an Ada source
16269 file containing preprocessor directives.
16271 @item outfile
16272 is the full name of the output file, which is an Ada source
16273 in standard Ada form. When used with GNAT, this file name will
16274 normally have an ads or adb suffix.
16276 @item deffile
16277 is the full name of a text file containing definitions of
16278 preprocessing symbols to be referenced by the preprocessor. This argument is
16279 optional, and can be replaced by the use of the @option{-D} switch.
16281 @end table
16283 @node Switches for gnatprep
16284 @section Switches for @code{gnatprep}
16286 @table @option
16287 @c !sort!
16289 @item -b
16290 @cindex @option{-b} (@command{gnatprep})
16291 Causes both preprocessor lines and the lines deleted by
16292 preprocessing to be replaced by blank lines in the output source file,
16293 preserving line numbers in the output file.
16295 @item -c
16296 @cindex @option{-c} (@command{gnatprep})
16297 Causes both preprocessor lines and the lines deleted
16298 by preprocessing to be retained in the output source as comments marked
16299 with the special string @code{"--! "}. This option will result in line numbers
16300 being preserved in the output file.
16302 @item -C
16303 @cindex @option{-C} (@command{gnatprep})
16304 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16305 If this option is specified, then comments are scanned and any $symbol
16306 substitutions performed as in program text. This is particularly useful
16307 when structured comments are used (e.g., when writing programs in the
16308 SPARK dialect of Ada). Note that this switch is not available when
16309 doing integrated preprocessing (it would be useless in this context
16310 since comments are ignored by the compiler in any case).
16312 @item -Dsymbol=value
16313 @cindex @option{-D} (@command{gnatprep})
16314 Defines a new preprocessing symbol, associated with value. If no value is given
16315 on the command line, then symbol is considered to be @code{True}. This switch
16316 can be used in place of a definition file.
16319 @item -r
16320 @cindex @option{-r} (@command{gnatprep})
16321 Causes a @code{Source_Reference} pragma to be generated that
16322 references the original input file, so that error messages will use
16323 the file name of this original file. The use of this switch implies
16324 that preprocessor lines are not to be removed from the file, so its
16325 use will force @option{-b} mode if
16326 @option{-c}
16327 has not been specified explicitly.
16329 Note that if the file to be preprocessed contains multiple units, then
16330 it will be necessary to @code{gnatchop} the output file from
16331 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16332 in the preprocessed file, it will be respected by
16333 @code{gnatchop -r}
16334 so that the final chopped files will correctly refer to the original
16335 input source file for @code{gnatprep}.
16337 @item -s
16338 @cindex @option{-s} (@command{gnatprep})
16339 Causes a sorted list of symbol names and values to be
16340 listed on the standard output file.
16342 @item -u
16343 @cindex @option{-u} (@command{gnatprep})
16344 Causes undefined symbols to be treated as having the value FALSE in the context
16345 of a preprocessor test. In the absence of this option, an undefined symbol in
16346 a @code{#if} or @code{#elsif} test will be treated as an error.
16348 @end table
16350 @noindent
16351 Note: if neither @option{-b} nor @option{-c} is present,
16352 then preprocessor lines and
16353 deleted lines are completely removed from the output, unless -r is
16354 specified, in which case -b is assumed.
16356 @node Form of Definitions File
16357 @section Form of Definitions File
16359 @noindent
16360 The definitions file contains lines of the form
16362 @smallexample
16363 symbol := value
16364 @end smallexample
16366 @noindent
16367 where symbol is a preprocessing symbol, and value is one of the following:
16369 @itemize @bullet
16370 @item
16371 Empty, corresponding to a null substitution
16372 @item
16373 A string literal using normal Ada syntax
16374 @item
16375 Any sequence of characters from the set
16376 (letters, digits, period, underline).
16377 @end itemize
16379 @noindent
16380 Comment lines may also appear in the definitions file, starting with
16381 the usual @code{--},
16382 and comments may be added to the definitions lines.
16384 @node Form of Input Text for gnatprep
16385 @section Form of Input Text for @code{gnatprep}
16387 @noindent
16388 The input text may contain preprocessor conditional inclusion lines,
16389 as well as general symbol substitution sequences.
16391 The preprocessor conditional inclusion commands have the form
16393 @smallexample
16394 @group
16395 @cartouche
16396 #if @i{expression} @r{[}then@r{]}
16397    lines
16398 #elsif @i{expression} @r{[}then@r{]}
16399    lines
16400 #elsif @i{expression} @r{[}then@r{]}
16401    lines
16402 @dots{}
16403 #else
16404    lines
16405 #end if;
16406 @end cartouche
16407 @end group
16408 @end smallexample
16410 @noindent
16411 In this example, @i{expression} is defined by the following grammar:
16412 @smallexample
16413 @i{expression} ::=  <symbol>
16414 @i{expression} ::=  <symbol> = "<value>"
16415 @i{expression} ::=  <symbol> = <symbol>
16416 @i{expression} ::=  <symbol> = <integer>
16417 @i{expression} ::=  <symbol> > <integer>
16418 @i{expression} ::=  <symbol> >= <integer>
16419 @i{expression} ::=  <symbol> < <integer>
16420 @i{expression} ::=  <symbol> <= <integer>
16421 @i{expression} ::=  <symbol> 'Defined
16422 @i{expression} ::=  not @i{expression}
16423 @i{expression} ::=  @i{expression} and @i{expression}
16424 @i{expression} ::=  @i{expression} or @i{expression}
16425 @i{expression} ::=  @i{expression} and then @i{expression}
16426 @i{expression} ::=  @i{expression} or else @i{expression}
16427 @i{expression} ::=  ( @i{expression} )
16428 @end smallexample
16430 The following restriction exists: it is not allowed to have "and" or "or"
16431 following "not" in the same expression without parentheses. For example, this
16432 is not allowed:
16434 @smallexample
16435    not X or Y
16436 @end smallexample
16438 This should be one of the following:
16440 @smallexample
16441    (not X) or Y
16442    not (X or Y)
16443 @end smallexample
16445 @noindent
16446 For the first test (@i{expression} ::= <symbol>) the symbol must have
16447 either the value true or false, that is to say the right-hand of the
16448 symbol definition must be one of the (case-insensitive) literals
16449 @code{True} or @code{False}. If the value is true, then the
16450 corresponding lines are included, and if the value is false, they are
16451 excluded.
16453 When comparing a symbol to an integer, the integer is any non negative
16454 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
16455 2#11#. The symbol value must also be a non negative integer. Integer values
16456 in the range 0 .. 2**31-1 are supported.
16458 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16459 the symbol has been defined in the definition file or by a @option{-D}
16460 switch on the command line. Otherwise, the test is false.
16462 The equality tests are case insensitive, as are all the preprocessor lines.
16464 If the symbol referenced is not defined in the symbol definitions file,
16465 then the effect depends on whether or not switch @option{-u}
16466 is specified. If so, then the symbol is treated as if it had the value
16467 false and the test fails. If this switch is not specified, then
16468 it is an error to reference an undefined symbol. It is also an error to
16469 reference a symbol that is defined with a value other than @code{True}
16470 or @code{False}.
16472 The use of the @code{not} operator inverts the sense of this logical test.
16473 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16474 operators, without parentheses. For example, "if not X or Y then" is not
16475 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16477 The @code{then} keyword is optional as shown
16479 The @code{#} must be the first non-blank character on a line, but
16480 otherwise the format is free form. Spaces or tabs may appear between
16481 the @code{#} and the keyword. The keywords and the symbols are case
16482 insensitive as in normal Ada code. Comments may be used on a
16483 preprocessor line, but other than that, no other tokens may appear on a
16484 preprocessor line. Any number of @code{elsif} clauses can be present,
16485 including none at all. The @code{else} is optional, as in Ada.
16487 The @code{#} marking the start of a preprocessor line must be the first
16488 non-blank character on the line, i.e., it must be preceded only by
16489 spaces or horizontal tabs.
16491 Symbol substitution outside of preprocessor lines is obtained by using
16492 the sequence
16494 @smallexample
16495 $symbol
16496 @end smallexample
16498 @noindent
16499 anywhere within a source line, except in a comment or within a
16500 string literal. The identifier
16501 following the @code{$} must match one of the symbols defined in the symbol
16502 definition file, and the result is to substitute the value of the
16503 symbol in place of @code{$symbol} in the output file.
16505 Note that although the substitution of strings within a string literal
16506 is not possible, it is possible to have a symbol whose defined value is
16507 a string literal. So instead of setting XYZ to @code{hello} and writing:
16509 @smallexample
16510 Header : String := "$XYZ";
16511 @end smallexample
16513 @noindent
16514 you should set XYZ to @code{"hello"} and write:
16516 @smallexample
16517 Header : String := $XYZ;
16518 @end smallexample
16520 @noindent
16521 and then the substitution will occur as desired.
16523 @node The GNAT Library Browser gnatls
16524 @chapter The GNAT Library Browser @code{gnatls}
16525 @findex gnatls
16526 @cindex Library browser
16528 @noindent
16529 @code{gnatls} is a tool that outputs information about compiled
16530 units. It gives the relationship between objects, unit names and source
16531 files. It can also be used to check the source dependencies of a unit
16532 as well as various characteristics.
16534 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16535 driver (see @ref{The GNAT Driver and Project Files}).
16537 @menu
16538 * Running gnatls::
16539 * Switches for gnatls::
16540 * Examples of gnatls Usage::
16541 @end menu
16543 @node Running gnatls
16544 @section Running @code{gnatls}
16546 @noindent
16547 The @code{gnatls} command has the form
16549 @smallexample
16550 $ gnatls switches @var{object_or_ali_file}
16551 @end smallexample
16553 @noindent
16554 The main argument is the list of object or @file{ali} files
16555 (@pxref{The Ada Library Information Files})
16556 for which information is requested.
16558 In normal mode, without additional option, @code{gnatls} produces a
16559 four-column listing. Each line represents information for a specific
16560 object. The first column gives the full path of the object, the second
16561 column gives the name of the principal unit in this object, the third
16562 column gives the status of the source and the fourth column gives the
16563 full path of the source representing this unit.
16564 Here is a simple example of use:
16566 @smallexample
16567 $ gnatls *.o
16568 ./demo1.o            demo1            DIF demo1.adb
16569 ./demo2.o            demo2             OK demo2.adb
16570 ./hello.o            h1                OK hello.adb
16571 ./instr-child.o      instr.child      MOK instr-child.adb
16572 ./instr.o            instr             OK instr.adb
16573 ./tef.o              tef              DIF tef.adb
16574 ./text_io_example.o  text_io_example   OK text_io_example.adb
16575 ./tgef.o             tgef             DIF tgef.adb
16576 @end smallexample
16578 @noindent
16579 The first line can be interpreted as follows: the main unit which is
16580 contained in
16581 object file @file{demo1.o} is demo1, whose main source is in
16582 @file{demo1.adb}. Furthermore, the version of the source used for the
16583 compilation of demo1 has been modified (DIF). Each source file has a status
16584 qualifier which can be:
16586 @table @code
16587 @item OK (unchanged)
16588 The version of the source file used for the compilation of the
16589 specified unit corresponds exactly to the actual source file.
16591 @item MOK (slightly modified)
16592 The version of the source file used for the compilation of the
16593 specified unit differs from the actual source file but not enough to
16594 require recompilation. If you use gnatmake with the qualifier
16595 @option{-m (minimal recompilation)}, a file marked
16596 MOK will not be recompiled.
16598 @item DIF (modified)
16599 No version of the source found on the path corresponds to the source
16600 used to build this object.
16602 @item ??? (file not found)
16603 No source file was found for this unit.
16605 @item HID (hidden,  unchanged version not first on PATH)
16606 The version of the source that corresponds exactly to the source used
16607 for compilation has been found on the path but it is hidden by another
16608 version of the same source that has been modified.
16610 @end table
16612 @node Switches for gnatls
16613 @section Switches for @code{gnatls}
16615 @noindent
16616 @code{gnatls} recognizes the following switches:
16618 @table @option
16619 @c !sort!
16620 @cindex @option{--version} @command{gnatls}
16621 Display Copyright and version, then exit disregarding all other options.
16623 @item --help
16624 @cindex @option{--help} @command{gnatls}
16625 If @option{--version} was not used, display usage, then exit disregarding
16626 all other options.
16628 @item -a
16629 @cindex @option{-a} (@code{gnatls})
16630 Consider all units, including those of the predefined Ada library.
16631 Especially useful with @option{-d}.
16633 @item -d
16634 @cindex @option{-d} (@code{gnatls})
16635 List sources from which specified units depend on.
16637 @item -h
16638 @cindex @option{-h} (@code{gnatls})
16639 Output the list of options.
16641 @item -o
16642 @cindex @option{-o} (@code{gnatls})
16643 Only output information about object files.
16645 @item -s
16646 @cindex @option{-s} (@code{gnatls})
16647 Only output information about source files.
16649 @item -u
16650 @cindex @option{-u} (@code{gnatls})
16651 Only output information about compilation units.
16653 @item -files=@var{file}
16654 @cindex @option{-files} (@code{gnatls})
16655 Take as arguments the files listed in text file @var{file}.
16656 Text file @var{file} may contain empty lines that are ignored.
16657 Each nonempty line should contain the name of an existing file.
16658 Several such switches may be specified simultaneously.
16660 @item -aO@var{dir}
16661 @itemx -aI@var{dir}
16662 @itemx -I@var{dir}
16663 @itemx  -I-
16664 @itemx -nostdinc
16665 @cindex @option{-aO} (@code{gnatls})
16666 @cindex @option{-aI} (@code{gnatls})
16667 @cindex @option{-I} (@code{gnatls})
16668 @cindex @option{-I-} (@code{gnatls})
16669 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16670 flags (@pxref{Switches for gnatmake}).
16672 @item -aP@var{dir}
16673 @cindex @option{-aP} (@code{gnatls})
16674 Add @var{dir} at the beginning of the project search dir.
16676 @item --RTS=@var{rts-path}
16677 @cindex @option{--RTS} (@code{gnatls})
16678 Specifies the default location of the runtime library. Same meaning as the
16679 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16681 @item -v
16682 @cindex @option{-v} (@code{gnatls})
16683 Verbose mode. Output the complete source, object and project paths. Do not use
16684 the default column layout but instead use long format giving as much as
16685 information possible on each requested units, including special
16686 characteristics such as:
16688 @table @code
16689 @item  Preelaborable
16690 The unit is preelaborable in the Ada sense.
16692 @item No_Elab_Code
16693 No elaboration code has been produced by the compiler for this unit.
16695 @item Pure
16696 The unit is pure in the Ada sense.
16698 @item Elaborate_Body
16699 The unit contains a pragma Elaborate_Body.
16701 @item Remote_Types
16702 The unit contains a pragma Remote_Types.
16704 @item Shared_Passive
16705 The unit contains a pragma Shared_Passive.
16707 @item Predefined
16708 This unit is part of the predefined environment and cannot be modified
16709 by the user.
16711 @item Remote_Call_Interface
16712 The unit contains a pragma Remote_Call_Interface.
16714 @end table
16716 @end table
16718 @node Examples of gnatls Usage
16719 @section Example of @code{gnatls} Usage
16721 @noindent
16722 Example of using the verbose switch. Note how the source and
16723 object paths are affected by the -I switch.
16725 @smallexample
16726 $ gnatls -v -I.. demo1.o
16728 GNATLS 5.03w (20041123-34)
16729 Copyright 1997-2004 Free Software Foundation, Inc.
16731 Source Search Path:
16732    <Current_Directory>
16733    ../
16734    /home/comar/local/adainclude/
16736 Object Search Path:
16737    <Current_Directory>
16738    ../
16739    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16741 Project Search Path:
16742    <Current_Directory>
16743    /home/comar/local/lib/gnat/
16745 ./demo1.o
16746    Unit =>
16747      Name   => demo1
16748      Kind   => subprogram body
16749      Flags  => No_Elab_Code
16750      Source => demo1.adb    modified
16751 @end smallexample
16753 @noindent
16754 The following is an example of use of the dependency list.
16755 Note the use of the -s switch
16756 which gives a straight list of source files. This can be useful for
16757 building specialized scripts.
16759 @smallexample
16760 $ gnatls -d demo2.o
16761 ./demo2.o   demo2        OK demo2.adb
16762                          OK gen_list.ads
16763                          OK gen_list.adb
16764                          OK instr.ads
16765                          OK instr-child.ads
16767 $ gnatls -d -s -a demo1.o
16768 demo1.adb
16769 /home/comar/local/adainclude/ada.ads
16770 /home/comar/local/adainclude/a-finali.ads
16771 /home/comar/local/adainclude/a-filico.ads
16772 /home/comar/local/adainclude/a-stream.ads
16773 /home/comar/local/adainclude/a-tags.ads
16774 gen_list.ads
16775 gen_list.adb
16776 /home/comar/local/adainclude/gnat.ads
16777 /home/comar/local/adainclude/g-io.ads
16778 instr.ads
16779 /home/comar/local/adainclude/system.ads
16780 /home/comar/local/adainclude/s-exctab.ads
16781 /home/comar/local/adainclude/s-finimp.ads
16782 /home/comar/local/adainclude/s-finroo.ads
16783 /home/comar/local/adainclude/s-secsta.ads
16784 /home/comar/local/adainclude/s-stalib.ads
16785 /home/comar/local/adainclude/s-stoele.ads
16786 /home/comar/local/adainclude/s-stratt.ads
16787 /home/comar/local/adainclude/s-tasoli.ads
16788 /home/comar/local/adainclude/s-unstyp.ads
16789 /home/comar/local/adainclude/unchconv.ads
16790 @end smallexample
16793 @node Cleaning Up with gnatclean
16794 @chapter Cleaning Up with @code{gnatclean}
16795 @findex gnatclean
16796 @cindex Cleaning tool
16798 @noindent
16799 @code{gnatclean} is a tool that allows the deletion of files produced by the
16800 compiler, binder and linker, including ALI files, object files, tree files,
16801 expanded source files, library files, interface copy source files, binder
16802 generated files and executable files.
16804 @menu
16805 * Running gnatclean::
16806 * Switches for gnatclean::
16807 @c * Examples of gnatclean Usage::
16808 @end menu
16810 @node Running gnatclean
16811 @section Running @code{gnatclean}
16813 @noindent
16814 The @code{gnatclean} command has the form:
16816 @smallexample
16817 $ gnatclean switches @var{names}
16818 @end smallexample
16820 @noindent
16821 @var{names} is a list of source file names. Suffixes @code{.ads} and
16822 @code{adb} may be omitted. If a project file is specified using switch
16823 @code{-P}, then @var{names} may be completely omitted.
16825 @noindent
16826 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16827 if switch @code{-c} is not specified, by the binder and
16828 the linker. In informative-only mode, specified by switch
16829 @code{-n}, the list of files that would have been deleted in
16830 normal mode is listed, but no file is actually deleted.
16832 @node Switches for gnatclean
16833 @section Switches for @code{gnatclean}
16835 @noindent
16836 @code{gnatclean} recognizes the following switches:
16838 @table @option
16839 @c !sort!
16840 @cindex @option{--version} @command{gnatclean}
16841 Display Copyright and version, then exit disregarding all other options.
16843 @item --help
16844 @cindex @option{--help} @command{gnatclean}
16845 If @option{--version} was not used, display usage, then exit disregarding
16846 all other options.
16848 @item --subdirs=subdir
16849 Actual object directory of each project file is the subdirectory subdir of the
16850 object directory specified or defaulted in the project file.
16852 @item --unchecked-shared-lib-imports
16853 By default, shared library projects are not allowed to import static library
16854 projects. When this switch is used on the command line, this restriction is
16855 relaxed.
16857 @item -c
16858 @cindex @option{-c} (@code{gnatclean})
16859 Only attempt to delete the files produced by the compiler, not those produced
16860 by the binder or the linker. The files that are not to be deleted are library
16861 files, interface copy files, binder generated files and executable files.
16863 @item -D @var{dir}
16864 @cindex @option{-D} (@code{gnatclean})
16865 Indicate that ALI and object files should normally be found in directory
16866 @var{dir}.
16868 @item -F
16869 @cindex @option{-F} (@code{gnatclean})
16870 When using project files, if some errors or warnings are detected during
16871 parsing and verbose mode is not in effect (no use of switch
16872 -v), then error lines start with the full path name of the project
16873 file, rather than its simple file name.
16875 @item -h
16876 @cindex @option{-h} (@code{gnatclean})
16877 Output a message explaining the usage of @code{gnatclean}.
16879 @item -n
16880 @cindex @option{-n} (@code{gnatclean})
16881 Informative-only mode. Do not delete any files. Output the list of the files
16882 that would have been deleted if this switch was not specified.
16884 @item -P@var{project}
16885 @cindex @option{-P} (@code{gnatclean})
16886 Use project file @var{project}. Only one such switch can be used.
16887 When cleaning a project file, the files produced by the compilation of the
16888 immediate sources or inherited sources of the project files are to be
16889 deleted. This is not depending on the presence or not of executable names
16890 on the command line.
16892 @item -q
16893 @cindex @option{-q} (@code{gnatclean})
16894 Quiet output. If there are no errors, do not output anything, except in
16895 verbose mode (switch -v) or in informative-only mode
16896 (switch -n).
16898 @item -r
16899 @cindex @option{-r} (@code{gnatclean})
16900 When a project file is specified (using switch -P),
16901 clean all imported and extended project files, recursively. If this switch
16902 is not specified, only the files related to the main project file are to be
16903 deleted. This switch has no effect if no project file is specified.
16905 @item -v
16906 @cindex @option{-v} (@code{gnatclean})
16907 Verbose mode.
16909 @item -vP@emph{x}
16910 @cindex @option{-vP} (@code{gnatclean})
16911 Indicates the verbosity of the parsing of GNAT project files.
16912 @xref{Switches Related to Project Files}.
16914 @item -X@var{name=value}
16915 @cindex @option{-X} (@code{gnatclean})
16916 Indicates that external variable @var{name} has the value @var{value}.
16917 The Project Manager will use this value for occurrences of
16918 @code{external(name)} when parsing the project file.
16919 @xref{Switches Related to Project Files}.
16921 @item -aO@var{dir}
16922 @cindex @option{-aO} (@code{gnatclean})
16923 When searching for ALI and object files, look in directory
16924 @var{dir}.
16926 @item -I@var{dir}
16927 @cindex @option{-I} (@code{gnatclean})
16928 Equivalent to @option{-aO@var{dir}}.
16930 @item -I-
16931 @cindex @option{-I-} (@code{gnatclean})
16932 @cindex Source files, suppressing search
16933 Do not look for ALI or object files in the directory
16934 where @code{gnatclean} was invoked.
16936 @end table
16938 @c @node Examples of gnatclean Usage
16939 @c @section Examples of @code{gnatclean} Usage
16941 @node GNAT and Libraries
16942 @chapter GNAT and Libraries
16943 @cindex Library, building, installing, using
16945 @noindent
16946 This chapter describes how to build and use libraries with GNAT, and also shows
16947 how to recompile the GNAT run-time library. You should be familiar with the
16948 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16949 chapter.
16951 @menu
16952 * Introduction to Libraries in GNAT::
16953 * General Ada Libraries::
16954 * Stand-alone Ada Libraries::
16955 * Rebuilding the GNAT Run-Time Library::
16956 @end menu
16958 @node Introduction to Libraries in GNAT
16959 @section Introduction to Libraries in GNAT
16961 @noindent
16962 A library is, conceptually, a collection of objects which does not have its
16963 own main thread of execution, but rather provides certain services to the
16964 applications that use it. A library can be either statically linked with the
16965 application, in which case its code is directly included in the application,
16966 or, on platforms that support it, be dynamically linked, in which case
16967 its code is shared by all applications making use of this library.
16969 GNAT supports both types of libraries.
16970 In the static case, the compiled code can be provided in different ways. The
16971 simplest approach is to provide directly the set of objects resulting from
16972 compilation of the library source files. Alternatively, you can group the
16973 objects into an archive using whatever commands are provided by the operating
16974 system. For the latter case, the objects are grouped into a shared library.
16976 In the GNAT environment, a library has three types of components:
16977 @itemize @bullet
16978 @item
16979 Source files.
16980 @item
16981 @file{ALI} files.
16982 @xref{The Ada Library Information Files}.
16983 @item
16984 Object files, an archive or a shared library.
16985 @end itemize
16987 @noindent
16988 A GNAT library may expose all its source files, which is useful for
16989 documentation purposes. Alternatively, it may expose only the units needed by
16990 an external user to make use of the library. That is to say, the specs
16991 reflecting the library services along with all the units needed to compile
16992 those specs, which can include generic bodies or any body implementing an
16993 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16994 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
16996 All compilation units comprising an application, including those in a library,
16997 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16998 computes the elaboration order from the @file{ALI} files and this is why they
16999 constitute a mandatory part of GNAT libraries.
17000 @emph{Stand-alone libraries} are the exception to this rule because a specific
17001 library elaboration routine is produced independently of the application(s)
17002 using the library.
17004 @node General Ada Libraries
17005 @section General Ada Libraries
17007 @menu
17008 * Building a library::
17009 * Installing a library::
17010 * Using a library::
17011 @end menu
17013 @node Building a library
17014 @subsection Building a library
17016 @noindent
17017 The easiest way to build a library is to use the Project Manager,
17018 which supports a special type of project called a @emph{Library Project}
17019 (@pxref{Library Projects}).
17021 A project is considered a library project, when two project-level attributes
17022 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17023 control different aspects of library configuration, additional optional
17024 project-level attributes can be specified:
17025 @table @code
17026 @item Library_Kind
17027 This attribute controls whether the library is to be static or dynamic
17029 @item Library_Version
17030 This attribute specifies the library version; this value is used
17031 during dynamic linking of shared libraries to determine if the currently
17032 installed versions of the binaries are compatible.
17034 @item Library_Options
17035 @item Library_GCC
17036 These attributes specify additional low-level options to be used during
17037 library generation, and redefine the actual application used to generate
17038 library.
17039 @end table
17041 @noindent
17042 The GNAT Project Manager takes full care of the library maintenance task,
17043 including recompilation of the source files for which objects do not exist
17044 or are not up to date, assembly of the library archive, and installation of
17045 the library (i.e., copying associated source, object and @file{ALI} files
17046 to the specified location).
17048 Here is a simple library project file:
17049 @smallexample @c ada
17050 project My_Lib @b{is}
17051    @b{for} Source_Dirs @b{use} ("src1", "src2");
17052    @b{for} Object_Dir @b{use} "obj";
17053    @b{for} Library_Name @b{use} "mylib";
17054    @b{for} Library_Dir @b{use} "lib";
17055    @b{for} Library_Kind @b{use} "dynamic";
17056 @b{end} My_lib;
17057 @end smallexample
17059 @noindent
17060 and the compilation command to build and install the library:
17062 @smallexample @c ada
17063   $ gnatmake -Pmy_lib
17064 @end smallexample
17066 @noindent
17067 It is not entirely trivial to perform manually all the steps required to
17068 produce a library. We recommend that you use the GNAT Project Manager
17069 for this task. In special cases where this is not desired, the necessary
17070 steps are discussed below.
17072 There are various possibilities for compiling the units that make up the
17073 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17074 with a conventional script. For simple libraries, it is also possible to create
17075 a dummy main program which depends upon all the packages that comprise the
17076 interface of the library. This dummy main program can then be given to
17077 @command{gnatmake}, which will ensure that all necessary objects are built.
17079 After this task is accomplished, you should follow the standard procedure
17080 of the underlying operating system to produce the static or shared library.
17082 Here is an example of such a dummy program:
17083 @smallexample @c ada
17084 @group
17085 @b{with} My_Lib.Service1;
17086 @b{with} My_Lib.Service2;
17087 @b{with} My_Lib.Service3;
17088 @b{procedure} My_Lib_Dummy @b{is}
17089 @b{begin}
17090    @b{null};
17091 @b{end};
17092 @end group
17093 @end smallexample
17095 @noindent
17096 Here are the generic commands that will build an archive or a shared library.
17098 @smallexample
17099 # compiling the library
17100 $ gnatmake -c my_lib_dummy.adb
17102 # we don't need the dummy object itself
17103 $ rm my_lib_dummy.o my_lib_dummy.ali
17105 # create an archive with the remaining objects
17106 $ ar rc libmy_lib.a *.o
17107 # some systems may require "ranlib" to be run as well
17109 # or create a shared library
17110 $ gcc -shared -o libmy_lib.so *.o
17111 # some systems may require the code to have been compiled with -fPIC
17113 # remove the object files that are now in the library
17114 $ rm *.o
17116 # Make the ALI files read-only so that gnatmake will not try to
17117 # regenerate the objects that are in the library
17118 $ chmod -w *.ali
17119 @end smallexample
17121 @noindent
17122 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17123 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17124 be accessed by the directive @option{-l@var{xxx}} at link time.
17126 @node Installing a library
17127 @subsection Installing a library
17128 @cindex @code{ADA_PROJECT_PATH}
17129 @cindex @code{GPR_PROJECT_PATH}
17131 @noindent
17132 If you use project files, library installation is part of the library build
17133 process (@pxref{Installing a library with project files}).
17135 When project files are not an option, it is also possible, but not recommended,
17136 to install the library so that the sources needed to use the library are on the
17137 Ada source path and the ALI files & libraries be on the Ada Object path (see
17138 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17139 administrator can place general-purpose libraries in the default compiler
17140 paths, by specifying the libraries' location in the configuration files
17141 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17142 must be located in the GNAT installation tree at the same place as the gcc spec
17143 file. The location of the gcc spec file can be determined as follows:
17144 @smallexample
17145 $ gcc -v
17146 @end smallexample
17148 @noindent
17149 The configuration files mentioned above have a simple format: each line
17150 must contain one unique directory name.
17151 Those names are added to the corresponding path
17152 in their order of appearance in the file. The names can be either absolute
17153 or relative; in the latter case, they are relative to where theses files
17154 are located.
17156 The files @file{ada_source_path} and @file{ada_object_path} might not be
17157 present in a
17158 GNAT installation, in which case, GNAT will look for its run-time library in
17159 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17160 objects and @file{ALI} files). When the files exist, the compiler does not
17161 look in @file{adainclude} and @file{adalib}, and thus the
17162 @file{ada_source_path} file
17163 must contain the location for the GNAT run-time sources (which can simply
17164 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17165 contain the location for the GNAT run-time objects (which can simply
17166 be @file{adalib}).
17168 You can also specify a new default path to the run-time library at compilation
17169 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17170 the run-time library you want your program to be compiled with. This switch is
17171 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17172 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17174 It is possible to install a library before or after the standard GNAT
17175 library, by reordering the lines in the configuration files. In general, a
17176 library must be installed before the GNAT library if it redefines
17177 any part of it.
17179 @node Using a library
17180 @subsection Using a library
17182 @noindent Once again, the project facility greatly simplifies the use of
17183 libraries. In this context, using a library is just a matter of adding a
17184 @code{with} clause in the user project. For instance, to make use of the
17185 library @code{My_Lib} shown in examples in earlier sections, you can
17186 write:
17188 @smallexample @c projectfile
17189 @b{with} "my_lib";
17190 @b{project} My_Proj @b{is}
17191   @dots{}
17192 @b{end} My_Proj;
17193 @end smallexample
17195 Even if you have a third-party, non-Ada library, you can still use GNAT's
17196 Project Manager facility to provide a wrapper for it. For example, the
17197 following project, when @code{with}ed by your main project, will link with the
17198 third-party library @file{liba.a}:
17200 @smallexample @c projectfile
17201 @group
17202 @b{project} Liba @b{is}
17203    @b{for} Externally_Built @b{use} "true";
17204    @b{for} Source_Files @b{use} ();
17205    @b{for} Library_Dir @b{use} "lib";
17206    @b{for} Library_Name @b{use} "a";
17207    @b{for} Library_Kind @b{use} "static";
17208 @b{end} Liba;
17209 @end group
17210 @end smallexample
17211 This is an alternative to the use of @code{pragma Linker_Options}. It is
17212 especially interesting in the context of systems with several interdependent
17213 static libraries where finding a proper linker order is not easy and best be
17214 left to the tools having visibility over project dependence information.
17216 @noindent
17217 In order to use an Ada library manually, you need to make sure that this
17218 library is on both your source and object path
17219 (see @ref{Search Paths and the Run-Time Library (RTL)}
17220 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17221 in an archive or a shared library, you need to specify the desired
17222 library at link time.
17224 For example, you can use the library @file{mylib} installed in
17225 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17227 @smallexample
17228 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17229   -largs -lmy_lib
17230 @end smallexample
17232 @noindent
17233 This can be expressed more simply:
17234 @smallexample
17235 $ gnatmake my_appl
17236 @end smallexample
17237 @noindent
17238 when the following conditions are met:
17239 @itemize @bullet
17240 @item
17241 @file{/dir/my_lib_src} has been added by the user to the environment
17242 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17243 @file{ada_source_path}
17244 @item
17245 @file{/dir/my_lib_obj} has been added by the user to the environment
17246 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17247 @file{ada_object_path}
17248 @item
17249 a pragma @code{Linker_Options} has been added to one of the sources.
17250 For example:
17252 @smallexample @c ada
17253 @b{pragma} Linker_Options ("-lmy_lib");
17254 @end smallexample
17255 @end itemize
17257 Note that you may also load a library dynamically at
17258 run time given its filename, as illustrated in the GNAT @file{plugins} example
17259 in the directory @file{share/examples/gnat/plugins} within the GNAT
17260 install area.
17262 @node Stand-alone Ada Libraries
17263 @section Stand-alone Ada Libraries
17264 @cindex Stand-alone library, building, using
17266 @menu
17267 * Introduction to Stand-alone Libraries::
17268 * Building a Stand-alone Library::
17269 * Creating a Stand-alone Library to be used in a non-Ada context::
17270 * Restrictions in Stand-alone Libraries::
17271 @end menu
17273 @node Introduction to Stand-alone Libraries
17274 @subsection Introduction to Stand-alone Libraries
17276 @noindent
17277 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17278 necessary code to
17279 elaborate the Ada units that are included in the library. In contrast with
17280 an ordinary library, which consists of all sources, objects and @file{ALI}
17281 files of the
17282 library, a SAL may specify a restricted subset of compilation units
17283 to serve as a library interface. In this case, the fully
17284 self-sufficient set of files will normally consist of an objects
17285 archive, the sources of interface units' specs, and the @file{ALI}
17286 files of interface units.
17287 If an interface spec contains a generic unit or an inlined subprogram,
17288 the body's
17289 source must also be provided; if the units that must be provided in the source
17290 form depend on other units, the source and @file{ALI} files of those must
17291 also be provided.
17293 The main purpose of a SAL is to minimize the recompilation overhead of client
17294 applications when a new version of the library is installed. Specifically,
17295 if the interface sources have not changed, client applications do not need to
17296 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17297 version, controlled by @code{Library_Version} attribute, is not changed,
17298 then the clients do not need to be relinked.
17300 SALs also allow the library providers to minimize the amount of library source
17301 text exposed to the clients.  Such ``information hiding'' might be useful or
17302 necessary for various reasons.
17304 Stand-alone libraries are also well suited to be used in an executable whose
17305 main routine is not written in Ada.
17307 @node Building a Stand-alone Library
17308 @subsection Building a Stand-alone Library
17310 @noindent
17311 GNAT's Project facility provides a simple way of building and installing
17312 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17313 To be a Stand-alone Library Project, in addition to the two attributes
17314 that make a project a Library Project (@code{Library_Name} and
17315 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17316 @code{Library_Interface} must be defined.  For example:
17318 @smallexample @c projectfile
17319 @group
17320    @b{for} Library_Dir @b{use} "lib_dir";
17321    @b{for} Library_Name @b{use} "dummy";
17322    @b{for} Library_Interface @b{use} ("int1", "int1.child");
17323 @end group
17324 @end smallexample
17326 @noindent
17327 Attribute @code{Library_Interface} has a non-empty string list value,
17328 each string in the list designating a unit contained in an immediate source
17329 of the project file.
17331 When a Stand-alone Library is built, first the binder is invoked to build
17332 a package whose name depends on the library name
17333 (@file{b~dummy.ads/b} in the example above).
17334 This binder-generated package includes initialization and
17335 finalization procedures whose
17336 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17337 in the example
17338 above). The object corresponding to this package is included in the library.
17340 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17341 calling of these procedures if a static SAL is built, or if a shared SAL
17342 is built
17343 with the project-level attribute @code{Library_Auto_Init} set to
17344 @code{"false"}.
17346 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17347 (those that are listed in attribute @code{Library_Interface}) are copied to
17348 the Library Directory. As a consequence, only the Interface Units may be
17349 imported from Ada units outside of the library. If other units are imported,
17350 the binding phase will fail.
17352 @noindent
17353 It is also possible to build an encapsulated library where not only
17354 the code to elaborate and finalize the library is embedded but also
17355 ensuring that the library is linked only against static
17356 libraries. So an encapsulated library only depends on system
17357 libraries, all other code, including the GNAT runtime, is embedded. To
17358 build an encapsulated library the attribute
17359 @code{Library_Standalone} must be set to @code{encapsulated}:
17361 @smallexample @c projectfile
17362 @group
17363    @b{for} Library_Dir @b{use} "lib_dir";
17364    @b{for} Library_Name @b{use} "dummy";
17365    @b{for} Library_Kind @b{use} "dynamic";
17366    @b{for} Library_Interface @b{use} ("int1", "int1.child");
17367    @b{for} Library_Standalone @b{use} "encapsulated";
17368 @end group
17369 @end smallexample
17371 @noindent
17372 The default value for this attribute is @code{standard} in which case
17373 a stand-alone library is built.
17375 The attribute @code{Library_Src_Dir} may be specified for a
17376 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17377 single string value. Its value must be the path (absolute or relative to the
17378 project directory) of an existing directory. This directory cannot be the
17379 object directory or one of the source directories, but it can be the same as
17380 the library directory. The sources of the Interface
17381 Units of the library that are needed by an Ada client of the library will be
17382 copied to the designated directory, called the Interface Copy directory.
17383 These sources include the specs of the Interface Units, but they may also
17384 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17385 are used, or when there is a generic unit in the spec. Before the sources
17386 are copied to the Interface Copy directory, an attempt is made to delete all
17387 files in the Interface Copy directory.
17389 Building stand-alone libraries by hand is somewhat tedious, but for those
17390 occasions when it is necessary here are the steps that you need to perform:
17391 @itemize @bullet
17392 @item
17393 Compile all library sources.
17395 @item
17396 Invoke the binder with the switch @option{-n} (No Ada main program),
17397 with all the @file{ALI} files of the interfaces, and
17398 with the switch @option{-L} to give specific names to the @code{init}
17399 and @code{final} procedures.  For example:
17400 @smallexample
17401   gnatbind -n int1.ali int2.ali -Lsal1
17402 @end smallexample
17404 @item
17405 Compile the binder generated file:
17406 @smallexample
17407   gcc -c b~int2.adb
17408 @end smallexample
17410 @item
17411 Link the dynamic library with all the necessary object files,
17412 indicating to the linker the names of the @code{init} (and possibly
17413 @code{final}) procedures for automatic initialization (and finalization).
17414 The built library should be placed in a directory different from
17415 the object directory.
17417 @item
17418 Copy the @code{ALI} files of the interface to the library directory,
17419 add in this copy an indication that it is an interface to a SAL
17420 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17421 with letter ``P'') and make the modified copy of the @file{ALI} file
17422 read-only.
17423 @end itemize
17425 @noindent
17426 Using SALs is not different from using other libraries
17427 (see @ref{Using a library}).
17429 @node Creating a Stand-alone Library to be used in a non-Ada context
17430 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17432 @noindent
17433 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17434 a non-Ada context.
17436 The only extra step required is to ensure that library interface subprograms
17437 are compatible with the main program, by means of @code{pragma Export}
17438 or @code{pragma Convention}.
17440 Here is an example of simple library interface for use with C main program:
17442 @smallexample @c ada
17443 @b{package} My_Package @b{is}
17445    @b{procedure} Do_Something;
17446    @b{pragma} Export (C, Do_Something, "do_something");
17448    @b{procedure} Do_Something_Else;
17449    @b{pragma} Export (C, Do_Something_Else, "do_something_else");
17451 @b{end} My_Package;
17452 @end smallexample
17454 @noindent
17455 On the foreign language side, you must provide a ``foreign'' view of the
17456 library interface; remember that it should contain elaboration routines in
17457 addition to interface subprograms.
17459 The example below shows the content of @code{mylib_interface.h} (note
17460 that there is no rule for the naming of this file, any name can be used)
17461 @smallexample
17462 /* the library elaboration procedure */
17463 extern void mylibinit (void);
17465 /* the library finalization procedure */
17466 extern void mylibfinal (void);
17468 /* the interface exported by the library */
17469 extern void do_something (void);
17470 extern void do_something_else (void);
17471 @end smallexample
17473 @noindent
17474 Libraries built as explained above can be used from any program, provided
17475 that the elaboration procedures (named @code{mylibinit} in the previous
17476 example) are called before the library services are used. Any number of
17477 libraries can be used simultaneously, as long as the elaboration
17478 procedure of each library is called.
17480 Below is an example of a C program that uses the @code{mylib} library.
17482 @smallexample
17483 #include "mylib_interface.h"
17486 main (void)
17488    /* First, elaborate the library before using it */
17489    mylibinit ();
17491    /* Main program, using the library exported entities */
17492    do_something ();
17493    do_something_else ();
17495    /* Library finalization at the end of the program */
17496    mylibfinal ();
17497    return 0;
17499 @end smallexample
17501 @noindent
17502 Note that invoking any library finalization procedure generated by
17503 @code{gnatbind} shuts down the Ada run-time environment.
17504 Consequently, the
17505 finalization of all Ada libraries must be performed at the end of the program.
17506 No call to these libraries or to the Ada run-time library should be made
17507 after the finalization phase.
17509 @node Restrictions in Stand-alone Libraries
17510 @subsection Restrictions in Stand-alone Libraries
17512 @noindent
17513 The pragmas listed below should be used with caution inside libraries,
17514 as they can create incompatibilities with other Ada libraries:
17515 @itemize @bullet
17516 @item pragma @code{Locking_Policy}
17517 @item pragma @code{Partition_Elaboration_Policy}
17518 @item pragma @code{Queuing_Policy}
17519 @item pragma @code{Task_Dispatching_Policy}
17520 @item pragma @code{Unreserve_All_Interrupts}
17521 @end itemize
17523 @noindent
17524 When using a library that contains such pragmas, the user must make sure
17525 that all libraries use the same pragmas with the same values. Otherwise,
17526 @code{Program_Error} will
17527 be raised during the elaboration of the conflicting
17528 libraries. The usage of these pragmas and its consequences for the user
17529 should therefore be well documented.
17531 Similarly, the traceback in the exception occurrence mechanism should be
17532 enabled or disabled in a consistent manner across all libraries.
17533 Otherwise, Program_Error will be raised during the elaboration of the
17534 conflicting libraries.
17536 If the @code{Version} or @code{Body_Version}
17537 attributes are used inside a library, then you need to
17538 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17539 libraries, so that version identifiers can be properly computed.
17540 In practice these attributes are rarely used, so this is unlikely
17541 to be a consideration.
17543 @node  Rebuilding the GNAT Run-Time Library
17544 @section Rebuilding the GNAT Run-Time Library
17545 @cindex GNAT Run-Time Library, rebuilding
17546 @cindex Building the GNAT Run-Time Library
17547 @cindex Rebuilding the GNAT Run-Time Library
17548 @cindex Run-Time Library, rebuilding
17550 @noindent
17551 It may be useful to recompile the GNAT library in various contexts, the
17552 most important one being the use of partition-wide configuration pragmas
17553 such as @code{Normalize_Scalars}. A special Makefile called
17554 @code{Makefile.adalib} is provided to that effect and can be found in
17555 the directory containing the GNAT library. The location of this
17556 directory depends on the way the GNAT environment has been installed and can
17557 be determined by means of the command:
17559 @smallexample
17560 $ gnatls -v
17561 @end smallexample
17563 @noindent
17564 The last entry in the object search path usually contains the
17565 gnat library. This Makefile contains its own documentation and in
17566 particular the set of instructions needed to rebuild a new library and
17567 to use it.
17569 @node Using the GNU make Utility
17570 @chapter Using the GNU @code{make} Utility
17571 @findex make
17573 @noindent
17574 This chapter offers some examples of makefiles that solve specific
17575 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
17576 make, make, GNU @code{make}}), nor does it try to replace the
17577 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
17579 All the examples in this section are specific to the GNU version of
17580 make. Although @command{make} is a standard utility, and the basic language
17581 is the same, these examples use some advanced features found only in
17582 @code{GNU make}.
17584 @menu
17585 * Using gnatmake in a Makefile::
17586 * Automatically Creating a List of Directories::
17587 * Generating the Command Line Switches::
17588 * Overcoming Command Line Length Limits::
17589 @end menu
17591 @node Using gnatmake in a Makefile
17592 @section Using gnatmake in a Makefile
17593 @findex makefile
17594 @cindex GNU make
17596 @noindent
17597 Complex project organizations can be handled in a very powerful way by
17598 using GNU make combined with gnatmake. For instance, here is a Makefile
17599 which allows you to build each subsystem of a big project into a separate
17600 shared library. Such a makefile allows you to significantly reduce the link
17601 time of very big applications while maintaining full coherence at
17602 each step of the build process.
17604 The list of dependencies are handled automatically by
17605 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17606 the appropriate directories.
17608 Note that you should also read the example on how to automatically
17609 create the list of directories
17610 (@pxref{Automatically Creating a List of Directories})
17611 which might help you in case your project has a lot of subdirectories.
17613 @smallexample
17614 @iftex
17615 @leftskip=0cm
17616 @font@heightrm=cmr8
17617 @heightrm
17618 @end iftex
17619 ## This Makefile is intended to be used with the following directory
17620 ## configuration:
17621 ##  - The sources are split into a series of csc (computer software components)
17622 ##    Each of these csc is put in its own directory.
17623 ##    Their name are referenced by the directory names.
17624 ##    They will be compiled into shared library (although this would also work
17625 ##    with static libraries
17626 ##  - The main program (and possibly other packages that do not belong to any
17627 ##    csc is put in the top level directory (where the Makefile is).
17628 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17629 ##                    \_ second_csc (sources) __ lib (will contain the library)
17630 ##                    \_ @dots{}
17631 ## Although this Makefile is build for shared library, it is easy to modify
17632 ## to build partial link objects instead (modify the lines with -shared and
17633 ## gnatlink below)
17635 ## With this makefile, you can change any file in the system or add any new
17636 ## file, and everything will be recompiled correctly (only the relevant shared
17637 ## objects will be recompiled, and the main program will be re-linked).
17639 # The list of computer software component for your project. This might be
17640 # generated automatically.
17641 CSC_LIST=aa bb cc
17643 # Name of the main program (no extension)
17644 MAIN=main
17646 # If we need to build objects with -fPIC, uncomment the following line
17647 #NEED_FPIC=-fPIC
17649 # The following variable should give the directory containing libgnat.so
17650 # You can get this directory through 'gnatls -v'. This is usually the last
17651 # directory in the Object_Path.
17652 GLIB=@dots{}
17654 # The directories for the libraries
17655 # (This macro expands the list of CSC to the list of shared libraries, you
17656 # could simply use the expanded form:
17657 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17658 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17660 $@{MAIN@}: objects $@{LIB_DIR@}
17661     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17662     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17664 objects::
17665     # recompile the sources
17666     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17668 # Note: In a future version of GNAT, the following commands will be simplified
17669 # by a new tool, gnatmlib
17670 $@{LIB_DIR@}:
17671     mkdir -p $@{dir $@@ @}
17672     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17673     cd $@{dir $@@ @} && cp -f ../*.ali .
17675 # The dependencies for the modules
17676 # Note that we have to force the expansion of *.o, since in some cases
17677 # make won't be able to do it itself.
17678 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17679 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17680 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17682 # Make sure all of the shared libraries are in the path before starting the
17683 # program
17684 run::
17685     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17687 clean::
17688     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17689     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17690     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17691     $@{RM@} *.o *.ali $@{MAIN@}
17692 @end smallexample
17694 @node Automatically Creating a List of Directories
17695 @section Automatically Creating a List of Directories
17697 @noindent
17698 In most makefiles, you will have to specify a list of directories, and
17699 store it in a variable. For small projects, it is often easier to
17700 specify each of them by hand, since you then have full control over what
17701 is the proper order for these directories, which ones should be
17702 included.
17704 However, in larger projects, which might involve hundreds of
17705 subdirectories, it might be more convenient to generate this list
17706 automatically.
17708 The example below presents two methods. The first one, although less
17709 general, gives you more control over the list. It involves wildcard
17710 characters, that are automatically expanded by @command{make}. Its
17711 shortcoming is that you need to explicitly specify some of the
17712 organization of your project, such as for instance the directory tree
17713 depth, whether some directories are found in a separate tree, @enddots{}
17715 The second method is the most general one. It requires an external
17716 program, called @command{find}, which is standard on all Unix systems. All
17717 the directories found under a given root directory will be added to the
17718 list.
17720 @smallexample
17721 @iftex
17722 @leftskip=0cm
17723 @font@heightrm=cmr8
17724 @heightrm
17725 @end iftex
17726 # The examples below are based on the following directory hierarchy:
17727 # All the directories can contain any number of files
17728 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17729 #                       ->  ab
17730 #                       ->  ac
17731 #                ->  b  ->  ba  ->  baa
17732 #                       ->  bb
17733 #                       ->  bc
17734 # This Makefile creates a variable called DIRS, that can be reused any time
17735 # you need this list (see the other examples in this section)
17737 # The root of your project's directory hierarchy
17738 ROOT_DIRECTORY=.
17740 ####
17741 # First method: specify explicitly the list of directories
17742 # This allows you to specify any subset of all the directories you need.
17743 ####
17745 DIRS := a/aa/ a/ab/ b/ba/
17747 ####
17748 # Second method: use wildcards
17749 # Note that the argument(s) to wildcard below should end with a '/'.
17750 # Since wildcards also return file names, we have to filter them out
17751 # to avoid duplicate directory names.
17752 # We thus use make's @code{dir} and @code{sort} functions.
17753 # It sets DIRs to the following value (note that the directories aaa and baa
17754 # are not given, unless you change the arguments to wildcard).
17755 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17756 ####
17758 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17759                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17761 ####
17762 # Third method: use an external program
17763 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17764 # This is the most complete command: it sets DIRs to the following value:
17765 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17766 ####
17768 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17770 @end smallexample
17772 @node Generating the Command Line Switches
17773 @section Generating the Command Line Switches
17775 @noindent
17776 Once you have created the list of directories as explained in the
17777 previous section (@pxref{Automatically Creating a List of Directories}),
17778 you can easily generate the command line arguments to pass to gnatmake.
17780 For the sake of completeness, this example assumes that the source path
17781 is not the same as the object path, and that you have two separate lists
17782 of directories.
17784 @smallexample
17785 # see "Automatically creating a list of directories" to create
17786 # these variables
17787 SOURCE_DIRS=
17788 OBJECT_DIRS=
17790 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17791 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17793 all:
17794         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17795 @end smallexample
17797 @node Overcoming Command Line Length Limits
17798 @section Overcoming Command Line Length Limits
17800 @noindent
17801 One problem that might be encountered on big projects is that many
17802 operating systems limit the length of the command line. It is thus hard to give
17803 gnatmake the list of source and object directories.
17805 This example shows how you can set up environment variables, which will
17806 make @command{gnatmake} behave exactly as if the directories had been
17807 specified on the command line, but have a much higher length limit (or
17808 even none on most systems).
17810 It assumes that you have created a list of directories in your Makefile,
17811 using one of the methods presented in
17812 @ref{Automatically Creating a List of Directories}.
17813 For the sake of completeness, we assume that the object
17814 path (where the ALI files are found) is different from the sources patch.
17816 Note a small trick in the Makefile below: for efficiency reasons, we
17817 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17818 expanded immediately by @code{make}. This way we overcome the standard
17819 make behavior which is to expand the variables only when they are
17820 actually used.
17822 On Windows, if you are using the standard Windows command shell, you must
17823 replace colons with semicolons in the assignments to these variables.
17825 @smallexample
17826 @iftex
17827 @leftskip=0cm
17828 @font@heightrm=cmr8
17829 @heightrm
17830 @end iftex
17831 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17832 # This is the same thing as putting the -I arguments on the command line.
17833 # (the equivalent of using -aI on the command line would be to define
17834 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17835 # You can of course have different values for these variables.
17837 # Note also that we need to keep the previous values of these variables, since
17838 # they might have been set before running 'make' to specify where the GNAT
17839 # library is installed.
17841 # see "Automatically creating a list of directories" to create these
17842 # variables
17843 SOURCE_DIRS=
17844 OBJECT_DIRS=
17846 empty:=
17847 space:=$@{empty@} $@{empty@}
17848 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17849 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17850 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17851 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17852 export ADA_INCLUDE_PATH
17853 export ADA_OBJECTS_PATH
17855 all:
17856         gnatmake main_unit
17857 @end smallexample
17859 @node Memory Management Issues
17860 @chapter Memory Management Issues
17862 @noindent
17863 This chapter describes some useful memory pools provided in the GNAT library
17864 and in particular the GNAT Debug Pool facility, which can be used to detect
17865 incorrect uses of access values (including ``dangling references'').
17866 @ifclear FSFEDITION
17867 It also describes the @command{gnatmem} tool, which can be used to track down
17868 ``memory leaks''.
17869 @end ifclear
17871 @menu
17872 * Some Useful Memory Pools::
17873 * The GNAT Debug Pool Facility::
17874 @ifclear FSFEDITION
17875 * The gnatmem Tool::
17876 @end ifclear
17877 @end menu
17879 @node Some Useful Memory Pools
17880 @section Some Useful Memory Pools
17881 @findex Memory Pool
17882 @cindex storage, pool
17884 @noindent
17885 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17886 storage pool. Allocations use the standard system call @code{malloc} while
17887 deallocations use the standard system call @code{free}. No reclamation is
17888 performed when the pool goes out of scope. For performance reasons, the
17889 standard default Ada allocators/deallocators do not use any explicit storage
17890 pools but if they did, they could use this storage pool without any change in
17891 behavior. That is why this storage pool is used  when the user
17892 manages to make the default implicit allocator explicit as in this example:
17893 @smallexample @c ada
17894    @b{type} T1 @b{is} @b{access} Something;
17895     --@i{ no Storage pool is defined for T2}
17896    @b{type} T2 @b{is} @b{access} Something_Else;
17897    @b{for} T2'Storage_Pool @b{use} T1'Storage_Pool;
17898    --@i{ the above is equivalent to}
17899    @b{for} T2'Storage_Pool @b{use} System.Pool_Global.Global_Pool_Object;
17900 @end smallexample
17902 @noindent
17903 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17904 pool. The allocation strategy is similar to @code{Pool_Local}'s
17905 except that the all
17906 storage allocated with this pool is reclaimed when the pool object goes out of
17907 scope. This pool provides a explicit mechanism similar to the implicit one
17908 provided by several Ada 83 compilers for allocations performed through a local
17909 access type and whose purpose was to reclaim memory when exiting the
17910 scope of a given local access. As an example, the following program does not
17911 leak memory even though it does not perform explicit deallocation:
17913 @smallexample @c ada
17914 @b{with} System.Pool_Local;
17915 @b{procedure} Pooloc1 @b{is}
17916    @b{procedure} Internal @b{is}
17917       @b{type} A @b{is} @b{access} Integer;
17918       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17919       @b{for} A'Storage_Pool @b{use} X;
17920       v : A;
17921    @b{begin}
17922       @b{for} I @b{in}  1 .. 50 @b{loop}
17923          v := @b{new} Integer;
17924       @b{end} @b{loop};
17925    @b{end} Internal;
17926 @b{begin}
17927    @b{for} I @b{in}  1 .. 100 @b{loop}
17928       Internal;
17929    @b{end} @b{loop};
17930 @b{end} Pooloc1;
17931 @end smallexample
17933 @noindent
17934 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17935 @code{Storage_Size} is specified for an access type.
17936 The whole storage for the pool is
17937 allocated at once, usually on the stack at the point where the access type is
17938 elaborated. It is automatically reclaimed when exiting the scope where the
17939 access type is defined. This package is not intended to be used directly by the
17940 user and it is implicitly used for each such declaration:
17942 @smallexample @c ada
17943    @b{type} T1 @b{is} @b{access} Something;
17944    @b{for} T1'Storage_Size @b{use} 10_000;
17945 @end smallexample
17947 @node The GNAT Debug Pool Facility
17948 @section The GNAT Debug Pool Facility
17949 @findex Debug Pool
17950 @cindex storage, pool, memory corruption
17952 @noindent
17953 The use of unchecked deallocation and unchecked conversion can easily
17954 lead to incorrect memory references. The problems generated by such
17955 references are usually difficult to tackle because the symptoms can be
17956 very remote from the origin of the problem. In such cases, it is
17957 very helpful to detect the problem as early as possible. This is the
17958 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17960 In order to use the GNAT specific debugging pool, the user must
17961 associate a debug pool object with each of the access types that may be
17962 related to suspected memory problems. See Ada Reference Manual 13.11.
17963 @smallexample @c ada
17964 @b{type} Ptr @b{is} @b{access} Some_Type;
17965 Pool : GNAT.Debug_Pools.Debug_Pool;
17966 @b{for} Ptr'Storage_Pool @b{use} Pool;
17967 @end smallexample
17969 @noindent
17970 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17971 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17972 allow the user to redefine allocation and deallocation strategies. They
17973 also provide a checkpoint for each dereference, through the use of
17974 the primitive operation @code{Dereference} which is implicitly called at
17975 each dereference of an access value.
17977 Once an access type has been associated with a debug pool, operations on
17978 values of the type may raise four distinct exceptions,
17979 which correspond to four potential kinds of memory corruption:
17980 @itemize @bullet
17981 @item
17982 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17983 @item
17984 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17985 @item
17986 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17987 @item
17988 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17989 @end itemize
17991 @noindent
17992 For types associated with a Debug_Pool, dynamic allocation is performed using
17993 the standard GNAT allocation routine. References to all allocated chunks of
17994 memory are kept in an internal dictionary. Several deallocation strategies are
17995 provided, whereupon the user can choose to release the memory to the system,
17996 keep it allocated for further invalid access checks, or fill it with an easily
17997 recognizable pattern for debug sessions. The memory pattern is the old IBM
17998 hexadecimal convention: @code{16#DEADBEEF#}.
18000 See the documentation in the file g-debpoo.ads for more information on the
18001 various strategies.
18003 Upon each dereference, a check is made that the access value denotes a
18004 properly allocated memory location. Here is a complete example of use of
18005 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18006 @smallexample @c ada
18007 @iftex
18008 @leftskip=0cm
18009 @end iftex
18010 @b{with} Gnat.Io; @b{use} Gnat.Io;
18011 @b{with} Unchecked_Deallocation;
18012 @b{with} Unchecked_Conversion;
18013 @b{with} GNAT.Debug_Pools;
18014 @b{with} System.Storage_Elements;
18015 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
18016 @b{procedure} Debug_Pool_Test @b{is}
18018    @b{type} T @b{is} @b{access} Integer;
18019    @b{type} U @b{is} @b{access} @b{all} T;
18021    P : GNAT.Debug_Pools.Debug_Pool;
18022    @b{for} T'Storage_Pool @b{use} P;
18024    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
18025    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
18026    A, B : @b{aliased} T;
18028    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
18030 @b{begin}
18031    Info (P);
18032    A := @b{new} Integer;
18033    B := @b{new} Integer;
18034    B := A;
18035    Info (P);
18036    Free (A);
18037    @b{begin}
18038       Put_Line (Integer'Image(B.@b{all}));
18039    @b{exception}
18040       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18041    @b{end};
18042    @b{begin}
18043       Free (B);
18044    @b{exception}
18045       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18046    @b{end};
18047    B := UC(A'Access);
18048    @b{begin}
18049       Put_Line (Integer'Image(B.@b{all}));
18050    @b{exception}
18051       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18052    @b{end};
18053    @b{begin}
18054       Free (B);
18055    @b{exception}
18056       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18057    @b{end};
18058    Info (P);
18059 @b{end} Debug_Pool_Test;
18060 @end smallexample
18062 @noindent
18063 The debug pool mechanism provides the following precise diagnostics on the
18064 execution of this erroneous program:
18065 @smallexample
18066 Debug Pool info:
18067   Total allocated bytes :  0
18068   Total deallocated bytes :  0
18069   Current Water Mark:  0
18070   High Water Mark:  0
18072 Debug Pool info:
18073   Total allocated bytes :  8
18074   Total deallocated bytes :  0
18075   Current Water Mark:  8
18076   High Water Mark:  8
18078 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18079 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18080 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18081 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18082 Debug Pool info:
18083   Total allocated bytes :  8
18084   Total deallocated bytes :  4
18085   Current Water Mark:  4
18086   High Water Mark:  8
18087 @end smallexample
18089 @ifclear FSFEDITION
18090 @node The gnatmem Tool
18091 @section The @command{gnatmem} Tool
18092 @findex gnatmem
18094 @noindent
18095 The @code{gnatmem} utility monitors dynamic allocation and
18096 deallocation activity in a program, and displays information about
18097 incorrect deallocations and possible sources of memory leaks.
18098 It is designed to work in association with a static runtime library
18099 only and in this context provides three types of information:
18100 @itemize @bullet
18101 @item
18102 General information concerning memory management, such as the total
18103 number of allocations and deallocations, the amount of allocated
18104 memory and the high water mark, i.e.@: the largest amount of allocated
18105 memory in the course of program execution.
18107 @item
18108 Backtraces for all incorrect deallocations, that is to say deallocations
18109 which do not correspond to a valid allocation.
18111 @item
18112 Information on each allocation that is potentially the origin of a memory
18113 leak.
18114 @end itemize
18116 @menu
18117 * Running gnatmem::
18118 * Switches for gnatmem::
18119 * Example of gnatmem Usage::
18120 @end menu
18122 @node Running gnatmem
18123 @subsection Running @code{gnatmem}
18125 @noindent
18126 @code{gnatmem} makes use of the output created by the special version of
18127 allocation and deallocation routines that record call information. This allows
18128 it to obtain accurate dynamic memory usage history at a minimal cost to the
18129 execution speed. Note however, that @code{gnatmem} is not supported on all
18130 platforms (currently, it is supported on AIX, HP-UX, GNU/Linux, Solaris and
18131 Windows NT/2000/XP (x86).
18133 @noindent
18134 The @code{gnatmem} command has the form
18136 @smallexample
18137 @c    $ gnatmem @ovar{switches} user_program
18138 @c Expanding @ovar macro inline (explanation in macro def comments)
18139       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18140 @end smallexample
18142 @noindent
18143 The program must have been linked with the instrumented version of the
18144 allocation and deallocation routines. This is done by linking with the
18145 @file{libgmem.a} library. For correct symbolic backtrace information,
18146 the user program should be compiled with debugging options
18147 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18149 @smallexample
18150 $ gnatmake -g my_program -largs -lgmem
18151 @end smallexample
18153 @noindent
18154 As library @file{libgmem.a} contains an alternate body for package
18155 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18156 when an executable is linked with library @file{libgmem.a}. It is then not
18157 recommended to use @command{gnatmake} with switch @option{-a}.
18159 @noindent
18160 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18161 This file contains information about all allocations and deallocations
18162 performed by the program. It is produced by the instrumented allocations and
18163 deallocations routines and will be used by @code{gnatmem}.
18165 In order to produce symbolic backtrace information for allocations and
18166 deallocations performed by the GNAT run-time library, you need to use a
18167 version of that library that has been compiled with the @option{-g} switch
18168 (see @ref{Rebuilding the GNAT Run-Time Library}).
18170 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18171 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18172 @option{-i} switch, gnatmem will assume that this file can be found in the
18173 current directory. For example, after you have executed @file{my_program},
18174 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18176 @smallexample
18177 $ gnatmem my_program
18178 @end smallexample
18180 @noindent
18181 This will produce the output with the following format:
18183 *************** debut cc
18184 @smallexample
18185 $ gnatmem my_program
18187 Global information
18188 ------------------
18189    Total number of allocations        :  45
18190    Total number of deallocations      :   6
18191    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18192    High Water Mark                    :  11.40 Kilobytes
18197 Allocation Root # 2
18198 -------------------
18199  Number of non freed allocations    :  11
18200  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18201  High Water Mark                    :   1.27 Kilobytes
18202  Backtrace                          :
18203    my_program.adb:23 my_program.alloc
18207 @end smallexample
18209 The first block of output gives general information. In this case, the
18210 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18211 Unchecked_Deallocation routine occurred.
18213 @noindent
18214 Subsequent paragraphs display  information on all allocation roots.
18215 An allocation root is a specific point in the execution of the program
18216 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18217 construct. This root is represented by an execution backtrace (or subprogram
18218 call stack). By default the backtrace depth for allocations roots is 1, so
18219 that a root corresponds exactly to a source location. The backtrace can
18220 be made deeper, to make the root more specific.
18222 @node Switches for gnatmem
18223 @subsection Switches for @code{gnatmem}
18225 @noindent
18226 @code{gnatmem} recognizes the following switches:
18228 @table @option
18230 @item -q
18231 @cindex @option{-q} (@code{gnatmem})
18232 Quiet. Gives the minimum output needed to identify the origin of the
18233 memory leaks. Omits statistical information.
18235 @item @var{N}
18236 @cindex @var{N} (@code{gnatmem})
18237 N is an integer literal (usually between 1 and 10) which controls the
18238 depth of the backtraces defining allocation root. The default value for
18239 N is 1. The deeper the backtrace, the more precise the localization of
18240 the root. Note that the total number of roots can depend on this
18241 parameter. This parameter must be specified @emph{before} the name of the
18242 executable to be analyzed, to avoid ambiguity.
18244 @item -b n
18245 @cindex @option{-b} (@code{gnatmem})
18246 This switch has the same effect as just depth parameter.
18248 @item -i @var{file}
18249 @cindex @option{-i} (@code{gnatmem})
18250 Do the @code{gnatmem} processing starting from @file{file}, rather than
18251 @file{gmem.out} in the current directory.
18253 @item -m n
18254 @cindex @option{-m} (@code{gnatmem})
18255 This switch causes @code{gnatmem} to mask the allocation roots that have less
18256 than n leaks.  The default value is 1. Specifying the value of 0 will allow
18257 examination of even the roots that did not result in leaks.
18259 @item -s order
18260 @cindex @option{-s} (@code{gnatmem})
18261 This switch causes @code{gnatmem} to sort the allocation roots according to the
18262 specified order of sort criteria, each identified by a single letter. The
18263 currently supported criteria are @code{n, h, w} standing respectively for
18264 number of unfreed allocations, high watermark, and final watermark
18265 corresponding to a specific root. The default order is @code{nwh}.
18267 @item -t
18268 @cindex @option{-t} (@code{gnatmem})
18269 This switch causes memory allocated size to be always output in bytes.
18270 Default @code{gnatmem} behavior is to show memory sizes less then 1 kilobyte
18271 in bytes, from 1 kilobyte till 1 megabyte in kilobytes and the rest in
18272 megabytes.
18274 @end table
18276 @node Example of gnatmem Usage
18277 @subsection Example of @code{gnatmem} Usage
18279 @noindent
18280 The following example shows the use of @code{gnatmem}
18281 on a simple memory-leaking program.
18282 Suppose that we have the following Ada program:
18284 @smallexample @c ada
18285 @group
18286 @cartouche
18287 @b{with} Unchecked_Deallocation;
18288 @b{procedure} Test_Gm @b{is}
18290    @b{type} T @b{is} @b{array} (1..1000) @b{of} Integer;
18291    @b{type} Ptr @b{is} @b{access} T;
18292    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (T, Ptr);
18293    A : Ptr;
18295    @b{procedure} My_Alloc @b{is}
18296    @b{begin}
18297       A := @b{new} T;
18298    @b{end} My_Alloc;
18300    @b{procedure} My_DeAlloc @b{is}
18301       B : Ptr := A;
18302    @b{begin}
18303       Free (B);
18304    @b{end} My_DeAlloc;
18306 @b{begin}
18307    My_Alloc;
18308    @b{for} I @b{in} 1 .. 5 @b{loop}
18309       @b{for} J @b{in} I .. 5 @b{loop}
18310          My_Alloc;
18311       @b{end} @b{loop};
18312       My_Dealloc;
18313    @b{end} @b{loop};
18314 @b{end};
18315 @end cartouche
18316 @end group
18317 @end smallexample
18319 @noindent
18320 The program needs to be compiled with debugging option and linked with
18321 @code{gmem} library:
18323 @smallexample
18324 $ gnatmake -g test_gm -largs -lgmem
18325 @end smallexample
18327 @noindent
18328 Then we execute the program as usual:
18330 @smallexample
18331 $ test_gm
18332 @end smallexample
18334 @noindent
18335 Then @code{gnatmem} is invoked simply with
18336 @smallexample
18337 $ gnatmem test_gm
18338 @end smallexample
18340 @noindent
18341 which produces the following output (result may vary on different platforms):
18343 @smallexample
18344 Global information
18345 ------------------
18346    Total number of allocations        :  18
18347    Total number of deallocations      :   5
18348    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18349    High Water Mark                    :  56.90 Kilobytes
18351 Allocation Root # 1
18352 -------------------
18353  Number of non freed allocations    :  11
18354  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18355  High Water Mark                    :  46.88 Kilobytes
18356  Backtrace                          :
18357    test_gm.adb:11 test_gm.my_alloc
18359 Allocation Root # 2
18360 -------------------
18361  Number of non freed allocations    :   1
18362  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18363  High Water Mark                    :  10.02 Kilobytes
18364  Backtrace                          :
18365    s-secsta.adb:81 system.secondary_stack.ss_init
18367 Allocation Root # 3
18368 -------------------
18369  Number of non freed allocations    :   1
18370  Final Water Mark (non freed mem)   :  12 Bytes
18371  High Water Mark                    :  12 Bytes
18372  Backtrace                          :
18373    s-secsta.adb:181 system.secondary_stack.ss_init
18374 @end smallexample
18376 @noindent
18377 Note that the GNAT run time contains itself a certain number of
18378 allocations that have no  corresponding deallocation,
18379 as shown here for root #2 and root
18380 #3. This is a normal behavior when the number of non-freed allocations
18381 is one, it allocates dynamic data structures that the run time needs for
18382 the complete lifetime of the program. Note also that there is only one
18383 allocation root in the user program with a single line back trace:
18384 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18385 program shows that 'My_Alloc' is called at 2 different points in the
18386 source (line 21 and line 24). If those two allocation roots need to be
18387 distinguished, the backtrace depth parameter can be used:
18389 @smallexample
18390 $ gnatmem 3 test_gm
18391 @end smallexample
18393 @noindent
18394 which will give the following output:
18396 @smallexample
18397 Global information
18398 ------------------
18399    Total number of allocations        :  18
18400    Total number of deallocations      :   5
18401    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18402    High Water Mark                    :  56.90 Kilobytes
18404 Allocation Root # 1
18405 -------------------
18406  Number of non freed allocations    :  10
18407  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18408  High Water Mark                    :  42.97 Kilobytes
18409  Backtrace                          :
18410    test_gm.adb:11 test_gm.my_alloc
18411    test_gm.adb:24 test_gm
18412    b_test_gm.c:52 main
18414 Allocation Root # 2
18415 -------------------
18416  Number of non freed allocations    :   1
18417  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18418  High Water Mark                    :  10.02 Kilobytes
18419  Backtrace                          :
18420    s-secsta.adb:81  system.secondary_stack.ss_init
18421    s-secsta.adb:283 <system__secondary_stack___elabb>
18422    b_test_gm.c:33   adainit
18424 Allocation Root # 3
18425 -------------------
18426  Number of non freed allocations    :   1
18427  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18428  High Water Mark                    :   3.91 Kilobytes
18429  Backtrace                          :
18430    test_gm.adb:11 test_gm.my_alloc
18431    test_gm.adb:21 test_gm
18432    b_test_gm.c:52 main
18434 Allocation Root # 4
18435 -------------------
18436  Number of non freed allocations    :   1
18437  Final Water Mark (non freed mem)   :  12 Bytes
18438  High Water Mark                    :  12 Bytes
18439  Backtrace                          :
18440    s-secsta.adb:181 system.secondary_stack.ss_init
18441    s-secsta.adb:283 <system__secondary_stack___elabb>
18442    b_test_gm.c:33   adainit
18443 @end smallexample
18445 @noindent
18446 The allocation root #1 of the first example has been split in 2 roots #1
18447 and #3 thanks to the more precise associated backtrace.
18448 @end ifclear
18450 @node Stack Related Facilities
18451 @chapter Stack Related Facilities
18453 @noindent
18454 This chapter describes some useful tools associated with stack
18455 checking and analysis. In
18456 particular, it deals with dynamic and static stack usage measurements.
18458 @menu
18459 * Stack Overflow Checking::
18460 * Static Stack Usage Analysis::
18461 * Dynamic Stack Usage Analysis::
18462 @end menu
18464 @node Stack Overflow Checking
18465 @section Stack Overflow Checking
18466 @cindex Stack Overflow Checking
18467 @cindex -fstack-check
18469 @noindent
18470 For most operating systems, @command{gcc} does not perform stack overflow
18471 checking by default. This means that if the main environment task or
18472 some other task exceeds the available stack space, then unpredictable
18473 behavior will occur. Most native systems offer some level of protection by
18474 adding a guard page at the end of each task stack. This mechanism is usually
18475 not enough for dealing properly with stack overflow situations because
18476 a large local variable could ``jump'' above the guard page.
18477 Furthermore, when the
18478 guard page is hit, there may not be any space left on the stack for executing
18479 the exception propagation code. Enabling stack checking avoids
18480 such situations.
18482 To activate stack checking, compile all units with the gcc option
18483 @option{-fstack-check}. For example:
18485 @smallexample
18486 gcc -c -fstack-check package1.adb
18487 @end smallexample
18489 @noindent
18490 Units compiled with this option will generate extra instructions to check
18491 that any use of the stack (for procedure calls or for declaring local
18492 variables in declare blocks) does not exceed the available stack space.
18493 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18495 For declared tasks, the stack size is controlled by the size
18496 given in an applicable @code{Storage_Size} pragma or by the value specified
18497 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18498 the default size as defined in the GNAT runtime otherwise.
18500 For the environment task, the stack size depends on
18501 system defaults and is unknown to the compiler. Stack checking
18502 may still work correctly if a fixed
18503 size stack is allocated, but this cannot be guaranteed.
18504 To ensure that a clean exception is signalled for stack
18505 overflow, set the environment variable
18506 @env{GNAT_STACK_LIMIT} to indicate the maximum
18507 stack area that can be used, as in:
18508 @cindex GNAT_STACK_LIMIT
18510 @smallexample
18511 SET GNAT_STACK_LIMIT 1600
18512 @end smallexample
18514 @noindent
18515 The limit is given in kilobytes, so the above declaration would
18516 set the stack limit of the environment task to 1.6 megabytes.
18517 Note that the only purpose of this usage is to limit the amount
18518 of stack used by the environment task. If it is necessary to
18519 increase the amount of stack for the environment task, then this
18520 is an operating systems issue, and must be addressed with the
18521 appropriate operating systems commands.
18523 @node Static Stack Usage Analysis
18524 @section Static Stack Usage Analysis
18525 @cindex Static Stack Usage Analysis
18526 @cindex -fstack-usage
18528 @noindent
18529 A unit compiled with @option{-fstack-usage} will generate an extra file
18530 that specifies
18531 the maximum amount of stack used, on a per-function basis.
18532 The file has the same
18533 basename as the target object file with a @file{.su} extension.
18534 Each line of this file is made up of three fields:
18536 @itemize
18537 @item
18538 The name of the function.
18539 @item
18540 A number of bytes.
18541 @item
18542 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18543 @end itemize
18545 The second field corresponds to the size of the known part of the function
18546 frame.
18548 The qualifier @code{static} means that the function frame size
18549 is purely static.
18550 It usually means that all local variables have a static size.
18551 In this case, the second field is a reliable measure of the function stack
18552 utilization.
18554 The qualifier @code{dynamic} means that the function frame size is not static.
18555 It happens mainly when some local variables have a dynamic size. When this
18556 qualifier appears alone, the second field is not a reliable measure
18557 of the function stack analysis. When it is qualified with  @code{bounded}, it
18558 means that the second field is a reliable maximum of the function stack
18559 utilization.
18561 A unit compiled with @option{-Wstack-usage} will issue a warning for each
18562 subprogram whose stack usage might be larger than the specified amount of
18563 bytes.  The wording is in keeping with the qualifier documented above.
18565 @node Dynamic Stack Usage Analysis
18566 @section Dynamic Stack Usage Analysis
18568 @noindent
18569 It is possible to measure the maximum amount of stack used by a task, by
18570 adding a switch to @command{gnatbind}, as:
18572 @smallexample
18573 $ gnatbind -u0 file
18574 @end smallexample
18576 @noindent
18577 With this option, at each task termination, its stack usage is  output on
18578 @file{stderr}.
18579 It is not always convenient to output the stack usage when the program
18580 is still running. Hence, it is possible to delay this output until program
18581 termination. for a given number of tasks specified as the argument of the
18582 @option{-u} option. For instance:
18584 @smallexample
18585 $ gnatbind -u100 file
18586 @end smallexample
18588 @noindent
18589 will buffer the stack usage information of the first 100 tasks to terminate and
18590 output this info at program termination. Results are displayed in four
18591 columns:
18593 @noindent
18594 Index | Task Name | Stack Size | Stack Usage
18596 @noindent
18597 where:
18599 @table @emph
18600 @item Index
18601 is a number associated with each task.
18603 @item Task Name
18604 is the name of the task analyzed.
18606 @item Stack Size
18607 is the maximum size for the stack.
18609 @item Stack Usage
18610 is the measure done by the stack analyzer. In order to prevent overflow, the stack
18611 is not entirely analyzed, and it's not possible to know exactly how
18612 much has actually been used.
18614 @end table
18616 @noindent
18617 The environment task stack, e.g., the stack that contains the main unit, is
18618 only processed when the environment variable GNAT_STACK_LIMIT is set.
18620 @noindent
18621 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
18622 stack usage reports at run-time. See its body for the details.
18624 @ifclear FSFEDITION
18625 @c *********************************
18626 @c *            GNATCHECK          *
18627 @c *********************************
18628 @node Verifying Properties with gnatcheck
18629 @chapter Verifying Properties with @command{gnatcheck}
18630 @findex gnatcheck
18631 @cindex @command{gnatcheck}
18633 @noindent
18634 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18635 of Ada source files according to a given set of semantic rules.
18636 @cindex ASIS
18638 In order to check compliance with a given rule, @command{gnatcheck} has to
18639 semantically analyze the Ada sources.
18640 Therefore, checks can only be performed on
18641 legal Ada units. Moreover, when a unit depends semantically upon units located
18642 outside the current directory, the source search path has to be provided when
18643 calling @command{gnatcheck}, either through a specified project file or
18644 through @command{gnatcheck} switches.
18646 For full details, refer to @cite{GNATcheck Reference Manual} document.
18647 @end ifclear
18649 @ifclear FSFEDITION
18650 @c *********************************
18651 @node Creating Sample Bodies with gnatstub
18652 @chapter Creating Sample Bodies with @command{gnatstub}
18653 @findex gnatstub
18655 @noindent
18656 @command{gnatstub} creates empty but compilable bodies
18657 for library unit declarations and empty but compilable
18658 subunit for body stubs.
18660 To create a body or a subunit, @command{gnatstub} invokes the Ada
18661 compiler and generates and uses the ASIS tree for the input source;
18662 thus the input must be legal Ada code, and the tool should have all the
18663 information needed to compile the input source. To provide this information,
18664 you may specify as a tool parameter the project file the input source belongs to
18665 (or you may call @command{gnatstub}
18666 through the @command{gnat} driver (see @ref{The GNAT Driver and
18667 Project Files}). Another possibility is to specify the source search
18668 path and needed configuration files in @option{-cargs} section of @command{gnatstub}
18669 call, see the description of the @command{gnatstub} switches below.
18671 If the @command{gnatstub} argument source contains preprocessing directives
18672 then the needed options should be provided to run preprocessor as a part of
18673 the @command{gnatstub} call, and the generated body stub will correspond to
18674 the preprocessed source.
18676 By default, all the program unit bodies generated by @code{gnatstub}
18677 raise the predefined @code{Program_Error} exception, which will catch
18678 accidental calls of generated stubs. This behavior can be changed with
18679 option @option{--no-exception} (see below).
18681 @menu
18682 * Running gnatstub::
18683 * Switches for gnatstub::
18684 @end menu
18686 @node Running gnatstub
18687 @section Running @command{gnatstub}
18689 @noindent
18690 @command{gnatstub} has a command-line interface of the form:
18692 @smallexample
18693 @c $ gnatstub @ovar{switches} @var{filename}
18694 @c Expanding @ovar macro inline (explanation in macro def comments)
18695 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
18696 @end smallexample
18698 @noindent
18699 where
18700 @table @var
18701 @item filename
18702 is the name of the source file that contains a library unit declaration
18703 for which a body must be created or a library unit body for which subunits
18704 must be created for the body stubs declared in this body.
18705 The file name may contain the path information.
18706 If the name does not follow GNAT file naming conventions and a set
18707 of seitches does not contain a project file that defines naming
18708 conventions, the name of the body file must
18709 be provided
18710 explicitly as the value of the @option{-o@var{body-name}} option.
18711 If the file name follows the GNAT file naming
18712 conventions and the name of the body file is not provided,
18713 @command{gnatstub}
18714 takes the naming conventions for the generated source from the
18715 project file provided as a parameter of @option{-P} switch if any,
18716 or creates the name file to generate using the standard GNAT
18717 naming conventions.
18719 @item @samp{@var{gcc_switches}} is a list of switches for
18720 @command{gcc}. They will be passed on to all compiler invocations made by
18721 @command{gnatstub} to generate the ASIS trees. Here you can provide
18722 @option{-I} switches to form the source search path,
18723 use the @option{-gnatec} switch to set the configuration file,
18724 use the @option{-gnat05} switch if sources should be compiled in
18725 Ada 2005 mode etc.
18727 @item switches
18728 is an optional sequence of switches as described in the next section
18729 @end table
18731 @node Switches for gnatstub
18732 @section Switches for @command{gnatstub}
18734 @table @option
18735 @c !sort!
18737 @item --version
18738 @cindex @option{--version} @command{gnatstub}
18739 Display Copyright and version, then exit disregarding all other options.
18741 @item --help
18742 @cindex @option{--help} @command{gnatstub}
18743 Display usage, then exit disregarding all other options.
18745 @item -P @var{file}
18746 @cindex @option{-P} @command{gnatstub}
18747 Indicates the name of the project file that describes the set of sources
18748 to be processed.
18750 @item -X@var{name}=@var{value}
18751 @cindex @option{-X} @command{gnatstub}
18752 Indicates that external variable @var{name} in the argument project
18753 has the value @var{value}. Has no effect if no project is specified as
18754 tool argument.
18756 @item --subunits
18757 @cindex @option{--subunits} (@command{gnatstub})
18758 Generate subunits for body stubs. If this switch is specified,
18759 @command{gnatstub} expects a library unit body as an agrument file,
18760 otherwise a library unit declaration is expected. If a body stub
18761 already has a corresponding subunit, @command{gnatstub} does not
18762 generate anything for it.
18764 @item -f
18765 @cindex @option{-f} (@command{gnatstub})
18766 If the destination directory already contains a file with the name of the
18767 body file
18768 for the argument spec file, replace it with the generated body stub.
18769 This switch cannot be used together with @option{--subunits}.
18771 @item -hs
18772 @cindex @option{-hs} (@command{gnatstub})
18773 Put the comment header (i.e., all the comments preceding the
18774 compilation unit) from the source of the library unit declaration
18775 into the body stub.
18777 @item -hg
18778 @cindex @option{-hg} (@command{gnatstub})
18779 Put a sample comment header into the body stub.
18781 @item --header-file=@var{filename}
18782 @cindex @option{--header-file} (@command{gnatstub})
18783 Use the content of the file as the comment header for a generated body stub.
18785 @item -IDIR
18786 @cindex @option{-IDIR} (@command{gnatstub})
18787 @itemx -I-
18788 @cindex @option{-I-} (@command{gnatstub})
18789 These switches have  the same meaning as in calls to
18790 @command{gcc}.
18791 They define  the source search path in the call to
18792 @command{gcc} issued
18793 by @command{gnatstub} to compile an argument source file.
18795 @item -gnatec@var{PATH}
18796 @cindex @option{-gnatec} (@command{gnatstub})
18797 This switch has the same meaning as in calls to @command{gcc}.
18798 It defines the additional configuration file to be passed to the call to
18799 @command{gcc} issued
18800 by @command{gnatstub} to compile an argument source file.
18802 @item -gnatyM@var{n}
18803 @cindex @option{-gnatyM} (@command{gnatstub})
18804 (@var{n} is a non-negative integer). Set the maximum line length that is
18805 allowed in a source file. The default is 79. The maximum value that can be
18806 specified is 32767. Note that in the special case of configuration
18807 pragma files, the maximum is always 32767 regardless of whether or
18808 not this switch appears.
18810 @item -gnaty@var{n}
18811 @cindex @option{-gnaty} (@command{gnatstub})
18812 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18813 the generated body sample to @var{n}.
18814 The default indentation is 3.
18816 @item -gnatyo
18817 @cindex @option{-gnatyo} (@command{gnatstub})
18818 Order local bodies alphabetically. (By default local bodies are ordered
18819 in the same way as the corresponding local specs in the argument spec file.)
18821 @item -i@var{n}
18822 @cindex @option{-i} (@command{gnatstub})
18823 Same as @option{-gnaty@var{n}}
18825 @item -k
18826 @cindex @option{-k} (@command{gnatstub})
18827 Do not remove the tree file (i.e., the snapshot of the compiler internal
18828 structures used by @command{gnatstub}) after creating the body stub.
18830 @item -l@var{n}
18831 @cindex @option{-l} (@command{gnatstub})
18832 Same as @option{-gnatyM@var{n}}
18834 @item --no-exception
18835 @cindex @option{--no-exception} (@command{gnatstub})
18836 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18837 This is not always possible for function stubs.
18839 @item --no-local-header
18840 @cindex @option{--no-local-header} (@command{gnatstub})
18841 Do not place local comment header with unit name before body stub for a
18842 unit.
18844 @item -o @var{body-name}
18845 @cindex @option{-o} (@command{gnatstub})
18846 Body file name.  This should be set if the argument file name does not
18847 follow
18848 the GNAT file naming
18849 conventions. If this switch is omitted the default name for the body will be
18850 obtained
18851 from the argument file name according to the GNAT file naming conventions.
18853 @item --dir=@var{dir-name}
18854 @cindex @option{--dir} (@command{gnatstub})
18855 The path to the directory to place the generated files into.
18856 If this switch is not set, the generated library unit body is
18857 placed in the current directory, and generated sununits -
18858 in the directory where the argument body is located.
18860 @item -W@var{e}
18861 @cindex @option{-W} (@command{gnatstub})
18862 Specify the wide character encoding method for the output body file.
18863 @var{e} is one of the following:
18865 @itemize @bullet
18867 @item h
18868 Hex encoding
18870 @item u
18871 Upper half encoding
18873 @item s
18874 Shift/JIS encoding
18876 @item e
18877 EUC encoding
18879 @item 8
18880 UTF-8 encoding
18882 @item b
18883 Brackets encoding (default value)
18884 @end itemize
18886 @item -q
18887 @cindex @option{-q} (@command{gnatstub})
18888 Quiet mode: do not generate a confirmation when a body is
18889 successfully created, and do not generate a message when a body is not
18890 required for an
18891 argument unit.
18893 @item -r
18894 @cindex @option{-r} (@command{gnatstub})
18895 Reuse the tree file (if it exists) instead of creating it.  Instead of
18896 creating the tree file for the library unit declaration, @command{gnatstub}
18897 tries to find it in the current directory and use it for creating
18898 a body. If the tree file is not found, no body is created. This option
18899 also implies @option{-k}, whether or not
18900 the latter is set explicitly.
18902 @item -t
18903 @cindex @option{-t} (@command{gnatstub})
18904 Overwrite the existing tree file.  If the current directory already
18905 contains the file which, according to the GNAT file naming rules should
18906 be considered as a tree file for the argument source file,
18907 @command{gnatstub}
18908 will refuse to create the tree file needed to create a sample body
18909 unless this option is set.
18911 @item -v
18912 @cindex @option{-v} (@command{gnatstub})
18913 Verbose mode: generate version information.
18915 @end table
18916 @end ifclear
18918 @ifclear FSFEDITION
18919 @c *********************************
18920 @node Creating Unit Tests with gnattest
18921 @chapter Creating Unit Tests with @command{gnattest}
18922 @findex gnattest
18924 @noindent
18925 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
18926 as well as a test driver infrastructure (harness). @command{gnattest} creates
18927 a skeleton for each visible subprogram in the packages under consideration when
18928 they do not exist already.
18930 In order to process source files from a project, @command{gnattest} has to
18931 semantically analyze the sources. Therefore, test skeletons can only be
18932 generated for legal Ada units. If a unit is dependent on other units,
18933 those units should be among the source files of the project or of other projects
18934 imported by this one.
18936 Generated skeletons and harnesses are based on the AUnit testing framework.
18937 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
18938 for Java or CppUnit for C++. While it is advised that gnattest users read
18939 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
18940 For correct operation of @command{gnattest}, AUnit should be installed and
18941 aunit.gpr must be on the project path. This happens automatically when Aunit
18942 is installed at its default location.
18943 @menu
18944 * Running gnattest::
18945 * Switches for gnattest::
18946 * Project Attributes for gnattest::
18947 * Simple Example::
18948 * Setting Up and Tearing Down the Testing Environment::
18949 * Regenerating Tests::
18950 * Default Test Behavior::
18951 * Testing Primitive Operations of Tagged Types::
18952 * Testing Inheritance::
18953 * Tagged Types Substitutability Testing::
18954 * Testing with Contracts::
18955 * Additional Tests::
18956 * Putting Tests under Version Control::
18957 * Support for other platforms/run-times::
18958 * Current Limitations::
18959 @end menu
18961 @node Running gnattest
18962 @section Running @command{gnattest}
18964 @noindent
18965 @command{gnattest} has a command-line interface of the form
18967 @smallexample
18968 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
18969 @c Expanding @ovar macro inline (explanation in macro def comments)
18970 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18971 @end smallexample
18973 @noindent
18974 where
18975 @table @var
18977 @item -Pprojname
18978 specifies the project defining the location of source files. When no
18979 file names are provided on the command line, all sources in the project
18980 are used as input. This switch is required.
18982 @item filename
18983 is the name of the source file containing the library unit package declaration
18984 for which a test package will be created. The file name may be given with a
18985 path.
18987 @item @samp{@var{gcc_switches}}
18988 is a list of switches for
18989 @command{gcc}. These switches will be passed on to all compiler invocations
18990 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
18991 @option{-I} switches to form the source search path,
18992 use the @option{-gnatec} switch to set the configuration file,
18993 use the @option{-gnat05} switch if sources should be compiled in
18994 Ada 2005 mode, etc.
18996 @item switches
18997 is an optional sequence of switches as described in the next section.
18999 @end table
19001 @command{gnattest} results can be found in two different places.
19003 @itemize @bullet
19004 @item automatic harness:
19005 the harness code, which is located by default in "gnattest/harness" directory
19006 that is created in the object directory of corresponding project file. All of
19007 this code is generated completely automatically and can be destroyed and
19008 regenerated at will. It is not recommended to modify this code manually, since
19009 it could easily be overridden by mistake. The entry point in the harness code is
19010 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19011 using a command such as:
19013 @smallexample
19014 gnatmake -P<harness-dir>/test_driver
19015 test_runner
19016 @end smallexample
19018 Note that you might need to specify the necessary values of scenario variables
19019 when you are not using the AUnit defaults.
19021 @item actual unit test skeletons:
19022 a test skeleton for each visible subprogram is created in a separate file, if it
19023 doesn't exist already. By default, those separate test files are located in a
19024 "gnattest/tests" directory that is created in the object directory of
19025 corresponding project file. For example, if a source file my_unit.ads in
19026 directory src contains a visible subprogram Proc, then the corresponding unit
19027 test will be found in file src/tests/my_unit-test_data-tests.adb and will be
19028 called Test_Proc_<code>. <code> is a signature encoding used to differentiate
19029 test names in case of overloading.
19031 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19032 this will cause a name conflict with the generated test package.
19033 @end itemize
19035 @node Switches for gnattest
19036 @section Switches for @command{gnattest}
19038 @table @option
19039 @c !sort!
19041 @item --harness-only
19042 @cindex @option{--harness-only} (@command{gnattest})
19043 When this option is given, @command{gnattest} creates a harness for all
19044 sources, treating them as test packages.
19046 @item --additional-tests=@var{projname}
19047 @cindex @option{--additional-tests} (@command{gnattest})
19048 Sources described in @var{projname} are considered potential additional
19049 manual tests to be added to the test suite.
19051 @item -r
19052 @cindex @option{-r} (@command{gnattest})
19053 Recursively consider all sources from all projects.
19055 @item -X@var{name=value}
19056 @cindex @option{-X} (@command{gnattest})
19057 Indicate that external variable @var{name} has the value @var{value}.
19059 @item -q
19060 @cindex @option{-q} (@command{gnattest})
19061 Suppresses noncritical output messages.
19063 @item -v
19064 @cindex @option{-v} (@command{gnattest})
19065 Verbose mode: generates version information if specified by itself on the
19066 command line.  If specified via GNATtest_Switches, produces output
19067 about the execution of the tool.
19069 @item --validate-type-extensions
19070 @cindex @option{--validate-type-extensions} (@command{gnattest})
19071 Enables substitution check: run all tests from all parents in order
19072 to check substitutability.
19074 @item --skeleton-default=@var{val}
19075 @cindex @option{--skeleton-default} (@command{gnattest})
19076 Specifies the default behavior of generated skeletons. @var{val} can be either
19077 "fail" or "pass", "fail" being the default.
19079 @item --passed-tests=@var{val}
19080 @cindex @option{--passed-tests} (@command{gnattest})
19081 Specifies whether or not passed tests should be shown. @var{val} can be either
19082 "show" or "hide", "show" being the default.
19084 @item --exit-status=@var{val}
19085 @cindex @option{--exit-status} (@command{gnattest})
19086 Specifies whether or not generated test driver should return failure exit
19087 status if at least one test fails or crashes. @var{val} can be either
19088 "on" or "off", "off" being the default.
19091 @item --tests-root=@var{dirname}
19092 @cindex @option{--tests-root} (@command{gnattest})
19093 The hierarchy of source directories, if any, is recreated in the @var{dirname}
19094 directory, with test packages placed in directories corresponding to those of the sources.
19095 If the @var{dirname} is a relative path, it is considered relative to the object
19096 directory of the project file. When all sources from all projects are taken
19097 recursively from all projects, directory hierarchies of tested sources are
19098 recreated for each project in their object directories and test packages are
19099 placed accordingly.
19101 @item --subdir=@var{dirname}
19102 @cindex @option{--subdir} (@command{gnattest})
19103 Test packages are placed in a subdirectory of the corresponding source directory,
19104 with the name @var{dirname}. Thus, each set of unit tests is located in a subdirectory of the
19105 code under test.  If the sources are in separate directories, each source directory
19106 has a test subdirectory named @var{dirname}.
19108 @item --tests-dir=@var{dirname}
19109 @cindex @option{--tests-dir} (@command{gnattest})
19110 All test packages are placed in the @var{dirname} directory.
19111 If the @var{dirname} is a relative path, it is considered relative to the object
19112 directory of the project file. When all sources from all projects are taken
19113 recursively from all projects, @var{dirname} directories are created for each
19114 project in their object directories and test packages are placed accordingly.
19116 @item --harness-dir=@var{dirname}
19117 @cindex @option{--harness-dir} (@command{gnattest})
19118 specifies the directory that will hold the harness packages and project file
19119 for the test driver. If the @var{dirname} is a relative path, it is considered
19120 relative to the object directory of the project file.
19122 @item --separates
19123 @cindex @option{--separates} (@command{gnattest})
19124 Bodies of all test routines are generated as separates. Note that this mode is
19125 kept for compatibility reasons only and it is not advised to use it due to
19126 possible problems with hash in names of test skeletons when using an
19127 inconsistent casing. Separate test skeletons can be incorporated to monolith
19128 test package with improved hash being used by using @option{--transition}
19129 switch.
19132 @item --transition
19133 @cindex @option{--transition} (@command{gnattest})
19134 This allows transition from separate test routines to monolith test packages.
19135 All matching test routines are overwritten with contents of corresponding
19136 separates. Note that if separate test routines had any manually added with
19137 clauses they will be moved to the test package body as is and have to be moved
19138 by hand.
19140 @item --omit-sloc
19141 @cindex @option{--omit-sloc} (@command{gnattest})
19142 Suppresses comment line containing file name and line number of corresponding
19143 subprograms in test skeletons.
19145 @item --test-duration
19146 @cindex @option{--test-duration} (@command{gnattest})
19147 Adds time measurements for each test in generated test driver.
19149 @end table
19151 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19152 mutually exclusive.
19154 @node Project Attributes for gnattest
19155 @section Project Attributes for @command{gnattest}
19157 @noindent
19159 Most of the command-line options can also be passed to the tool by adding
19160 special attributes to the project file. Those attributes should be put in
19161 package gnattest. Here is the list of attributes:
19163 @itemize @bullet
19165 @item Tests_Root
19166 is used to select the same output mode as with the --tests-root option.
19167 This attribute cannot be used together with Subdir or Tests_Dir.
19169 @item Subdir
19170 is used to select the same output mode as with the --subdir option.
19171 This attribute cannot be used together with Tests_Root or Tests_Dir.
19173 @item Tests_Dir
19174 is used to select the same output mode as with the --tests-dir option.
19175 This attribute cannot be used together with Subdir or Tests_Root.
19177 @item Harness_Dir
19178 is used to specify the directory in which to place harness packages and project
19179 file for the test driver, otherwise specified by --harness-dir.
19181 @item Additional_Tests
19182 is used to specify the project file, otherwise given by
19183 --additional-tests switch.
19185 @item Skeletons_Default
19186 is used to specify the default behaviour of test skeletons, otherwise
19187 specified by --skeleton-default option. The value of this attribute
19188 should be either "pass" or "fail".
19190 @end itemize
19192 Each of those attributes can be overridden from the command line if needed.
19193 Other @command{gnattest} switches can also be passed via the project
19194 file as an attribute list called GNATtest_Switches.
19196 @node Simple Example
19197 @section Simple Example
19199 @noindent
19201 Let's take a very simple example using the first @command{gnattest} example
19202 located in:
19204 @smallexample
19205 <install_prefix>/share/examples/gnattest/simple
19206 @end smallexample
19208 This project contains a simple package containing one subprogram. By running gnattest:
19210 @smallexample
19211 $ gnattest --harness-dir=driver -Psimple.gpr
19212 @end smallexample
19214 a test driver is created in directory "driver". It can be compiled and run:
19216 @smallexample
19217 $ cd obj/driver
19218 $ gnatmake -Ptest_driver
19219 $ test_runner
19220 @end smallexample
19222 One failed test with diagnosis "test not implemented" is reported.
19223 Since no special output option was specified, the test package Simple.Tests
19224 is located in:
19226 @smallexample
19227 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19228 @end smallexample
19230 For each package containing visible subprograms, a child test package is
19231 generated. It contains one test routine per tested subprogram. Each
19232 declaration of a test subprogram has a comment specifying which tested
19233 subprogram it corresponds to. Bodies of test routines are placed in test package
19234 bodies and are surrounded by special comment sections. Those comment sections
19235 should not be removed or modified in order for gnattest to be able to regenerate
19236 test packages and keep already written tests in place.
19237 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19238 a single statement: a call to procedure Assert. It has two arguments:
19239 the Boolean expression we want to check and the diagnosis message to display if
19240 the condition is false.
19242 That is where actual testing code should be written after a proper setup.
19243 An actual check can be performed by replacing the Assert call with:
19245 @smallexample @c ada
19246 Assert (Inc (1) = 2, "wrong incrementation");
19247 @end smallexample
19249 After recompiling and running the test driver, one successfully passed test
19250 is reported.
19252 @node Setting Up and Tearing Down the Testing Environment
19253 @section Setting Up and Tearing Down the Testing Environment
19255 @noindent
19257 Besides test routines themselves, each test package has a parent package
19258 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19259 overwritten by the tool. Set_Up is called before each test routine of the
19260 package and Tear_Down is called after each test routine. Those two procedures
19261 can be used to perform necessary initialization and finalization,
19262 memory allocation, etc. Test type declared in Test_Data package is parent type
19263 for the test type of test package and can have user-defined components whose
19264 values can be set by Set_Up routine and used in test routines afterwards.
19266 @node Regenerating Tests
19267 @section Regenerating Tests
19269 @noindent
19271 Bodies of test routines and test_data packages are never overridden after they
19272 have been created once. As long as the name of the subprogram, full expanded Ada
19273 names, and the order of its parameters is the same, and comment sections are
19274 intact the old test routine will fit in its place and no test skeleton will be
19275 generated for the subprogram.
19277 This can be demonstrated with the previous example. By uncommenting declaration
19278 and body of function Dec in simple.ads and simple.adb, running
19279 @command{gnattest} on the project, and then running the test driver:
19281 @smallexample
19282 gnattest --harness-dir=driver -Psimple.gpr
19283 cd obj/driver
19284 gnatmake -Ptest_driver
19285 test_runner
19286 @end smallexample
19288 the old test is not replaced with a stub, nor is it lost, but a new test
19289 skeleton is created for function Dec.
19291 The only way of regenerating tests skeletons is to remove the previously created
19292 tests together with corresponding comment sections.
19294 @node Default Test Behavior
19295 @section Default Test Behavior
19297 @noindent
19299 The generated test driver can treat unimplemented tests in two ways:
19300 either count them all as failed (this is useful to see which tests are still
19301 left to implement) or as passed (to sort out unimplemented ones from those
19302 actually failing).
19304 The test driver accepts a switch to specify this behavior:
19305 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19306 @command{gnattest}).
19308 The default behavior of the test driver is set with the same switch
19309 as passed to gnattest when generating the test driver.
19311 Passing it to the driver generated on the first example:
19313 @smallexample
19314 test_runner --skeleton-default=pass
19315 @end smallexample
19317 makes both tests pass, even the unimplemented one.
19319 @node Testing Primitive Operations of Tagged Types
19320 @section Testing Primitive Operations of Tagged Types
19322 @noindent
19324 Creation of test skeletons for primitive operations of tagged types entails
19325 a number of features. Test routines for all primitives of a given tagged type
19326 are placed in a separate child package named according to the tagged type. For
19327 example, if you have tagged type T in package P, all tests for primitives
19328 of T will be in P.T_Test_Data.T_Tests.
19330 Consider running gnattest on the second example (note: actual tests for this
19331 example already exist, so there's no need to worry if the tool reports that
19332 no new stubs were generated):
19334 @smallexample
19335 cd <install_prefix>/share/examples/gnattest/tagged_rec
19336 gnattest --harness-dir=driver -Ptagged_rec.gpr
19337 @end smallexample
19339 Taking a closer look at the test type declared in the test package
19340 Speed1.Controller_Test_Data is necessary. It is declared in:
19342 @smallexample
19343 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19344 @end smallexample
19346 Test types are direct or indirect descendants of
19347 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19348 subprograms, the user doesn't need to be concerned with them. However,
19349 when generating test packages for primitive operations, there are some things
19350 the user needs to know.
19352 Type Test_Controller has components that allow assignment of various
19353 derivations of type Controller. And if you look at the specification of
19354 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19355 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19356 Thus, test types mirror the hierarchy of tested types.
19358 The Set_Up procedure of Test_Data package corresponding to a test package
19359 of primitive operations of type T assigns to Fixture a reference to an
19360 object of that exact type T. Notice, however, that if the tagged type has
19361 discriminants, the Set_Up only has a commented template for setting
19362 up the fixture, since filling the discriminant with actual value is up
19363 to the user.
19365 The knowledge of the structure of test types allows additional testing
19366 without additional effort. Those possibilities are described below.
19368 @node Testing Inheritance
19369 @section Testing Inheritance
19371 @noindent
19373 Since the test type hierarchy mimics the hierarchy of tested types, the
19374 inheritance of tests takes place. An example of such inheritance can be
19375 seen by running the test driver generated for the second example. As previously
19376 mentioned, actual tests are already written for this example.
19378 @smallexample
19379 cd obj/driver
19380 gnatmake -Ptest_driver
19381 test_runner
19382 @end smallexample
19384 There are 6 passed tests while there are only 5 testable subprograms. The test
19385 routine for function Speed has been inherited and run against objects of the
19386 derived type.
19388 @node Tagged Types Substitutability Testing
19389 @section Tagged Types Substitutability Testing
19391 @noindent
19393 Tagged Types Substitutability Testing is a way of verifying the global type
19394 consistency by testing. Global type consistency is a principle stating that if
19395 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19396 then objects of type T may be replaced with objects of type S (that is,
19397 objects of type S may be substituted for objects of type T), without
19398 altering any of the desirable properties of the program. When the properties
19399 of the program are expressed in the form of subprogram preconditions and
19400 postconditions (let's call them pre and post), the principle is formulated as
19401 relations between the pre and post of primitive operations and the pre and post
19402 of their derived operations. The pre of a derived operation should not be
19403 stronger than the original pre, and the post of the derived operation should
19404 not be weaker than the original post. Those relations ensure that verifying if
19405 a dispatching call is safe can be done just by using the pre and post of the
19406 root operation.
19408 Verifying global type consistency by testing consists of running all the unit
19409 tests associated with the primitives of a given tagged type with objects of its
19410 derived types.
19412 In the example used in the previous section, there was clearly a violation of
19413 type consistency. The overriding primitive Adjust_Speed in package Speed2
19414 removes the functionality of the overridden primitive and thus doesn't respect
19415 the consistency principle.
19416 Gnattest has a special option to run overridden parent tests against objects
19417 of the type which have overriding primitives:
19419 @smallexample
19420 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19421 cd obj/driver
19422 gnatmake -Ptest_driver
19423 test_runner
19424 @end smallexample
19426 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19427 against objects of the derived type.
19429 Non-overridden tests are already inherited for derived test types, so the
19430 --validate-type-extensions enables the application of overriden tests to objects
19431 of derived types.
19433 @node Testing with Contracts
19434 @section Testing with Contracts
19436 @noindent
19438 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19439 as well as corresponding aspects.
19440 Test routines are generated, one per each Test_Case associated with a tested
19441 subprogram. Those test routines have special wrappers for tested functions
19442 that have composition of pre- and postcondition of the subprogram with
19443 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19444 either count for Nominal mode or do not count for Robustness mode).
19446 The third example demonstrates how this works:
19448 @smallexample
19449 cd <install_prefix>/share/examples/gnattest/contracts
19450 gnattest --harness-dir=driver -Pcontracts.gpr
19451 @end smallexample
19453 Putting actual checks within the range of the contract does not cause any
19454 error reports. For example, for the test routine which corresponds to
19455 test case 1:
19457 @smallexample @c ada
19458 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19459 @end smallexample
19461 and for the test routine corresponding to test case 2:
19463 @smallexample @c ada
19464 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19465 @end smallexample
19467 are acceptable:
19469 @smallexample
19470 cd obj/driver
19471 gnatmake -Ptest_driver
19472 test_runner
19473 @end smallexample
19475 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19476 a precondition violation for test case one. Also, by using any otherwise
19477 correct but positive pair of numbers in the second test routine, you can also
19478 get a precondition violation. Postconditions are checked and reported
19479 the same way.
19481 @node Additional Tests
19482 @section Additional Tests
19484 @noindent
19485 @command{gnattest} can add user-written tests to the main suite of the test
19486 driver. @command{gnattest} traverses the given packages and searches for test
19487 routines. All procedures with a single in out parameter of a type which is
19488 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19489 specifications are added to the suites and are then executed by the test driver.
19490 (Set_Up and Tear_Down are filtered out.)
19492 An example illustrates two ways of creating test harnesses for user-written
19493 tests. Directory additional_tests contains an AUnit-based test driver written
19494 by hand.
19496 @smallexample
19497 <install_prefix>/share/examples/gnattest/additional_tests/
19498 @end smallexample
19500 To create a test driver for already-written tests, use the --harness-only
19501 option:
19503 @smallexample
19504 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19505   --harness-only
19506 gnatmake -Pharness_only/test_driver.gpr
19507 harness_only/test_runner
19508 @end smallexample
19510 Additional tests can also be executed together with generated tests:
19512 @smallexample
19513 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19514   --harness-dir=mixing
19515 gnatmake -Pmixing/test_driver.gpr
19516 mixing/test_runner
19517 @end smallexample
19519 @node Putting Tests under Version Control
19520 @section Putting Tests under Version Control
19522 @noindent
19523 As has been stated earlier, @command{gnattest} generates two different types
19524 of code, test skeletons and harness. The harness is generated completely
19525 automatically each time, does not require manual changes and therefore should
19526 not be put under version control.
19527 It makes sense to put under version control files containing test data packages,
19528 both specs and bodies, and files containing bodies of test packages. Note that
19529 test package specs are also generated automatically each time and should not be
19530 put under version control.
19531 Option @option{--omit-sloc} may be usefull when putting test packages under VCS.
19533 @node Support for other platforms/run-times
19534 @section Support for other platforms/run-times
19536 @noindent
19537 @command{gnattest} can be used to generate the test harness for platforms
19538 and run-time libraries others than the default native target with the
19539 default full run-time. For example, when using a limited run-time library
19540 such as Zero FootPrint (ZFP), a simplified harness is generated.
19542 Two variables are used to tell the underlying AUnit framework how to generate
19543 the test harness: @code{PLATFORM}, which identifies the target, and
19544 @code{RUNTIME}, used to determine the run-time library for which the harness
19545 is generated. Corresponding prefix should also be used when calling
19546 @command{gnattest} for non-native targets. For example, the following options
19547 are used to generate the AUnit test harness for a PowerPC ELF target using
19548 the ZFP run-time library:
19550 @smallexample
19551 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19552 @end smallexample
19554 @node Current Limitations
19555 @section Current Limitations
19557 @noindent
19559 The tool currently does not support following features:
19561 @itemize @bullet
19562 @item generic tests for nested generic packages and their instantiations
19563 @item tests for protected subprograms and entries
19565 @end itemize
19566 @end ifclear
19569 @c *********************************
19570 @node Performing Dimensionality Analysis in GNAT
19571 @chapter Performing Dimensionality Analysis in GNAT
19572 @cindex Dimensionality analysis
19574 @noindent
19575 The GNAT compiler now supports dimensionality checking. The user can
19576 specify physical units for objects, and the compiler will verify that uses
19577 of these objects are compatible with their dimensions, in a fashion that is
19578 familiar to engineering practice. The dimensions of algebraic expressions
19579 (including powers with static exponents) are computed from their constituents.
19581 This feature depends on Ada 2012 aspect specifications, and is available from
19582 version 7.0.1 of GNAT onwards.
19583 The GNAT-specific aspect @code{Dimension_System}
19584 @cindex @code{Dimension_System} aspect
19585 allows you to define a system of units; the aspect @code{Dimension}
19586 @cindex @code{Dimension} aspect
19587 then allows the user to declare dimensioned quantities within a given system.
19588 (These aspects are described in the @i{Implementation Defined Aspects}
19589 chapter of the @i{GNAT Reference Manual}).
19591 The major advantage of this model is that it does not require the declaration of
19592 multiple operators for all possible combinations of types: it is only necessary
19593 to use the proper subtypes in object declarations.
19595 The simplest way to impose dimensionality checking on a computation is to make
19596 use of the package @code{System.Dim.Mks},
19597 @cindex @code{System.Dim.Mks} package (GNAT library)
19598 which is part of the GNAT library. This
19599 package defines a floating-point type @code{MKS_Type},
19600 @cindex @code{MKS_Type} type
19601 for which a sequence of
19602 dimension names are specified, together with their conventional abbreviations.
19603 The following should be read together with the full specification of the
19604 package, in file @file{s-dimmks.ads}.
19605 @cindex @file{s-dimmks.ads} file
19607 @smallexample @c ada
19608 @group
19609    @b{type} Mks_Type @b{is} @b{new} Long_Long_Float
19610      @b{with}
19611       Dimension_System => (
19612         (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
19613         (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
19614         (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
19615         (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
19616         (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
19617         (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
19618         (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
19619 @end group
19620 @end smallexample
19622 @noindent
19623 The package then defines a series of subtypes that correspond to these
19624 conventional units. For example:
19626 @smallexample @c ada
19627 @group
19628    @b{subtype} Length @b{is} Mks_Type
19629      @b{with}
19630       Dimension => (Symbol => 'm', Meter  => 1, @b{others} => 0);
19631 @end group
19632 @end smallexample
19634 @noindent
19635 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
19636 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
19637 @code{Luminous_Intensity} (the standard set of units of the SI system).
19639 The package also defines conventional names for values of each unit, for
19640 example:
19642 @smallexample @c ada
19643 @group
19644    m   : @b{constant} Length           := 1.0;
19645    kg  : @b{constant} Mass             := 1.0;
19646    s   : @b{constant} Time             := 1.0;
19647    A   : @b{constant} Electric_Current := 1.0;
19648 @end group
19649 @end smallexample
19651 @noindent
19652 as well as useful multiples of these units:
19654 @smallexample @c ada
19655 @group
19656    cm  : @b{constant} Length := 1.0E-02;
19657    g   : @b{constant} Mass   := 1.0E-03;
19658    min : @b{constant} Time   := 60.0;
19659    day : @b{constant} Time   := 60.0 * 24.0 * min;
19660   ...
19661 @end group
19662 @end smallexample
19664 @noindent
19665 Using this package, you can then define a derived unit by
19666 providing the aspect that
19667 specifies its dimensions within the MKS system, as well as the string to
19668 be used for output of a value of that unit:
19670 @smallexample @c ada
19671 @group
19672   @b{subtype} Acceleration @b{is} Mks_Type
19673     @b{with} Dimension => ("m/sec^2",
19674                        Meter => 1,
19675                        Second => -2,
19676                        @b{others} => 0);
19677 @end group
19678 @end smallexample
19680 @noindent
19681 Here is a complete example of use:
19683 @smallexample @c ada
19684 @group
19685 @b{with} System.Dim.MKS; @b{use} System.Dim.Mks;
19686 @b{with} System.Dim.Mks_IO; @b{use} System.Dim.Mks_IO;
19687 @b{with} Text_IO; @b{use} Text_IO;
19688 @b{procedure} Free_Fall @b{is}
19689   @b{subtype} Acceleration @b{is} Mks_Type
19690     @b{with} Dimension => ("m/sec^2", 1, 0, -2, @b{others} => 0);
19691   G : @b{constant} acceleration := 9.81 * m / (s ** 2);
19692   T : Time := 10.0*s;
19693   Distance : Length;
19694 @end group
19695 @group
19696 @b{begin}
19697   Put ("Gravitational constant: ");
19698   Put (G, Aft => 2, Exp => 0); Put_Line ("");
19699   Distance := 0.5 * G * T ** 2;
19700   Put ("distance travelled in 10 seconds of free fall ");
19701   Put (Distance, Aft => 2, Exp => 0);
19702   Put_Line ("");
19703 @b{end} Free_Fall;
19704 @end group
19705 @end smallexample
19707 @noindent
19708 Execution of this program yields:
19709 @smallexample
19710 @group
19711 Gravitational constant:  9.81 m/sec^2
19712 distance travelled in 10 seconds of free fall 490.50 m
19713 @end group
19714 @end smallexample
19716 @noindent
19717 However, incorrect assignments such as:
19719 @smallexample @c ada
19720 @group
19721    Distance := 5.0;
19722    Distance := 5.0 * kg:
19723 @end group
19724 @end smallexample
19726 @noindent
19727 are rejected with the following diagnoses:
19729 @smallexample
19730 @group
19731    Distance := 5.0;
19732       >>> dimensions mismatch in assignment
19733       >>> left-hand side has dimension [L]
19734       >>> right-hand side is dimensionless
19735 @end group
19737 @group
19738    Distance := 5.0 * kg:
19739       >>> dimensions mismatch in assignment
19740       >>> left-hand side has dimension [L]
19741       >>> right-hand side has dimension [M]
19742 @end group
19743 @end smallexample
19745 @noindent
19746 The dimensions of an expression are properly displayed, even if there is
19747 no explicit subtype for it. If we add to the program:
19749 @smallexample @c ada
19750 @group
19751       Put ("Final velocity: ");
19752       Put (G * T, Aft =>2, Exp =>0);
19753       Put_Line ("");
19754 @end group
19755 @end smallexample
19757 @noindent
19758 then the output includes:
19759 @smallexample
19760      Final velocity: 98.10 m.s**(-1)
19761 @end smallexample
19764 @c *********************************
19765 @node Generating Ada Bindings for C and C++ headers
19766 @chapter Generating Ada Bindings for C and C++ headers
19767 @findex binding
19769 @noindent
19770 GNAT now comes with a binding generator for C and C++ headers which is
19771 intended to do 95% of the tedious work of generating Ada specs from C
19772 or C++ header files.
19774 Note that this capability is not intended to generate 100% correct Ada specs,
19775 and will is some cases require manual adjustments, although it can often
19776 be used out of the box in practice.
19778 Some of the known limitations include:
19780 @itemize @bullet
19781 @item only very simple character constant macros are translated into Ada
19782 constants. Function macros (macros with arguments) are partially translated
19783 as comments, to be completed manually if needed.
19784 @item some extensions (e.g. vector types) are not supported
19785 @item pointers to pointers or complex structures are mapped to System.Address
19786 @item identifiers with identical name (except casing) will generate compilation
19787       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19788 @end itemize
19790 The code generated is using the Ada 2005 syntax, which makes it
19791 easier to interface with other languages than previous versions of Ada.
19793 @menu
19794 * Running the binding generator::
19795 * Generating bindings for C++ headers::
19796 * Switches::
19797 @end menu
19799 @node Running the binding generator
19800 @section Running the binding generator
19802 @noindent
19803 The binding generator is part of the @command{gcc} compiler and can be
19804 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
19805 spec files for the header files specified on the command line, and all
19806 header files needed by these files transitively. For example:
19808 @smallexample
19809 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
19810 $ gcc -c -gnat05 *.ads
19811 @end smallexample
19813 will generate, under GNU/Linux, the following files: @file{time_h.ads},
19814 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
19815 correspond to the files @file{/usr/include/time.h},
19816 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
19817 mode these Ada specs.
19819 The @code{-C} switch tells @command{gcc} to extract comments from headers,
19820 and will attempt to generate corresponding Ada comments.
19822 If you want to generate a single Ada file and not the transitive closure, you
19823 can use instead the @option{-fdump-ada-spec-slim} switch.
19825 You can optionally specify a parent unit, of which all generated units will
19826 be children, using @code{-fada-spec-parent=}@var{unit}.
19828 Note that we recommend when possible to use the @command{g++} driver to
19829 generate bindings, even for most C headers, since this will in general
19830 generate better Ada specs. For generating bindings for C++ headers, it is
19831 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
19832 is equivalent in this case. If @command{g++} cannot work on your C headers
19833 because of incompatibilities between C and C++, then you can fallback to
19834 @command{gcc} instead.
19836 For an example of better bindings generated from the C++ front-end,
19837 the name of the parameters (when available) are actually ignored by the C
19838 front-end. Consider the following C header:
19840 @smallexample
19841 extern void foo (int variable);
19842 @end smallexample
19844 with the C front-end, @code{variable} is ignored, and the above is handled as:
19846 @smallexample
19847 extern void foo (int);
19848 @end smallexample
19850 generating a generic:
19852 @smallexample
19853 procedure foo (param1 : int);
19854 @end smallexample
19856 with the C++ front-end, the name is available, and we generate:
19858 @smallexample
19859 procedure foo (variable : int);
19860 @end smallexample
19862 In some cases, the generated bindings will be more complete or more meaningful
19863 when defining some macros, which you can do via the @option{-D} switch. This
19864 is for example the case with @file{Xlib.h} under GNU/Linux:
19866 @smallexample
19867 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
19868 @end smallexample
19870 The above will generate more complete bindings than a straight call without
19871 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
19873 In other cases, it is not possible to parse a header file in a stand-alone
19874 manner, because other include files need to be included first. In this
19875 case, the solution is to create a small header file including the needed
19876 @code{#include} and possible @code{#define} directives. For example, to
19877 generate Ada bindings for @file{readline/readline.h}, you need to first
19878 include @file{stdio.h}, so you can create a file with the following two
19879 lines in e.g. @file{readline1.h}:
19881 @smallexample
19882 #include <stdio.h>
19883 #include <readline/readline.h>
19884 @end smallexample
19886 and then generate Ada bindings from this file:
19888 @smallexample
19889 $ g++ -c -fdump-ada-spec readline1.h
19890 @end smallexample
19892 @node Generating bindings for C++ headers
19893 @section Generating bindings for C++ headers
19895 @noindent
19896 Generating bindings for C++ headers is done using the same options, always
19897 with the @command{g++} compiler.
19899 In this mode, C++ classes will be mapped to Ada tagged types, constructors
19900 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
19901 multiple inheritance of abstract classes will be mapped to Ada interfaces
19902 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
19903 information on interfacing to C++).
19905 For example, given the following C++ header file:
19907 @smallexample
19908 @group
19909 @cartouche
19910 class Carnivore @{
19911 public:
19912    virtual int Number_Of_Teeth () = 0;
19915 class Domestic @{
19916 public:
19917    virtual void Set_Owner (char* Name) = 0;
19920 class Animal @{
19921 public:
19922   int Age_Count;
19923   virtual void Set_Age (int New_Age);
19926 class Dog : Animal, Carnivore, Domestic @{
19927  public:
19928   int  Tooth_Count;
19929   char *Owner;
19931   virtual int  Number_Of_Teeth ();
19932   virtual void Set_Owner (char* Name);
19934   Dog();
19936 @end cartouche
19937 @end group
19938 @end smallexample
19940 The corresponding Ada code is generated:
19942 @smallexample @c ada
19943 @group
19944 @cartouche
19945   @b{package} Class_Carnivore @b{is}
19946     @b{type} Carnivore @b{is} @b{limited} interface;
19947     @b{pragma} Import (CPP, Carnivore);
19949     @b{function} Number_Of_Teeth (this : @b{access} Carnivore) @b{return} int @b{is} @b{abstract};
19950   @b{end};
19951   @b{use} Class_Carnivore;
19953   @b{package} Class_Domestic @b{is}
19954     @b{type} Domestic @b{is} @b{limited} interface;
19955     @b{pragma} Import (CPP, Domestic);
19957     @b{procedure} Set_Owner
19958       (this : @b{access} Domestic;
19959        Name : Interfaces.C.Strings.chars_ptr) @b{is} @b{abstract};
19960   @b{end};
19961   @b{use} Class_Domestic;
19963   @b{package} Class_Animal @b{is}
19964     @b{type} Animal @b{is} @b{tagged} @b{limited} @b{record}
19965       Age_Count : @b{aliased} int;
19966     @b{end} @b{record};
19967     @b{pragma} Import (CPP, Animal);
19969     @b{procedure} Set_Age (this : @b{access} Animal; New_Age : int);
19970     @b{pragma} Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
19971   @b{end};
19972   @b{use} Class_Animal;
19974   @b{package} Class_Dog @b{is}
19975     @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
19976       Tooth_Count : @b{aliased} int;
19977       Owner : Interfaces.C.Strings.chars_ptr;
19978     @b{end} @b{record};
19979     @b{pragma} Import (CPP, Dog);
19981     @b{function} Number_Of_Teeth (this : @b{access} Dog) @b{return} int;
19982     @b{pragma} Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
19984     @b{procedure} Set_Owner
19985       (this : @b{access} Dog; Name : Interfaces.C.Strings.chars_ptr);
19986     @b{pragma} Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
19988     @b{function} New_Dog @b{return} Dog;
19989     @b{pragma} CPP_Constructor (New_Dog);
19990     @b{pragma} Import (CPP, New_Dog, "_ZN3DogC1Ev");
19991   @b{end};
19992   @b{use} Class_Dog;
19993 @end cartouche
19994 @end group
19995 @end smallexample
19997 @node Switches
19998 @section Switches
20000 @table @option
20001 @item -fdump-ada-spec
20002 @cindex @option{-fdump-ada-spec} (@command{gcc})
20003 Generate Ada spec files for the given header files transitively (including
20004 all header files that these headers depend upon).
20006 @item -fdump-ada-spec-slim
20007 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20008 Generate Ada spec files for the header files specified on the command line
20009 only.
20011 @item -fada-spec-parent=@var{unit}
20012 @cindex -fada-spec-parent (@command{gcc})
20013 Specifies that all files generated by @option{-fdump-ada-spec*} are
20014 to be child units of the specified parent unit.
20016 @item -C
20017 @cindex @option{-C} (@command{gcc})
20018 Extract comments from headers and generate Ada comments in the Ada spec files.
20019 @end table
20021 @node Other Utility Programs
20022 @chapter Other Utility Programs
20024 @noindent
20025 This chapter discusses some other utility programs available in the Ada
20026 environment.
20028 @menu
20029 * Using Other Utility Programs with GNAT::
20030 * The External Symbol Naming Scheme of GNAT::
20031 * Converting Ada Files to html with gnathtml::
20032 * Installing gnathtml::
20033 @end menu
20035 @node Using Other Utility Programs with GNAT
20036 @section Using Other Utility Programs with GNAT
20038 @noindent
20039 The object files generated by GNAT are in standard system format and in
20040 particular the debugging information uses this format. This means
20041 programs generated by GNAT can be used with existing utilities that
20042 depend on these formats.
20044 In general, any utility program that works with C will also often work with
20045 Ada programs generated by GNAT. This includes software utilities such as
20046 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20047 as Purify.
20049 @node The External Symbol Naming Scheme of GNAT
20050 @section The External Symbol Naming Scheme of GNAT
20052 @noindent
20053 In order to interpret the output from GNAT, when using tools that are
20054 originally intended for use with other languages, it is useful to
20055 understand the conventions used to generate link names from the Ada
20056 entity names.
20058 All link names are in all lowercase letters. With the exception of library
20059 procedure names, the mechanism used is simply to use the full expanded
20060 Ada name with dots replaced by double underscores. For example, suppose
20061 we have the following package spec:
20063 @smallexample @c ada
20064 @group
20065 @cartouche
20066 @b{package} QRS @b{is}
20067    MN : Integer;
20068 @b{end} QRS;
20069 @end cartouche
20070 @end group
20071 @end smallexample
20073 @noindent
20074 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20075 the corresponding link name is @code{qrs__mn}.
20076 @findex Export
20077 Of course if a @code{pragma Export} is used this may be overridden:
20079 @smallexample @c ada
20080 @group
20081 @cartouche
20082 @b{package} Exports @b{is}
20083    Var1 : Integer;
20084    @b{pragma} Export (Var1, C, External_Name => "var1_name");
20085    Var2 : Integer;
20086    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
20087 @b{end} Exports;
20088 @end cartouche
20089 @end group
20090 @end smallexample
20092 @noindent
20093 In this case, the link name for @var{Var1} is whatever link name the
20094 C compiler would assign for the C function @var{var1_name}. This typically
20095 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20096 system conventions, but other possibilities exist. The link name for
20097 @var{Var2} is @var{var2_link_name}, and this is not operating system
20098 dependent.
20100 @findex _main
20101 One exception occurs for library level procedures. A potential ambiguity
20102 arises between the required name @code{_main} for the C main program,
20103 and the name we would otherwise assign to an Ada library level procedure
20104 called @code{Main} (which might well not be the main program).
20106 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20107 names. So if we have a library level procedure such as
20109 @smallexample @c ada
20110 @group
20111 @cartouche
20112 @b{procedure} Hello (S : String);
20113 @end cartouche
20114 @end group
20115 @end smallexample
20117 @noindent
20118 the external name of this procedure will be @var{_ada_hello}.
20121 @node Converting Ada Files to html with gnathtml
20122 @section Converting Ada Files to HTML with @code{gnathtml}
20124 @noindent
20125 This @code{Perl} script allows Ada source files to be browsed using
20126 standard Web browsers. For installation procedure, see the section
20127 @xref{Installing gnathtml}.
20129 Ada reserved keywords are highlighted in a bold font and Ada comments in
20130 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20131 switch to suppress the generation of cross-referencing information, user
20132 defined variables and types will appear in a different color; you will
20133 be able to click on any identifier and go to its declaration.
20135 The command line is as follow:
20136 @smallexample
20137 @c $ perl gnathtml.pl @ovar{switches} @var{ada-files}
20138 @c Expanding @ovar macro inline (explanation in macro def comments)
20139 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{ada-files}
20140 @end smallexample
20142 @noindent
20143 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20144 an html file for every ada file, and a global file called @file{index.htm}.
20145 This file is an index of every identifier defined in the files.
20147 The available switches are the following ones:
20149 @table @option
20150 @item -83
20151 @cindex @option{-83} (@code{gnathtml})
20152 Only the Ada 83 subset of keywords will be highlighted.
20154 @item -cc @var{color}
20155 @cindex @option{-cc} (@code{gnathtml})
20156 This option allows you to change the color used for comments. The default
20157 value is green. The color argument can be any name accepted by html.
20159 @item -d
20160 @cindex @option{-d} (@code{gnathtml})
20161 If the Ada files depend on some other files (for instance through
20162 @code{with} clauses, the latter files will also be converted to html.
20163 Only the files in the user project will be converted to html, not the files
20164 in the run-time library itself.
20166 @item -D
20167 @cindex @option{-D} (@code{gnathtml})
20168 This command is the same as @option{-d} above, but @command{gnathtml} will
20169 also look for files in the run-time library, and generate html files for them.
20171 @item -ext @var{extension}
20172 @cindex @option{-ext} (@code{gnathtml})
20173 This option allows you to change the extension of the generated HTML files.
20174 If you do not specify an extension, it will default to @file{htm}.
20176 @item -f
20177 @cindex @option{-f} (@code{gnathtml})
20178 By default, gnathtml will generate html links only for global entities
20179 ('with'ed units, global variables and types,@dots{}).  If you specify
20180 @option{-f} on the command line, then links will be generated for local
20181 entities too.
20183 @item -l @var{number}
20184 @cindex @option{-l} (@code{gnathtml})
20185 If this switch is provided and @var{number} is not 0, then
20186 @code{gnathtml} will number the html files every @var{number} line.
20188 @item -I @var{dir}
20189 @cindex @option{-I} (@code{gnathtml})
20190 Specify a directory to search for library files (@file{.ALI} files) and
20191 source files. You can provide several -I switches on the command line,
20192 and the directories will be parsed in the order of the command line.
20194 @item -o @var{dir}
20195 @cindex @option{-o} (@code{gnathtml})
20196 Specify the output directory for html files. By default, gnathtml will
20197 saved the generated html files in a subdirectory named @file{html/}.
20199 @item -p @var{file}
20200 @cindex @option{-p} (@code{gnathtml})
20201 If you are using Emacs and the most recent Emacs Ada mode, which provides
20202 a full Integrated Development Environment for compiling, checking,
20203 running and debugging applications, you may use @file{.gpr} files
20204 to give the directories where Emacs can find sources and object files.
20206 Using this switch, you can tell gnathtml to use these files.
20207 This allows you to get an html version of your application, even if it
20208 is spread over multiple directories.
20210 @item -sc @var{color}
20211 @cindex @option{-sc} (@code{gnathtml})
20212 This switch allows you to change the color used for symbol
20213 definitions.
20214 The default value is red. The color argument can be any name accepted by html.
20216 @item -t @var{file}
20217 @cindex @option{-t} (@code{gnathtml})
20218 This switch provides the name of a file. This file contains a list of
20219 file names to be converted, and the effect is exactly as though they had
20220 appeared explicitly on the command line. This
20221 is the recommended way to work around the command line length limit on some
20222 systems.
20224 @end table
20226 @node Installing gnathtml
20227 @section Installing @code{gnathtml}
20229 @noindent
20230 @code{Perl} needs to be installed on your machine to run this script.
20231 @code{Perl} is freely available for almost every architecture and
20232 Operating System via the Internet.
20234 On Unix systems, you  may want to modify  the  first line of  the script
20235 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
20236 is. The syntax of this line is:
20237 @smallexample
20238 #!full_path_name_to_perl
20239 @end smallexample
20241 @noindent
20242 Alternatively, you may run the script using the following command line:
20244 @smallexample
20245 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20246 @c Expanding @ovar macro inline (explanation in macro def comments)
20247 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20248 @end smallexample
20251 @c ******************************
20252 @node Code Coverage and Profiling
20253 @chapter Code Coverage and Profiling
20254 @cindex Code Coverage
20255 @cindex Profiling
20257 @noindent
20258 This chapter describes how to use @code{gcov} - coverage testing tool - and
20259 @code{gprof} - profiler tool - on your Ada programs.
20261 @menu
20262 * Code Coverage of Ada Programs with gcov::
20263 * Profiling an Ada Program with gprof::
20264 @end menu
20266 @node Code Coverage of Ada Programs with gcov
20267 @section Code Coverage of Ada Programs with gcov
20268 @cindex gcov
20269 @cindex -fprofile-arcs
20270 @cindex -ftest-coverage
20271 @cindex -coverage
20272 @cindex Code Coverage
20274 @noindent
20275 @code{gcov} is a test coverage program: it analyzes the execution of a given
20276 program on selected tests, to help you determine the portions of the program
20277 that are still untested.
20279 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20280 User's Guide. You can refer to this documentation for a more complete
20281 description.
20283 This chapter provides a quick startup guide, and
20284 details some Gnat-specific features.
20286 @menu
20287 * Quick startup guide::
20288 * Gnat specifics::
20289 @end menu
20291 @node Quick startup guide
20292 @subsection Quick startup guide
20294 In order to perform coverage analysis of a program using @code{gcov}, 3
20295 steps are needed:
20297 @itemize @bullet
20298 @item
20299 Code instrumentation during the compilation process
20300 @item
20301 Execution of the instrumented program
20302 @item
20303 Execution of the @code{gcov} tool to generate the result.
20304 @end itemize
20306 The code instrumentation needed by gcov is created at the object level:
20307 The source code is not modified in any way, because the instrumentation code is
20308 inserted by gcc during the compilation process. To compile your code with code
20309 coverage activated, you need to recompile your whole project using the
20310 switches
20311 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20312 @code{-fprofile-arcs}.
20314 @smallexample
20315 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20316    -largs -fprofile-arcs
20317 @end smallexample
20319 This compilation process will create @file{.gcno} files together with
20320 the usual object files.
20322 Once the program is compiled with coverage instrumentation, you can
20323 run it as many times as needed - on portions of a test suite for
20324 example. The first execution will produce @file{.gcda} files at the
20325 same location as the @file{.gcno} files.  The following executions
20326 will update those files, so that a cumulative result of the covered
20327 portions of the program is generated.
20329 Finally, you need to call the @code{gcov} tool. The different options of
20330 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20332 This will create annotated source files with a @file{.gcov} extension:
20333 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20335 @node Gnat specifics
20336 @subsection Gnat specifics
20338 Because Ada semantics, portions of the source code may be shared among
20339 several object files. This is the case for example when generics are
20340 involved, when inlining is active  or when declarations generate  initialisation
20341 calls. In order to take
20342 into account this shared code, you need to call @code{gcov} on all
20343 source files of the tested program at once.
20345 The list of source files might exceed the system's maximum command line
20346 length. In order to bypass this limitation, a new mechanism has been
20347 implemented in @code{gcov}: you can now list all your project's files into a
20348 text file, and provide this file to gcov as a parameter,  preceded by a @@
20349 (e.g. @samp{gcov @@mysrclist.txt}).
20351 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20352 not supported as there can be unresolved symbols during the final link.
20354 @node Profiling an Ada Program with gprof
20355 @section Profiling an Ada Program with gprof
20356 @cindex gprof
20357 @cindex -pg
20358 @cindex Profiling
20360 @noindent
20361 This section is not meant to be an exhaustive documentation of @code{gprof}.
20362 Full documentation for it can be found in the GNU Profiler User's Guide
20363 documentation that is part of this GNAT distribution.
20365 Profiling a program helps determine the parts of a program that are executed
20366 most often, and are therefore the most time-consuming.
20368 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20369 better handle Ada programs and multitasking.
20370 It is currently supported on the following platforms
20371 @itemize @bullet
20372 @item
20373 linux x86/x86_64
20374 @item
20375 solaris sparc/sparc64/x86
20376 @item
20377 windows x86
20378 @end itemize
20380 @noindent
20381 In order to profile a program using @code{gprof}, 3 steps are needed:
20383 @itemize @bullet
20384 @item
20385 Code instrumentation, requiring a full recompilation of the project with the
20386 proper switches.
20387 @item
20388 Execution of the program under the analysis conditions, i.e. with the desired
20389 input.
20390 @item
20391 Analysis of the results using the @code{gprof} tool.
20392 @end itemize
20394 @noindent
20395 The following sections detail the different steps, and indicate how
20396 to interpret the results:
20397 @menu
20398 * Compilation for profiling::
20399 * Program execution::
20400 * Running gprof::
20401 * Interpretation of profiling results::
20402 @end menu
20404 @node Compilation for profiling
20405 @subsection Compilation for profiling
20406 @cindex -pg
20407 @cindex Profiling
20409 In order to profile a program the first step is to tell the compiler
20410 to generate the necessary profiling information. The compiler switch to be used
20411 is @code{-pg}, which must be added to other compilation switches. This
20412 switch needs to be specified both during compilation and link stages, and can
20413 be specified once when using gnatmake:
20415 @smallexample
20416 gnatmake -f -pg -P my_project
20417 @end smallexample
20419 @noindent
20420 Note that only the objects that were compiled with the @samp{-pg} switch will
20421 be profiled; if you need to profile your whole project, use the @samp{-f}
20422 gnatmake switch to force full recompilation.
20424 @node Program execution
20425 @subsection Program execution
20427 @noindent
20428 Once the program has been compiled for profiling, you can run it as usual.
20430 The only constraint imposed by profiling is that the program must terminate
20431 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20432 properly analyzed.
20434 Once the program completes execution, a data file called @file{gmon.out} is
20435 generated in the directory where the program was launched from. If this file
20436 already exists, it will be overwritten.
20438 @node Running gprof
20439 @subsection Running gprof
20441 @noindent
20442 The @code{gprof} tool is called as follow:
20444 @smallexample
20445 gprof my_prog gmon.out
20446 @end smallexample
20448 @noindent
20449 or simpler:
20451 @smallexample
20452 gprof my_prog
20453 @end smallexample
20455 @noindent
20456 The complete form of the gprof command line is the following:
20458 @smallexample
20459 gprof [switches] [executable [data-file]]
20460 @end smallexample
20462 @noindent
20463 @code{gprof} supports numerous switch. The order of these
20464 switch does not matter. The full list of options can be found in
20465 the GNU Profiler User's Guide documentation that comes with this documentation.
20467 The following is the subset of those switches that is most relevant:
20469 @table @option
20471 @item --demangle[=@var{style}]
20472 @itemx --no-demangle
20473 @cindex @option{--demangle} (@code{gprof})
20474 These options control whether symbol names should be demangled when
20475 printing output.  The default is to demangle C++ symbols.  The
20476 @code{--no-demangle} option may be used to turn off demangling. Different
20477 compilers have different mangling styles.  The optional demangling style
20478 argument can be used to choose an appropriate demangling style for your
20479 compiler, in particular Ada symbols generated by GNAT can be demangled using
20480 @code{--demangle=gnat}.
20482 @item -e @var{function_name}
20483 @cindex @option{-e} (@code{gprof})
20484 The @samp{-e @var{function}} option tells @code{gprof} not to print
20485 information about the function @var{function_name} (and its
20486 children@dots{}) in the call graph.  The function will still be listed
20487 as a child of any functions that call it, but its index number will be
20488 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
20489 given; only one @var{function_name} may be indicated with each @samp{-e}
20490 option.
20492 @item -E @var{function_name}
20493 @cindex @option{-E} (@code{gprof})
20494 The @code{-E @var{function}} option works like the @code{-e} option, but
20495 execution time spent in the function (and children who were not called from
20496 anywhere else), will not be used to compute the percentages-of-time for
20497 the call graph.  More than one @samp{-E} option may be given; only one
20498 @var{function_name} may be indicated with each @samp{-E} option.
20500 @item -f @var{function_name}
20501 @cindex @option{-f} (@code{gprof})
20502 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20503 call graph to the function @var{function_name} and its children (and
20504 their children@dots{}).  More than one @samp{-f} option may be given;
20505 only one @var{function_name} may be indicated with each @samp{-f}
20506 option.
20508 @item -F @var{function_name}
20509 @cindex @option{-F} (@code{gprof})
20510 The @samp{-F @var{function}} option works like the @code{-f} option, but
20511 only time spent in the function and its children (and their
20512 children@dots{}) will be used to determine total-time and
20513 percentages-of-time for the call graph.  More than one @samp{-F} option
20514 may be given; only one @var{function_name} may be indicated with each
20515 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
20517 @end table
20519 @node Interpretation of profiling results
20520 @subsection Interpretation of profiling results
20522 @noindent
20524 The results of the profiling analysis are represented by two arrays: the
20525 'flat profile' and the 'call graph'. Full documentation of those outputs
20526 can be found in the GNU Profiler User's Guide.
20528 The flat profile shows the time spent in each function of the program, and how
20529 many time it has been called. This allows you to locate easily the most
20530 time-consuming functions.
20532 The call graph shows, for each subprogram, the subprograms that call it,
20533 and the subprograms that it calls. It also provides an estimate of the time
20534 spent in each of those callers/called subprograms.
20536 @c ******************************
20537 @node Running and Debugging Ada Programs
20538 @chapter Running and Debugging Ada Programs
20539 @cindex Debugging
20541 @noindent
20542 This chapter discusses how to debug Ada programs.
20544 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20546 @enumerate
20547 @item
20548 The illegality may be a violation of the static semantics of Ada. In
20549 that case GNAT diagnoses the constructs in the program that are illegal.
20550 It is then a straightforward matter for the user to modify those parts of
20551 the program.
20553 @item
20554 The illegality may be a violation of the dynamic semantics of Ada. In
20555 that case the program compiles and executes, but may generate incorrect
20556 results, or may terminate abnormally with some exception.
20558 @item
20559 When presented with a program that contains convoluted errors, GNAT
20560 itself may terminate abnormally without providing full diagnostics on
20561 the incorrect user program.
20562 @end enumerate
20564 @menu
20565 * The GNAT Debugger GDB::
20566 * Running GDB::
20567 * Introduction to GDB Commands::
20568 * Using Ada Expressions::
20569 * Calling User-Defined Subprograms::
20570 * Using the Next Command in a Function::
20571 * Ada Exceptions::
20572 * Ada Tasks::
20573 * Debugging Generic Units::
20574 * Remote Debugging with gdbserver::
20575 * GNAT Abnormal Termination or Failure to Terminate::
20576 * Naming Conventions for GNAT Source Files::
20577 * Getting Internal Debugging Information::
20578 * Stack Traceback::
20579 @end menu
20581 @cindex Debugger
20582 @findex gdb
20584 @node The GNAT Debugger GDB
20585 @section The GNAT Debugger GDB
20587 @noindent
20588 @code{GDB} is a general purpose, platform-independent debugger that
20589 can be used to debug mixed-language programs compiled with @command{gcc},
20590 and in particular is capable of debugging Ada programs compiled with
20591 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20592 complex Ada data structures.
20594 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20595 for full details on the usage of @code{GDB}, including a section on
20596 its usage on programs. This manual should be consulted for full
20597 details. The section that follows is a brief introduction to the
20598 philosophy and use of @code{GDB}.
20600 When GNAT programs are compiled, the compiler optionally writes debugging
20601 information into the generated object file, including information on
20602 line numbers, and on declared types and variables. This information is
20603 separate from the generated code. It makes the object files considerably
20604 larger, but it does not add to the size of the actual executable that
20605 will be loaded into memory, and has no impact on run-time performance. The
20606 generation of debug information is triggered by the use of the
20607 -g switch in the @command{gcc} or @command{gnatmake} command
20608 used to carry out the compilations. It is important to emphasize that
20609 the use of these options does not change the generated code.
20611 The debugging information is written in standard system formats that
20612 are used by many tools, including debuggers and profilers. The format
20613 of the information is typically designed to describe C types and
20614 semantics, but GNAT implements a translation scheme which allows full
20615 details about Ada types and variables to be encoded into these
20616 standard C formats. Details of this encoding scheme may be found in
20617 the file exp_dbug.ads in the GNAT source distribution. However, the
20618 details of this encoding are, in general, of no interest to a user,
20619 since @code{GDB} automatically performs the necessary decoding.
20621 When a program is bound and linked, the debugging information is
20622 collected from the object files, and stored in the executable image of
20623 the program. Again, this process significantly increases the size of
20624 the generated executable file, but it does not increase the size of
20625 the executable program itself. Furthermore, if this program is run in
20626 the normal manner, it runs exactly as if the debug information were
20627 not present, and takes no more actual memory.
20629 However, if the program is run under control of @code{GDB}, the
20630 debugger is activated.  The image of the program is loaded, at which
20631 point it is ready to run.  If a run command is given, then the program
20632 will run exactly as it would have if @code{GDB} were not present. This
20633 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
20634 entirely non-intrusive until a breakpoint is encountered.  If no
20635 breakpoint is ever hit, the program will run exactly as it would if no
20636 debugger were present. When a breakpoint is hit, @code{GDB} accesses
20637 the debugging information and can respond to user commands to inspect
20638 variables, and more generally to report on the state of execution.
20640 @c **************
20641 @node Running GDB
20642 @section Running GDB
20644 @noindent
20645 This section describes how to initiate the debugger.
20646 @c The above sentence is really just filler, but it was otherwise
20647 @c clumsy to get the first paragraph nonindented given the conditional
20648 @c nature of the description
20650 The debugger can be launched from a @code{GPS} menu or
20651 directly from the command line. The description below covers the latter use.
20652 All the commands shown can be used in the @code{GPS} debug console window,
20653 but there are usually more GUI-based ways to achieve the same effect.
20655 The command to run @code{GDB} is
20657 @smallexample
20658 $ gdb program
20659 @end smallexample
20661 @noindent
20662 where @code{program} is the name of the executable file. This
20663 activates the debugger and results in a prompt for debugger commands.
20664 The simplest command is simply @code{run}, which causes the program to run
20665 exactly as if the debugger were not present. The following section
20666 describes some of the additional commands that can be given to @code{GDB}.
20668 @c *******************************
20669 @node Introduction to GDB Commands
20670 @section Introduction to GDB Commands
20672 @noindent
20673 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
20674 Debugging with GDB, gdb, Debugging with GDB},
20675 for extensive documentation on the use
20676 of these commands, together with examples of their use. Furthermore,
20677 the command @command{help} invoked from within GDB activates a simple help
20678 facility which summarizes the available commands and their options.
20679 In this section we summarize a few of the most commonly
20680 used commands to give an idea of what @code{GDB} is about. You should create
20681 a simple program with debugging information and experiment with the use of
20682 these @code{GDB} commands on the program as you read through the
20683 following section.
20685 @table @code
20686 @item set args @var{arguments}
20687 The @var{arguments} list above is a list of arguments to be passed to
20688 the program on a subsequent run command, just as though the arguments
20689 had been entered on a normal invocation of the program. The @code{set args}
20690 command is not needed if the program does not require arguments.
20692 @item run
20693 The @code{run} command causes execution of the program to start from
20694 the beginning. If the program is already running, that is to say if
20695 you are currently positioned at a breakpoint, then a prompt will ask
20696 for confirmation that you want to abandon the current execution and
20697 restart.
20699 @item breakpoint @var{location}
20700 The breakpoint command sets a breakpoint, that is to say a point at which
20701 execution will halt and @code{GDB} will await further
20702 commands. @var{location} is
20703 either a line number within a file, given in the format @code{file:linenumber},
20704 or it is the name of a subprogram. If you request that a breakpoint be set on
20705 a subprogram that is overloaded, a prompt will ask you to specify on which of
20706 those subprograms you want to breakpoint. You can also
20707 specify that all of them should be breakpointed. If the program is run
20708 and execution encounters the breakpoint, then the program
20709 stops and @code{GDB} signals that the breakpoint was encountered by
20710 printing the line of code before which the program is halted.
20712 @item catch exception @var{name}
20713 This command causes the program execution to stop whenever exception
20714 @var{name} is raised.  If @var{name} is omitted, then the execution is
20715 suspended when any exception is raised.
20717 @item print @var{expression}
20718 This will print the value of the given expression. Most simple
20719 Ada expression formats are properly handled by @code{GDB}, so the expression
20720 can contain function calls, variables, operators, and attribute references.
20722 @item continue
20723 Continues execution following a breakpoint, until the next breakpoint or the
20724 termination of the program.
20726 @item step
20727 Executes a single line after a breakpoint. If the next statement
20728 is a subprogram call, execution continues into (the first statement of)
20729 the called subprogram.
20731 @item next
20732 Executes a single line. If this line is a subprogram call, executes and
20733 returns from the call.
20735 @item list
20736 Lists a few lines around the current source location. In practice, it
20737 is usually more convenient to have a separate edit window open with the
20738 relevant source file displayed. Successive applications of this command
20739 print subsequent lines. The command can be given an argument which is a
20740 line number, in which case it displays a few lines around the specified one.
20742 @item backtrace
20743 Displays a backtrace of the call chain. This command is typically
20744 used after a breakpoint has occurred, to examine the sequence of calls that
20745 leads to the current breakpoint. The display includes one line for each
20746 activation record (frame) corresponding to an active subprogram.
20748 @item up
20749 At a breakpoint, @code{GDB} can display the values of variables local
20750 to the current frame. The command @code{up} can be used to
20751 examine the contents of other active frames, by moving the focus up
20752 the stack, that is to say from callee to caller, one frame at a time.
20754 @item down
20755 Moves the focus of @code{GDB} down from the frame currently being
20756 examined to the frame of its callee (the reverse of the previous command),
20758 @item frame @var{n}
20759 Inspect the frame with the given number. The value 0 denotes the frame
20760 of the current breakpoint, that is to say the top of the call stack.
20762 @item kill
20763 Kills the child process in which the program is running under GDB.
20764 This may be useful for several purposes:
20765 @itemize @bullet
20766 @item
20767 It allows you to recompile and relink your program, since on many systems
20768 you cannot regenerate an executable file while it is running in a process.
20769 @item
20770 You can run your program outside the debugger, on systems that do not
20771 permit executing a program outside GDB while breakpoints are set
20772 within GDB.
20773 @item
20774 It allows you to debug a core dump rather than a running process.
20775 @end itemize
20776 @end table
20778 @noindent
20779 The above list is a very short introduction to the commands that
20780 @code{GDB} provides. Important additional capabilities, including conditional
20781 breakpoints, the ability to execute command sequences on a breakpoint,
20782 the ability to debug at the machine instruction level and many other
20783 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20784 Debugging with GDB}.  Note that most commands can be abbreviated
20785 (for example, c for continue, bt for backtrace).
20787 @node Using Ada Expressions
20788 @section Using Ada Expressions
20789 @cindex Ada expressions
20791 @noindent
20792 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20793 extensions. The philosophy behind the design of this subset is
20795 @itemize @bullet
20796 @item
20797 That @code{GDB} should provide basic literals and access to operations for
20798 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20799 leaving more sophisticated computations to subprograms written into the
20800 program (which therefore may be called from @code{GDB}).
20802 @item
20803 That type safety and strict adherence to Ada language restrictions
20804 are not particularly important to the @code{GDB} user.
20806 @item
20807 That brevity is important to the @code{GDB} user.
20808 @end itemize
20810 @noindent
20811 Thus, for brevity, the debugger acts as if there were
20812 implicit @code{with} and @code{use} clauses in effect for all user-written
20813 packages, thus making it unnecessary to fully qualify most names with
20814 their packages, regardless of context. Where this causes ambiguity,
20815 @code{GDB} asks the user's intent.
20817 For details on the supported Ada syntax, see @ref{Top,, Debugging with
20818 GDB, gdb, Debugging with GDB}.
20820 @node Calling User-Defined Subprograms
20821 @section Calling User-Defined Subprograms
20823 @noindent
20824 An important capability of @code{GDB} is the ability to call user-defined
20825 subprograms while debugging. This is achieved simply by entering
20826 a subprogram call statement in the form:
20828 @smallexample
20829 call subprogram-name (parameters)
20830 @end smallexample
20832 @noindent
20833 The keyword @code{call} can be omitted in the normal case where the
20834 @code{subprogram-name} does not coincide with any of the predefined
20835 @code{GDB} commands.
20837 The effect is to invoke the given subprogram, passing it the
20838 list of parameters that is supplied. The parameters can be expressions and
20839 can include variables from the program being debugged. The
20840 subprogram must be defined
20841 at the library level within your program, and @code{GDB} will call the
20842 subprogram within the environment of your program execution (which
20843 means that the subprogram is free to access or even modify variables
20844 within your program).
20846 The most important use of this facility is in allowing the inclusion of
20847 debugging routines that are tailored to particular data structures
20848 in your program. Such debugging routines can be written to provide a suitably
20849 high-level description of an abstract type, rather than a low-level dump
20850 of its physical layout. After all, the standard
20851 @code{GDB print} command only knows the physical layout of your
20852 types, not their abstract meaning. Debugging routines can provide information
20853 at the desired semantic level and are thus enormously useful.
20855 For example, when debugging GNAT itself, it is crucial to have access to
20856 the contents of the tree nodes used to represent the program internally.
20857 But tree nodes are represented simply by an integer value (which in turn
20858 is an index into a table of nodes).
20859 Using the @code{print} command on a tree node would simply print this integer
20860 value, which is not very useful. But the PN routine (defined in file
20861 treepr.adb in the GNAT sources) takes a tree node as input, and displays
20862 a useful high level representation of the tree node, which includes the
20863 syntactic category of the node, its position in the source, the integers
20864 that denote descendant nodes and parent node, as well as varied
20865 semantic information. To study this example in more detail, you might want to
20866 look at the body of the PN procedure in the stated file.
20868 @node Using the Next Command in a Function
20869 @section Using the Next Command in a Function
20871 @noindent
20872 When you use the @code{next} command in a function, the current source
20873 location will advance to the next statement as usual. A special case
20874 arises in the case of a @code{return} statement.
20876 Part of the code for a return statement is the ``epilog'' of the function.
20877 This is the code that returns to the caller. There is only one copy of
20878 this epilog code, and it is typically associated with the last return
20879 statement in the function if there is more than one return. In some
20880 implementations, this epilog is associated with the first statement
20881 of the function.
20883 The result is that if you use the @code{next} command from a return
20884 statement that is not the last return statement of the function you
20885 may see a strange apparent jump to the last return statement or to
20886 the start of the function. You should simply ignore this odd jump.
20887 The value returned is always that from the first return statement
20888 that was stepped through.
20890 @node Ada Exceptions
20891 @section Stopping when Ada Exceptions are Raised
20892 @cindex Exceptions
20894 @noindent
20895 You can set catchpoints that stop the program execution when your program
20896 raises selected exceptions.
20898 @table @code
20899 @item catch exception
20900 Set a catchpoint that stops execution whenever (any task in the) program
20901 raises any exception.
20903 @item catch exception @var{name}
20904 Set a catchpoint that stops execution whenever (any task in the) program
20905 raises the exception @var{name}.
20907 @item catch exception unhandled
20908 Set a catchpoint that stops executing whenever (any task in the) program
20909 raises an exception for which there is no handler.
20911 @item info exceptions
20912 @itemx info exceptions @var{regexp}
20913 The @code{info exceptions} command permits the user to examine all defined
20914 exceptions within Ada programs. With a regular expression, @var{regexp}, as
20915 argument, prints out only those exceptions whose name matches @var{regexp}.
20916 @end table
20918 @node Ada Tasks
20919 @section Ada Tasks
20920 @cindex Tasks
20922 @noindent
20923 @code{GDB} allows the following task-related commands:
20925 @table @code
20926 @item info tasks
20927 This command shows a list of current Ada tasks, as in the following example:
20929 @smallexample
20930 @iftex
20931 @leftskip=0cm
20932 @end iftex
20933 (gdb) info tasks
20934   ID       TID P-ID   Thread Pri State                 Name
20935    1   8088000   0   807e000  15 Child Activation Wait main_task
20936    2   80a4000   1   80ae000  15 Accept/Select Wait    b
20937    3   809a800   1   80a4800  15 Child Activation Wait a
20938 *  4   80ae800   3   80b8000  15 Running               c
20939 @end smallexample
20941 @noindent
20942 In this listing, the asterisk before the first task indicates it to be the
20943 currently running task. The first column lists the task ID that is used
20944 to refer to tasks in the following commands.
20946 @item break @var{linespec} task @var{taskid}
20947 @itemx break @var{linespec} task @var{taskid} if @dots{}
20948 @cindex Breakpoints and tasks
20949 These commands are like the @code{break @dots{} thread @dots{}}.
20950 @var{linespec} specifies source lines.
20952 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
20953 to specify that you only want @code{GDB} to stop the program when a
20954 particular Ada task reaches this breakpoint. @var{taskid} is one of the
20955 numeric task identifiers assigned by @code{GDB}, shown in the first
20956 column of the @samp{info tasks} display.
20958 If you do not specify @samp{task @var{taskid}} when you set a
20959 breakpoint, the breakpoint applies to @emph{all} tasks of your
20960 program.
20962 You can use the @code{task} qualifier on conditional breakpoints as
20963 well; in this case, place @samp{task @var{taskid}} before the
20964 breakpoint condition (before the @code{if}).
20966 @item task @var{taskno}
20967 @cindex Task switching
20969 This command allows switching to the task referred by @var{taskno}. In
20970 particular, this allows browsing of the backtrace of the specified
20971 task. It is advisable to switch back to the original task before
20972 continuing execution otherwise the scheduling of the program may be
20973 perturbed.
20974 @end table
20976 @noindent
20977 For more detailed information on the tasking support,
20978 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
20980 @node Debugging Generic Units
20981 @section Debugging Generic Units
20982 @cindex Debugging Generic Units
20983 @cindex Generics
20985 @noindent
20986 GNAT always uses code expansion for generic instantiation. This means that
20987 each time an instantiation occurs, a complete copy of the original code is
20988 made, with appropriate substitutions of formals by actuals.
20990 It is not possible to refer to the original generic entities in
20991 @code{GDB}, but it is always possible to debug a particular instance of
20992 a generic, by using the appropriate expanded names. For example, if we have
20994 @smallexample @c ada
20995 @group
20996 @cartouche
20997 @b{procedure} g @b{is}
20999    @b{generic} @b{package} k @b{is}
21000       @b{procedure} kp (v1 : @b{in} @b{out} integer);
21001    @b{end} k;
21003    @b{package} @b{body} k @b{is}
21004       @b{procedure} kp (v1 : @b{in} @b{out} integer) @b{is}
21005       @b{begin}
21006          v1 := v1 + 1;
21007       @b{end} kp;
21008    @b{end} k;
21010    @b{package} k1 @b{is} @b{new} k;
21011    @b{package} k2 @b{is} @b{new} k;
21013    var : integer := 1;
21015 @b{begin}
21016    k1.kp (var);
21017    k2.kp (var);
21018    k1.kp (var);
21019    k2.kp (var);
21020 @b{end};
21021 @end cartouche
21022 @end group
21023 @end smallexample
21025 @noindent
21026 Then to break on a call to procedure kp in the k2 instance, simply
21027 use the command:
21029 @smallexample
21030 (gdb) break g.k2.kp
21031 @end smallexample
21033 @noindent
21034 When the breakpoint occurs, you can step through the code of the
21035 instance in the normal manner and examine the values of local variables, as for
21036 other units.
21038 @node Remote Debugging with gdbserver
21039 @section Remote Debugging with gdbserver
21040 @cindex Remote Debugging with gdbserver
21042 @noindent
21043 On platforms where gdbserver is supported, it is possible to use this tool
21044 to debug your application remotely.  This can be useful in situations
21045 where the program needs to be run on a target host that is different
21046 from the host used for development, particularly when the target has
21047 a limited amount of resources (either CPU and/or memory).
21049 To do so, start your program using gdbserver on the target machine.
21050 gdbserver then automatically suspends the execution of your program
21051 at its entry point, waiting for a debugger to connect to it.  The
21052 following commands starts an application and tells gdbserver to
21053 wait for a connection with the debugger on localhost port 4444.
21055 @smallexample
21056 $ gdbserver localhost:4444 program
21057 Process program created; pid = 5685
21058 Listening on port 4444
21059 @end smallexample
21061 Once gdbserver has started listening, we can tell the debugger to establish
21062 a connection with this gdbserver, and then start the same debugging session
21063 as if the program was being debugged on the same host, directly under
21064 the control of GDB.
21066 @smallexample
21067 $ gdb program
21068 (gdb) target remote targethost:4444
21069 Remote debugging using targethost:4444
21070 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21071 (gdb) b foo.adb:3
21072 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21073 (gdb) continue
21074 Continuing.
21076 Breakpoint 1, foo () at foo.adb:4
21077 4       end foo;
21078 @end smallexample
21080 It is also possible to use gdbserver to attach to an already running
21081 program, in which case the execution of that program is simply suspended
21082 until the connection between the debugger and gdbserver is established.
21084 For more information on how to use gdbserver, @ref{Top, Server, Using
21085 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
21086 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21088 @node GNAT Abnormal Termination or Failure to Terminate
21089 @section GNAT Abnormal Termination or Failure to Terminate
21090 @cindex GNAT Abnormal Termination or Failure to Terminate
21092 @noindent
21093 When presented with programs that contain serious errors in syntax
21094 or semantics,
21095 GNAT may on rare occasions  experience problems in operation, such
21096 as aborting with a
21097 segmentation fault or illegal memory access, raising an internal
21098 exception, terminating abnormally, or failing to terminate at all.
21099 In such cases, you can activate
21100 various features of GNAT that can help you pinpoint the construct in your
21101 program that is the likely source of the problem.
21103 The following strategies are presented in increasing order of
21104 difficulty, corresponding to your experience in using GNAT and your
21105 familiarity with compiler internals.
21107 @enumerate
21108 @item
21109 Run @command{gcc} with the @option{-gnatf}. This first
21110 switch causes all errors on a given line to be reported. In its absence,
21111 only the first error on a line is displayed.
21113 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21114 are encountered, rather than after compilation is terminated. If GNAT
21115 terminates prematurely or goes into an infinite loop, the last error
21116 message displayed may help to pinpoint the culprit.
21118 @item
21119 Run @command{gcc} with the @option{-v (verbose)} switch. In this
21120 mode, @command{gcc} produces ongoing information about the progress of the
21121 compilation and provides the name of each procedure as code is
21122 generated. This switch allows you to find which Ada procedure was being
21123 compiled when it encountered a code generation problem.
21125 @item
21126 @cindex @option{-gnatdc} switch
21127 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21128 switch that does for the front-end what @option{-v} does
21129 for the back end. The system prints the name of each unit,
21130 either a compilation unit or nested unit, as it is being analyzed.
21131 @item
21132 Finally, you can start
21133 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21134 front-end of GNAT, and can be run independently (normally it is just
21135 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21136 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21137 @code{where} command is the first line of attack; the variable
21138 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21139 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21140 which the execution stopped, and @code{input_file name} indicates the name of
21141 the source file.
21142 @end enumerate
21144 @node Naming Conventions for GNAT Source Files
21145 @section Naming Conventions for GNAT Source Files
21147 @noindent
21148 In order to examine the workings of the GNAT system, the following
21149 brief description of its organization may be helpful:
21151 @itemize @bullet
21152 @item
21153 Files with prefix @file{sc} contain the lexical scanner.
21155 @item
21156 All files prefixed with @file{par} are components of the parser. The
21157 numbers correspond to chapters of the Ada Reference Manual. For example,
21158 parsing of select statements can be found in @file{par-ch9.adb}.
21160 @item
21161 All files prefixed with @file{sem} perform semantic analysis. The
21162 numbers correspond to chapters of the Ada standard. For example, all
21163 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21164 addition, some features of the language require sufficient special processing
21165 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21166 dynamic dispatching, etc.
21168 @item
21169 All files prefixed with @file{exp} perform normalization and
21170 expansion of the intermediate representation (abstract syntax tree, or AST).
21171 these files use the same numbering scheme as the parser and semantics files.
21172 For example, the construction of record initialization procedures is done in
21173 @file{exp_ch3.adb}.
21175 @item
21176 The files prefixed with @file{bind} implement the binder, which
21177 verifies the consistency of the compilation, determines an order of
21178 elaboration, and generates the bind file.
21180 @item
21181 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21182 data structures used by the front-end.
21184 @item
21185 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21186 the abstract syntax tree as produced by the parser.
21188 @item
21189 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21190 all entities, computed during semantic analysis.
21192 @item
21193 Library management issues are dealt with in files with prefix
21194 @file{lib}.
21196 @item
21197 @findex Ada
21198 @cindex Annex A
21199 Ada files with the prefix @file{a-} are children of @code{Ada}, as
21200 defined in Annex A.
21202 @item
21203 @findex Interfaces
21204 @cindex Annex B
21205 Files with prefix @file{i-} are children of @code{Interfaces}, as
21206 defined in Annex B.
21208 @item
21209 @findex System
21210 Files with prefix @file{s-} are children of @code{System}. This includes
21211 both language-defined children and GNAT run-time routines.
21213 @item
21214 @findex GNAT
21215 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
21216 general-purpose packages, fully documented in their specs. All
21217 the other @file{.c} files are modifications of common @command{gcc} files.
21218 @end itemize
21220 @node Getting Internal Debugging Information
21221 @section Getting Internal Debugging Information
21223 @noindent
21224 Most compilers have internal debugging switches and modes. GNAT
21225 does also, except GNAT internal debugging switches and modes are not
21226 secret. A summary and full description of all the compiler and binder
21227 debug flags are in the file @file{debug.adb}. You must obtain the
21228 sources of the compiler to see the full detailed effects of these flags.
21230 The switches that print the source of the program (reconstructed from
21231 the internal tree) are of general interest for user programs, as are the
21232 options to print
21233 the full internal tree, and the entity table (the symbol table
21234 information). The reconstructed source provides a readable version of the
21235 program after the front-end has completed analysis and  expansion,
21236 and is useful when studying the performance of specific constructs.
21237 For example, constraint checks are indicated, complex aggregates
21238 are replaced with loops and assignments, and tasking primitives
21239 are replaced with run-time calls.
21241 @node Stack Traceback
21242 @section Stack Traceback
21243 @cindex traceback
21244 @cindex stack traceback
21245 @cindex stack unwinding
21247 @noindent
21248 Traceback is a mechanism to display the sequence of subprogram calls that
21249 leads to a specified execution point in a program. Often (but not always)
21250 the execution point is an instruction at which an exception has been raised.
21251 This mechanism is also known as @i{stack unwinding} because it obtains
21252 its information by scanning the run-time stack and recovering the activation
21253 records of all active subprograms. Stack unwinding is one of the most
21254 important tools for program debugging.
21256 The first entry stored in traceback corresponds to the deepest calling level,
21257 that is to say the subprogram currently executing the instruction
21258 from which we want to obtain the traceback.
21260 Note that there is no runtime performance penalty when stack traceback
21261 is enabled, and no exception is raised during program execution.
21263 @menu
21264 * Non-Symbolic Traceback::
21265 * Symbolic Traceback::
21266 @end menu
21268 @node Non-Symbolic Traceback
21269 @subsection Non-Symbolic Traceback
21270 @cindex traceback, non-symbolic
21272 @noindent
21273 Note: this feature is not supported on all platforms. See
21274 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21275 platforms.
21277 @menu
21278 * Tracebacks From an Unhandled Exception::
21279 * Tracebacks From Exception Occurrences (non-symbolic)::
21280 * Tracebacks From Anywhere in a Program (non-symbolic)::
21281 @end menu
21283 @node Tracebacks From an Unhandled Exception
21284 @subsubsection Tracebacks From an Unhandled Exception
21286 @noindent
21287 A runtime non-symbolic traceback is a list of addresses of call instructions.
21288 To enable this feature you must use the @option{-E}
21289 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21290 of exception information. You can retrieve this information using the
21291 @code{addr2line} tool.
21293 Here is a simple example:
21295 @smallexample @c ada
21296 @cartouche
21297 @b{procedure} STB @b{is}
21299    @b{procedure} P1 @b{is}
21300    @b{begin}
21301       @b{raise} Constraint_Error;
21302    @b{end} P1;
21304    @b{procedure} P2 @b{is}
21305    @b{begin}
21306       P1;
21307    @b{end} P2;
21309 @b{begin}
21310    P2;
21311 @b{end} STB;
21312 @end cartouche
21313 @end smallexample
21315 @smallexample
21316 $ gnatmake stb -bargs -E
21317 $ stb
21319 Execution terminated by unhandled exception
21320 Exception name: CONSTRAINT_ERROR
21321 Message: stb.adb:5
21322 Call stack traceback locations:
21323 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21324 @end smallexample
21326 @noindent
21327 As we see the traceback lists a sequence of addresses for the unhandled
21328 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21329 guess that this exception come from procedure P1. To translate these
21330 addresses into the source lines where the calls appear, the
21331 @code{addr2line} tool, described below, is invaluable. The use of this tool
21332 requires the program to be compiled with debug information.
21334 @smallexample
21335 $ gnatmake -g stb -bargs -E
21336 $ stb
21338 Execution terminated by unhandled exception
21339 Exception name: CONSTRAINT_ERROR
21340 Message: stb.adb:5
21341 Call stack traceback locations:
21342 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21344 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21345    0x4011f1 0x77e892a4
21347 00401373 at d:/stb/stb.adb:5
21348 0040138B at d:/stb/stb.adb:10
21349 0040139C at d:/stb/stb.adb:14
21350 00401335 at d:/stb/b~stb.adb:104
21351 004011C4 at /build/@dots{}/crt1.c:200
21352 004011F1 at /build/@dots{}/crt1.c:222
21353 77E892A4 in ?? at ??:0
21354 @end smallexample
21356 @noindent
21357 The @code{addr2line} tool has several other useful options:
21359 @table @code
21360 @item --functions
21361 to get the function name corresponding to any location
21363 @item --demangle=gnat
21364 to use the gnat decoding mode for the function names. Note that
21365 for binutils version 2.9.x the option is simply @option{--demangle}.
21366 @end table
21368 @smallexample
21369 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21370    0x40139c 0x401335 0x4011c4 0x4011f1
21372 00401373 in stb.p1 at d:/stb/stb.adb:5
21373 0040138B in stb.p2 at d:/stb/stb.adb:10
21374 0040139C in stb at d:/stb/stb.adb:14
21375 00401335 in main at d:/stb/b~stb.adb:104
21376 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21377 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21378 @end smallexample
21380 @noindent
21381 From this traceback we can see that the exception was raised in
21382 @file{stb.adb} at line 5, which was reached from a procedure call in
21383 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21384 which contains the call to the main program.
21385 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21386 and the output will vary from platform to platform.
21388 It is also possible to use @code{GDB} with these traceback addresses to debug
21389 the program. For example, we can break at a given code location, as reported
21390 in the stack traceback:
21392 @smallexample
21393 $ gdb -nw stb
21394 @noindent
21395 Furthermore, this feature is not implemented inside Windows DLL. Only
21396 the non-symbolic traceback is reported in this case.
21398 (gdb) break *0x401373
21399 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21400 @end smallexample
21402 @noindent
21403 It is important to note that the stack traceback addresses
21404 do not change when debug information is included. This is particularly useful
21405 because it makes it possible to release software without debug information (to
21406 minimize object size), get a field report that includes a stack traceback
21407 whenever an internal bug occurs, and then be able to retrieve the sequence
21408 of calls with the same program compiled with debug information.
21410 @node Tracebacks From Exception Occurrences (non-symbolic)
21411 @subsubsection Tracebacks From Exception Occurrences
21413 @noindent
21414 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21415 The stack traceback is attached to the exception information string, and can
21416 be retrieved in an exception handler within the Ada program, by means of the
21417 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21419 @smallexample @c ada
21420 @b{with} Ada.Text_IO;
21421 @b{with} Ada.Exceptions;
21423 @b{procedure} STB @b{is}
21425    @b{use} Ada;
21426    @b{use} Ada.Exceptions;
21428    @b{procedure} P1 @b{is}
21429       K : Positive := 1;
21430    @b{begin}
21431       K := K - 1;
21432    @b{exception}
21433       @b{when} E : @b{others} =>
21434          Text_IO.Put_Line (Exception_Information (E));
21435    @b{end} P1;
21437    @b{procedure} P2 @b{is}
21438    @b{begin}
21439       P1;
21440    @b{end} P2;
21442 @b{begin}
21443    P2;
21444 @b{end} STB;
21445 @end smallexample
21447 @noindent
21448 This program will output:
21450 @smallexample
21451 $ stb
21453 Exception name: CONSTRAINT_ERROR
21454 Message: stb.adb:12
21455 Call stack traceback locations:
21456 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21457 @end smallexample
21459 @node Tracebacks From Anywhere in a Program (non-symbolic)
21460 @subsubsection Tracebacks From Anywhere in a Program
21462 @noindent
21463 It is also possible to retrieve a stack traceback from anywhere in a
21464 program. For this you need to
21465 use the @code{GNAT.Traceback} API. This package includes a procedure called
21466 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21467 display procedures described below. It is not necessary to use the
21468 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21469 is invoked explicitly.
21471 @noindent
21472 In the following example we compute a traceback at a specific location in
21473 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21474 convert addresses to strings:
21476 @smallexample @c ada
21477 @b{with} Ada.Text_IO;
21478 @b{with} GNAT.Traceback;
21479 @b{with} GNAT.Debug_Utilities;
21481 @b{procedure} STB @b{is}
21483    @b{use} Ada;
21484    @b{use} GNAT;
21485    @b{use} GNAT.Traceback;
21487    @b{procedure} P1 @b{is}
21488       TB  : Tracebacks_Array (1 .. 10);
21489       --@i{  We are asking for a maximum of 10 stack frames.}
21490       Len : Natural;
21491       --@i{  Len will receive the actual number of stack frames returned.}
21492    @b{begin}
21493       Call_Chain (TB, Len);
21495       Text_IO.Put ("In STB.P1 : ");
21497       @b{for} K @b{in} 1 .. Len @b{loop}
21498          Text_IO.Put (Debug_Utilities.Image (TB (K)));
21499          Text_IO.Put (' ');
21500       @b{end} @b{loop};
21502       Text_IO.New_Line;
21503    @b{end} P1;
21505    @b{procedure} P2 @b{is}
21506    @b{begin}
21507       P1;
21508    @b{end} P2;
21510 @b{begin}
21511    P2;
21512 @b{end} STB;
21513 @end smallexample
21515 @smallexample
21516 $ gnatmake -g stb
21517 $ stb
21519 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21520 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21521 @end smallexample
21523 @noindent
21524 You can then get further information by invoking the @code{addr2line}
21525 tool as described earlier (note that the hexadecimal addresses
21526 need to be specified in C format, with a leading ``0x'').
21528 @node Symbolic Traceback
21529 @subsection Symbolic Traceback
21530 @cindex traceback, symbolic
21532 @noindent
21533 A symbolic traceback is a stack traceback in which procedure names are
21534 associated with each code location.
21536 @noindent
21537 Note that this feature is not supported on all platforms. See
21538 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21539 list of currently supported platforms.
21541 @noindent
21542 Note that the symbolic traceback requires that the program be compiled
21543 with debug information. If it is not compiled with debug information
21544 only the non-symbolic information will be valid.
21546 @menu
21547 * Tracebacks From Exception Occurrences (symbolic)::
21548 * Tracebacks From Anywhere in a Program (symbolic)::
21549 @end menu
21551 @node Tracebacks From Exception Occurrences (symbolic)
21552 @subsubsection Tracebacks From Exception Occurrences
21554 @smallexample @c ada
21555 @b{with} Ada.Text_IO;
21556 @b{with} GNAT.Traceback.Symbolic;
21558 @b{procedure} STB @b{is}
21560    @b{procedure} P1 @b{is}
21561    @b{begin}
21562       @b{raise} Constraint_Error;
21563    @b{end} P1;
21565    @b{procedure} P2 @b{is}
21566    @b{begin}
21567       P1;
21568    @b{end} P2;
21570    @b{procedure} P3 @b{is}
21571    @b{begin}
21572       P2;
21573    @b{end} P3;
21575 @b{begin}
21576    P3;
21577 @b{exception}
21578    @b{when} E : @b{others} =>
21579       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21580 @b{end} STB;
21581 @end smallexample
21583 @smallexample
21584 $ gnatmake -g .\stb -bargs -E
21585 $ stb
21587 0040149F in stb.p1 at stb.adb:8
21588 004014B7 in stb.p2 at stb.adb:13
21589 004014CF in stb.p3 at stb.adb:18
21590 004015DD in ada.stb at stb.adb:22
21591 00401461 in main at b~stb.adb:168
21592 004011C4 in __mingw_CRTStartup at crt1.c:200
21593 004011F1 in mainCRTStartup at crt1.c:222
21594 77E892A4 in ?? at ??:0
21595 @end smallexample
21597 @noindent
21598 In the above example the ``.\'' syntax in the @command{gnatmake} command
21599 is currently required by @command{addr2line} for files that are in
21600 the current working directory.
21601 Moreover, the exact sequence of linker options may vary from platform
21602 to platform.
21603 The above @option{-largs} section is for Windows platforms. By contrast,
21604 under Unix there is no need for the @option{-largs} section.
21605 Differences across platforms are due to details of linker implementation.
21607 @node Tracebacks From Anywhere in a Program (symbolic)
21608 @subsubsection Tracebacks From Anywhere in a Program
21610 @noindent
21611 It is possible to get a symbolic stack traceback
21612 from anywhere in a program, just as for non-symbolic tracebacks.
21613 The first step is to obtain a non-symbolic
21614 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21615 information. Here is an example:
21617 @smallexample @c ada
21618 @b{with} Ada.Text_IO;
21619 @b{with} GNAT.Traceback;
21620 @b{with} GNAT.Traceback.Symbolic;
21622 @b{procedure} STB @b{is}
21624    @b{use} Ada;
21625    @b{use} GNAT.Traceback;
21626    @b{use} GNAT.Traceback.Symbolic;
21628    @b{procedure} P1 @b{is}
21629       TB  : Tracebacks_Array (1 .. 10);
21630       --@i{  We are asking for a maximum of 10 stack frames.}
21631       Len : Natural;
21632       --@i{  Len will receive the actual number of stack frames returned.}
21633    @b{begin}
21634       Call_Chain (TB, Len);
21635       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
21636    @b{end} P1;
21638    @b{procedure} P2 @b{is}
21639    @b{begin}
21640       P1;
21641    @b{end} P2;
21643 @b{begin}
21644    P2;
21645 @b{end} STB;
21646 @end smallexample
21648 @c ******************************
21650 @c **************************************
21651 @node Platform-Specific Information for the Run-Time Libraries
21652 @appendix Platform-Specific Information for the Run-Time Libraries
21653 @cindex Tasking and threads libraries
21654 @cindex Threads libraries and tasking
21655 @cindex Run-time libraries (platform-specific information)
21657 @noindent
21658 The GNAT run-time implementation may vary with respect to both the
21659 underlying threads library and the exception handling scheme.
21660 For threads support, one or more of the following are supplied:
21661 @itemize @bullet
21662 @item @b{native threads library}, a binding to the thread package from
21663 the underlying operating system
21665 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21666 POSIX thread package
21667 @end itemize
21669 @noindent
21670 For exception handling, either or both of two models are supplied:
21671 @itemize @bullet
21672 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21673 Most programs should experience a substantial speed improvement by
21674 being compiled with a ZCX run-time.
21675 This is especially true for
21676 tasking applications or applications with many exception handlers.}
21677 @cindex Zero-Cost Exceptions
21678 @cindex ZCX (Zero-Cost Exceptions)
21679 which uses binder-generated tables that
21680 are interrogated at run time to locate a handler
21682 @item @b{setjmp / longjmp} (``SJLJ''),
21683 @cindex setjmp/longjmp Exception Model
21684 @cindex SJLJ (setjmp/longjmp Exception Model)
21685 which uses dynamically-set data to establish
21686 the set of handlers
21687 @end itemize
21689 @noindent
21690 This appendix summarizes which combinations of threads and exception support
21691 are supplied on various GNAT platforms.
21692 It then shows how to select a particular library either
21693 permanently or temporarily,
21694 explains the properties of (and tradeoffs among) the various threads
21695 libraries, and provides some additional
21696 information about several specific platforms.
21698 @menu
21699 * Summary of Run-Time Configurations::
21700 * Specifying a Run-Time Library::
21701 * Choosing the Scheduling Policy::
21702 * Solaris-Specific Considerations::
21703 * Linux-Specific Considerations::
21704 * AIX-Specific Considerations::
21705 * RTX-Specific Considerations::
21706 * HP-UX-Specific Considerations::
21707 @end menu
21709 @node Summary of Run-Time Configurations
21710 @section Summary of Run-Time Configurations
21712 @multitable @columnfractions .30 .70
21713 @item @b{alpha-openvms}
21714 @item @code{@ @ }@i{rts-native (default)}
21715 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21716 @item @code{@ @ @ @ }Exceptions @tab ZCX
21718 @item @code{@ @ }@i{rts-sjlj}
21719 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21720 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21722 @item @b{ia64-hp_linux}
21723 @item @code{@ @ }@i{rts-native (default)}
21724 @item @code{@ @ @ @ }Tasking    @tab pthread library
21725 @item @code{@ @ @ @ }Exceptions @tab ZCX
21727 @item @b{ia64-hpux}
21728 @item @code{@ @ }@i{rts-native (default)}
21729 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21730 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21732 @item @b{ia64-openvms}
21733 @item @code{@ @ }@i{rts-native (default)}
21734 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21735 @item @code{@ @ @ @ }Exceptions @tab ZCX
21737 @item @b{ia64-sgi_linux}
21738 @item @code{@ @ }@i{rts-native (default)}
21739 @item @code{@ @ @ @ }Tasking    @tab pthread library
21740 @item @code{@ @ @ @ }Exceptions @tab ZCX
21742 @item @b{pa-hpux}
21743 @item @code{@ @ }@i{rts-native (default)}
21744 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21745 @item @code{@ @ @ @ }Exceptions @tab ZCX
21747 @item @code{@ @ }@i{rts-sjlj}
21748 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21749 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21751 @item @b{ppc-aix}
21752 @item @code{@ @ }@i{rts-native (default)}
21753 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21754 @item @code{@ @ @ @ }Exceptions @tab ZCX
21756 @item @code{@ @ }@i{rts-sjlj}
21757 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21758 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21760 @item @b{ppc-darwin}
21761 @item @code{@ @ }@i{rts-native (default)}
21762 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21763 @item @code{@ @ @ @ }Exceptions @tab ZCX
21765 @item @b{sparc-solaris}  @tab
21766 @item @code{@ @ }@i{rts-native (default)}
21767 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21768 @item @code{@ @ @ @ }Exceptions @tab ZCX
21770 @item @code{@ @ }@i{rts-pthread}
21771 @item @code{@ @ @ @ }Tasking    @tab pthread library
21772 @item @code{@ @ @ @ }Exceptions @tab ZCX
21774 @item @code{@ @ }@i{rts-sjlj}
21775 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21776 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21778 @item @b{sparc64-solaris}  @tab
21779 @item @code{@ @ }@i{rts-native (default)}
21780 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21781 @item @code{@ @ @ @ }Exceptions @tab ZCX
21783 @item @b{x86-linux}
21784 @item @code{@ @ }@i{rts-native (default)}
21785 @item @code{@ @ @ @ }Tasking    @tab pthread library
21786 @item @code{@ @ @ @ }Exceptions @tab ZCX
21788 @item @code{@ @ }@i{rts-sjlj}
21789 @item @code{@ @ @ @ }Tasking    @tab pthread library
21790 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21792 @item @b{x86-lynx}
21793 @item @code{@ @ }@i{rts-native (default)}
21794 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
21795 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21797 @item @b{x86-solaris}
21798 @item @code{@ @ }@i{rts-native (default)}
21799 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
21800 @item @code{@ @ @ @ }Exceptions @tab ZCX
21802 @item @code{@ @ }@i{rts-sjlj}
21803 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21804 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21806 @item @b{x86-windows}
21807 @item @code{@ @ }@i{rts-native (default)}
21808 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21809 @item @code{@ @ @ @ }Exceptions @tab ZCX
21811 @item @code{@ @ }@i{rts-sjlj}
21812 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21813 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21815 @item @b{x86-windows-rtx}
21816 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21817 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
21818 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21820 @item @code{@ @ }@i{rts-rtx-w32}
21821 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
21822 @item @code{@ @ @ @ }Exceptions @tab ZCX
21824 @item @b{x86_64-linux}
21825 @item @code{@ @ }@i{rts-native (default)}
21826 @item @code{@ @ @ @ }Tasking    @tab pthread library
21827 @item @code{@ @ @ @ }Exceptions @tab ZCX
21829 @item @code{@ @ }@i{rts-sjlj}
21830 @item @code{@ @ @ @ }Tasking    @tab pthread library
21831 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21833 @end multitable
21835 @node Specifying a Run-Time Library
21836 @section Specifying a Run-Time Library
21838 @noindent
21839 The @file{adainclude} subdirectory containing the sources of the GNAT
21840 run-time library, and the @file{adalib} subdirectory containing the
21841 @file{ALI} files and the static and/or shared GNAT library, are located
21842 in the gcc target-dependent area:
21844 @smallexample
21845 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21846 @end smallexample
21848 @noindent
21849 As indicated above, on some platforms several run-time libraries are supplied.
21850 These libraries are installed in the target dependent area and
21851 contain a complete source and binary subdirectory. The detailed description
21852 below explains the differences between the different libraries in terms of
21853 their thread support.
21855 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21856 This default run time is selected by the means of soft links.
21857 For example on x86-linux:
21859 @smallexample
21860 @group
21861  $(target-dir)
21862      |
21863      +--- adainclude----------+
21864      |                        |
21865      +--- adalib-----------+  |
21866      |                     |  |
21867      +--- rts-native       |  |
21868      |    |                |  |
21869      |    +--- adainclude <---+
21870      |    |                |
21871      |    +--- adalib <----+
21872      |
21873      +--- rts-sjlj
21874           |
21875           +--- adainclude
21876           |
21877           +--- adalib
21878 @end group
21879 @end smallexample
21881 @noindent
21882 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21883 these soft links can be modified with the following commands:
21885 @smallexample
21886 $ cd $target
21887 $ rm -f adainclude adalib
21888 $ ln -s rts-sjlj/adainclude adainclude
21889 $ ln -s rts-sjlj/adalib adalib
21890 @end smallexample
21892 @noindent
21893 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21894 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21895 @file{$target/ada_object_path}.
21897 Selecting another run-time library temporarily can be
21898 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21899 @cindex @option{--RTS} option
21901 @node Choosing the Scheduling Policy
21902 @section Choosing the Scheduling Policy
21904 @noindent
21905 When using a POSIX threads implementation, you have a choice of several
21906 scheduling policies: @code{SCHED_FIFO},
21907 @cindex @code{SCHED_FIFO} scheduling policy
21908 @code{SCHED_RR}
21909 @cindex @code{SCHED_RR} scheduling policy
21910 and @code{SCHED_OTHER}.
21911 @cindex @code{SCHED_OTHER} scheduling policy
21912 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21913 or @code{SCHED_RR} requires special (e.g., root) privileges.
21915 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21916 @code{SCHED_FIFO},
21917 @cindex @code{SCHED_FIFO} scheduling policy
21918 you can use one of the following:
21920 @itemize @bullet
21921 @item
21922 @code{pragma Time_Slice (0.0)}
21923 @cindex pragma Time_Slice
21924 @item
21925 the corresponding binder option @option{-T0}
21926 @cindex @option{-T0} option
21927 @item
21928 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21929 @cindex pragma Task_Dispatching_Policy
21930 @end itemize
21932 @noindent
21933 To specify @code{SCHED_RR},
21934 @cindex @code{SCHED_RR} scheduling policy
21935 you should use @code{pragma Time_Slice} with a
21936 value greater than @code{0.0}, or else use the corresponding @option{-T}
21937 binder option.
21939 @node Solaris-Specific Considerations
21940 @section Solaris-Specific Considerations
21941 @cindex Solaris Sparc threads libraries
21943 @noindent
21944 This section addresses some topics related to the various threads libraries
21945 on Sparc Solaris.
21947 @menu
21948 * Solaris Threads Issues::
21949 @end menu
21951 @node Solaris Threads Issues
21952 @subsection Solaris Threads Issues
21954 @noindent
21955 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21956 library based on POSIX threads --- @emph{rts-pthread}.
21957 @cindex rts-pthread threads library
21958 This run-time library has the advantage of being mostly shared across all
21959 POSIX-compliant thread implementations, and it also provides under
21960 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21961 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21962 and @code{PTHREAD_PRIO_PROTECT}
21963 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21964 semantics that can be selected using the predefined pragma
21965 @code{Locking_Policy}
21966 @cindex pragma Locking_Policy (under rts-pthread)
21967 with respectively
21968 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21969 @cindex @code{Inheritance_Locking} (under rts-pthread)
21970 @cindex @code{Ceiling_Locking} (under rts-pthread)
21972 As explained above, the native run-time library is based on the Solaris thread
21973 library (@code{libthread}) and is the default library.
21975 When the Solaris threads library is used (this is the default), programs
21976 compiled with GNAT can automatically take advantage of
21977 and can thus execute on multiple processors.
21978 The user can alternatively specify a processor on which the program should run
21979 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21980 is made by
21981 setting the environment variable @env{GNAT_PROCESSOR}
21982 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21983 to one of the following:
21985 @table @code
21986 @item -2
21987 Use the default configuration (run the program on all
21988 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21989 unset
21991 @item -1
21992 Let the run-time implementation choose one processor and run the program on
21993 that processor
21995 @item 0 .. Last_Proc
21996 Run the program on the specified processor.
21997 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21998 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21999 @end table
22001 @node Linux-Specific Considerations
22002 @section Linux-Specific Considerations
22003 @cindex Linux threads libraries
22005 @noindent
22006 On GNU/Linux without NPTL support (usually system with GNU C Library
22007 older than 2.3), the signal model is not POSIX compliant, which means
22008 that to send a signal to the process, you need to send the signal to all
22009 threads, e.g.@: by using @code{killpg()}.
22011 @node AIX-Specific Considerations
22012 @section AIX-Specific Considerations
22013 @cindex AIX resolver library
22015 @noindent
22016 On AIX, the resolver library initializes some internal structure on
22017 the first call to @code{get*by*} functions, which are used to implement
22018 @code{GNAT.Sockets.Get_Host_By_Name} and
22019 @code{GNAT.Sockets.Get_Host_By_Address}.
22020 If such initialization occurs within an Ada task, and the stack size for
22021 the task is the default size, a stack overflow may occur.
22023 To avoid this overflow, the user should either ensure that the first call
22024 to @code{GNAT.Sockets.Get_Host_By_Name} or
22025 @code{GNAT.Sockets.Get_Host_By_Addrss}
22026 occurs in the environment task, or use @code{pragma Storage_Size} to
22027 specify a sufficiently large size for the stack of the task that contains
22028 this call.
22030 @node RTX-Specific Considerations
22031 @section RTX-Specific Considerations
22032 @cindex RTX libraries
22034 @noindent
22035 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22036 API. Applications can be built to work in two different modes:
22038 @itemize @bullet
22039 @item
22040 Windows executables that run in Ring 3 to utilize memory protection
22041 (@emph{rts-rtx-w32}).
22043 @item
22044 Real-time subsystem (RTSS) executables that run in Ring 0, where
22045 performance can be optimized with RTSS applications taking precedent
22046 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22047 the Microsoft linker to handle RTSS libraries.
22049 @end itemize
22051 @node HP-UX-Specific Considerations
22052 @section HP-UX-Specific Considerations
22053 @cindex HP-UX Scheduling
22055 @noindent
22056 On HP-UX, appropriate privileges are required to change the scheduling
22057 parameters of a task. The calling process must have appropriate
22058 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22059 successfully change the scheduling parameters.
22061 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22062 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22063 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22065 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22066 one of the following:
22068 @itemize @bullet
22069 @item
22070 @code{pragma Time_Slice (0.0)}
22071 @cindex pragma Time_Slice
22072 @item
22073 the corresponding binder option @option{-T0}
22074 @cindex @option{-T0} option
22075 @item
22076 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22077 @cindex pragma Task_Dispatching_Policy
22078 @end itemize
22080 @noindent
22081 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22082 you should use @code{pragma Time_Slice} with a
22083 value greater than @code{0.0}, or use the corresponding @option{-T}
22084 binder option, or set the @code{pragma Task_Dispatching_Policy
22085 (Round_Robin_Within_Priorities)}.
22087 @c *******************************
22088 @node Example of Binder Output File
22089 @appendix Example of Binder Output File
22091 @noindent
22092 This Appendix displays the source code for @command{gnatbind}'s output
22093 file generated for a simple ``Hello World'' program.
22094 Comments have been added for clarification purposes.
22096 @smallexample @c adanocomment
22097 @iftex
22098 @leftskip=0cm
22099 @end iftex
22100 --  The package is called Ada_Main unless this name is actually used
22101 --  as a unit name in the partition, in which case some other unique
22102 --  name is used.
22104 @b{with} System;
22105 @b{package} ada_main @b{is}
22107    Elab_Final_Code : Integer;
22108    @b{pragma} Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22110    --  The main program saves the parameters (argument count,
22111    --  argument values, environment pointer) in global variables
22112    --  for later access by other units including
22113    --  Ada.Command_Line.
22115    gnat_argc : Integer;
22116    gnat_argv : System.Address;
22117    gnat_envp : System.Address;
22119    --  The actual variables are stored in a library routine. This
22120    --  is useful for some shared library situations, where there
22121    --  are problems if variables are not in the library.
22123    @b{pragma} Import (C, gnat_argc);
22124    @b{pragma} Import (C, gnat_argv);
22125    @b{pragma} Import (C, gnat_envp);
22127    --  The exit status is similarly an external location
22129    gnat_exit_status : Integer;
22130    @b{pragma} Import (C, gnat_exit_status);
22132    GNAT_Version : @b{constant} String :=
22133                     "GNAT Version: 6.0.0w (20061115)";
22134    @b{pragma} Export (C, GNAT_Version, "__gnat_version");
22136    --  This is the generated adafinal routine that performs
22137    --  finalization at the end of execution. In the case where
22138    --  Ada is the main program, this main program makes a call
22139    --  to adafinal at program termination.
22141    @b{procedure} adafinal;
22142    @b{pragma} Export (C, adafinal, "adafinal");
22144    --  This is the generated adainit routine that performs
22145    --  initialization at the start of execution. In the case
22146    --  where Ada is the main program, this main program makes
22147    --  a call to adainit at program startup.
22149    @b{procedure} adainit;
22150    @b{pragma} Export (C, adainit, "adainit");
22152    --  This routine is called at the start of execution. It is
22153    --  a dummy routine that is used by the debugger to breakpoint
22154    --  at the start of execution.
22156    @b{procedure} Break_Start;
22157    @b{pragma} Import (C, Break_Start, "__gnat_break_start");
22159    --  This is the actual generated main program (it would be
22160    --  suppressed if the no main program switch were used). As
22161    --  required by standard system conventions, this program has
22162    --  the external name main.
22164    @b{function} main
22165      (argc : Integer;
22166       argv : System.Address;
22167       envp : System.Address)
22168       @b{return} Integer;
22169    @b{pragma} Export (C, main, "main");
22171    --  The following set of constants give the version
22172    --  identification values for every unit in the bound
22173    --  partition. This identification is computed from all
22174    --  dependent semantic units, and corresponds to the
22175    --  string that would be returned by use of the
22176    --  Body_Version or Version attributes.
22178    @b{type} Version_32 @b{is} @b{mod} 2 ** 32;
22179    u00001 : @b{constant} Version_32 := 16#7880BEB3#;
22180    u00002 : @b{constant} Version_32 := 16#0D24CBD0#;
22181    u00003 : @b{constant} Version_32 := 16#3283DBEB#;
22182    u00004 : @b{constant} Version_32 := 16#2359F9ED#;
22183    u00005 : @b{constant} Version_32 := 16#664FB847#;
22184    u00006 : @b{constant} Version_32 := 16#68E803DF#;
22185    u00007 : @b{constant} Version_32 := 16#5572E604#;
22186    u00008 : @b{constant} Version_32 := 16#46B173D8#;
22187    u00009 : @b{constant} Version_32 := 16#156A40CF#;
22188    u00010 : @b{constant} Version_32 := 16#033DABE0#;
22189    u00011 : @b{constant} Version_32 := 16#6AB38FEA#;
22190    u00012 : @b{constant} Version_32 := 16#22B6217D#;
22191    u00013 : @b{constant} Version_32 := 16#68A22947#;
22192    u00014 : @b{constant} Version_32 := 16#18CC4A56#;
22193    u00015 : @b{constant} Version_32 := 16#08258E1B#;
22194    u00016 : @b{constant} Version_32 := 16#367D5222#;
22195    u00017 : @b{constant} Version_32 := 16#20C9ECA4#;
22196    u00018 : @b{constant} Version_32 := 16#50D32CB6#;
22197    u00019 : @b{constant} Version_32 := 16#39A8BB77#;
22198    u00020 : @b{constant} Version_32 := 16#5CF8FA2B#;
22199    u00021 : @b{constant} Version_32 := 16#2F1EB794#;
22200    u00022 : @b{constant} Version_32 := 16#31AB6444#;
22201    u00023 : @b{constant} Version_32 := 16#1574B6E9#;
22202    u00024 : @b{constant} Version_32 := 16#5109C189#;
22203    u00025 : @b{constant} Version_32 := 16#56D770CD#;
22204    u00026 : @b{constant} Version_32 := 16#02F9DE3D#;
22205    u00027 : @b{constant} Version_32 := 16#08AB6B2C#;
22206    u00028 : @b{constant} Version_32 := 16#3FA37670#;
22207    u00029 : @b{constant} Version_32 := 16#476457A0#;
22208    u00030 : @b{constant} Version_32 := 16#731E1B6E#;
22209    u00031 : @b{constant} Version_32 := 16#23C2E789#;
22210    u00032 : @b{constant} Version_32 := 16#0F1BD6A1#;
22211    u00033 : @b{constant} Version_32 := 16#7C25DE96#;
22212    u00034 : @b{constant} Version_32 := 16#39ADFFA2#;
22213    u00035 : @b{constant} Version_32 := 16#571DE3E7#;
22214    u00036 : @b{constant} Version_32 := 16#5EB646AB#;
22215    u00037 : @b{constant} Version_32 := 16#4249379B#;
22216    u00038 : @b{constant} Version_32 := 16#0357E00A#;
22217    u00039 : @b{constant} Version_32 := 16#3784FB72#;
22218    u00040 : @b{constant} Version_32 := 16#2E723019#;
22219    u00041 : @b{constant} Version_32 := 16#623358EA#;
22220    u00042 : @b{constant} Version_32 := 16#107F9465#;
22221    u00043 : @b{constant} Version_32 := 16#6843F68A#;
22222    u00044 : @b{constant} Version_32 := 16#63305874#;
22223    u00045 : @b{constant} Version_32 := 16#31E56CE1#;
22224    u00046 : @b{constant} Version_32 := 16#02917970#;
22225    u00047 : @b{constant} Version_32 := 16#6CCBA70E#;
22226    u00048 : @b{constant} Version_32 := 16#41CD4204#;
22227    u00049 : @b{constant} Version_32 := 16#572E3F58#;
22228    u00050 : @b{constant} Version_32 := 16#20729FF5#;
22229    u00051 : @b{constant} Version_32 := 16#1D4F93E8#;
22230    u00052 : @b{constant} Version_32 := 16#30B2EC3D#;
22231    u00053 : @b{constant} Version_32 := 16#34054F96#;
22232    u00054 : @b{constant} Version_32 := 16#5A199860#;
22233    u00055 : @b{constant} Version_32 := 16#0E7F912B#;
22234    u00056 : @b{constant} Version_32 := 16#5760634A#;
22235    u00057 : @b{constant} Version_32 := 16#5D851835#;
22237    --  The following Export pragmas export the version numbers
22238    --  with symbolic names ending in B (for body) or S
22239    --  (for spec) so that they can be located in a link. The
22240    --  information provided here is sufficient to track down
22241    --  the exact versions of units used in a given build.
22243    @b{pragma} Export (C, u00001, "helloB");
22244    @b{pragma} Export (C, u00002, "system__standard_libraryB");
22245    @b{pragma} Export (C, u00003, "system__standard_libraryS");
22246    @b{pragma} Export (C, u00004, "adaS");
22247    @b{pragma} Export (C, u00005, "ada__text_ioB");
22248    @b{pragma} Export (C, u00006, "ada__text_ioS");
22249    @b{pragma} Export (C, u00007, "ada__exceptionsB");
22250    @b{pragma} Export (C, u00008, "ada__exceptionsS");
22251    @b{pragma} Export (C, u00009, "gnatS");
22252    @b{pragma} Export (C, u00010, "gnat__heap_sort_aB");
22253    @b{pragma} Export (C, u00011, "gnat__heap_sort_aS");
22254    @b{pragma} Export (C, u00012, "systemS");
22255    @b{pragma} Export (C, u00013, "system__exception_tableB");
22256    @b{pragma} Export (C, u00014, "system__exception_tableS");
22257    @b{pragma} Export (C, u00015, "gnat__htableB");
22258    @b{pragma} Export (C, u00016, "gnat__htableS");
22259    @b{pragma} Export (C, u00017, "system__exceptionsS");
22260    @b{pragma} Export (C, u00018, "system__machine_state_operationsB");
22261    @b{pragma} Export (C, u00019, "system__machine_state_operationsS");
22262    @b{pragma} Export (C, u00020, "system__machine_codeS");
22263    @b{pragma} Export (C, u00021, "system__storage_elementsB");
22264    @b{pragma} Export (C, u00022, "system__storage_elementsS");
22265    @b{pragma} Export (C, u00023, "system__secondary_stackB");
22266    @b{pragma} Export (C, u00024, "system__secondary_stackS");
22267    @b{pragma} Export (C, u00025, "system__parametersB");
22268    @b{pragma} Export (C, u00026, "system__parametersS");
22269    @b{pragma} Export (C, u00027, "system__soft_linksB");
22270    @b{pragma} Export (C, u00028, "system__soft_linksS");
22271    @b{pragma} Export (C, u00029, "system__stack_checkingB");
22272    @b{pragma} Export (C, u00030, "system__stack_checkingS");
22273    @b{pragma} Export (C, u00031, "system__tracebackB");
22274    @b{pragma} Export (C, u00032, "system__tracebackS");
22275    @b{pragma} Export (C, u00033, "ada__streamsS");
22276    @b{pragma} Export (C, u00034, "ada__tagsB");
22277    @b{pragma} Export (C, u00035, "ada__tagsS");
22278    @b{pragma} Export (C, u00036, "system__string_opsB");
22279    @b{pragma} Export (C, u00037, "system__string_opsS");
22280    @b{pragma} Export (C, u00038, "interfacesS");
22281    @b{pragma} Export (C, u00039, "interfaces__c_streamsB");
22282    @b{pragma} Export (C, u00040, "interfaces__c_streamsS");
22283    @b{pragma} Export (C, u00041, "system__file_ioB");
22284    @b{pragma} Export (C, u00042, "system__file_ioS");
22285    @b{pragma} Export (C, u00043, "ada__finalizationB");
22286    @b{pragma} Export (C, u00044, "ada__finalizationS");
22287    @b{pragma} Export (C, u00045, "system__finalization_rootB");
22288    @b{pragma} Export (C, u00046, "system__finalization_rootS");
22289    @b{pragma} Export (C, u00047, "system__finalization_implementationB");
22290    @b{pragma} Export (C, u00048, "system__finalization_implementationS");
22291    @b{pragma} Export (C, u00049, "system__string_ops_concat_3B");
22292    @b{pragma} Export (C, u00050, "system__string_ops_concat_3S");
22293    @b{pragma} Export (C, u00051, "system__stream_attributesB");
22294    @b{pragma} Export (C, u00052, "system__stream_attributesS");
22295    @b{pragma} Export (C, u00053, "ada__io_exceptionsS");
22296    @b{pragma} Export (C, u00054, "system__unsigned_typesS");
22297    @b{pragma} Export (C, u00055, "system__file_control_blockS");
22298    @b{pragma} Export (C, u00056, "ada__finalization__list_controllerB");
22299    @b{pragma} Export (C, u00057, "ada__finalization__list_controllerS");
22301    -- BEGIN ELABORATION ORDER
22302    -- ada (spec)
22303    -- gnat (spec)
22304    -- gnat.heap_sort_a (spec)
22305    -- gnat.heap_sort_a (body)
22306    -- gnat.htable (spec)
22307    -- gnat.htable (body)
22308    -- interfaces (spec)
22309    -- system (spec)
22310    -- system.machine_code (spec)
22311    -- system.parameters (spec)
22312    -- system.parameters (body)
22313    -- interfaces.c_streams (spec)
22314    -- interfaces.c_streams (body)
22315    -- system.standard_library (spec)
22316    -- ada.exceptions (spec)
22317    -- system.exception_table (spec)
22318    -- system.exception_table (body)
22319    -- ada.io_exceptions (spec)
22320    -- system.exceptions (spec)
22321    -- system.storage_elements (spec)
22322    -- system.storage_elements (body)
22323    -- system.machine_state_operations (spec)
22324    -- system.machine_state_operations (body)
22325    -- system.secondary_stack (spec)
22326    -- system.stack_checking (spec)
22327    -- system.soft_links (spec)
22328    -- system.soft_links (body)
22329    -- system.stack_checking (body)
22330    -- system.secondary_stack (body)
22331    -- system.standard_library (body)
22332    -- system.string_ops (spec)
22333    -- system.string_ops (body)
22334    -- ada.tags (spec)
22335    -- ada.tags (body)
22336    -- ada.streams (spec)
22337    -- system.finalization_root (spec)
22338    -- system.finalization_root (body)
22339    -- system.string_ops_concat_3 (spec)
22340    -- system.string_ops_concat_3 (body)
22341    -- system.traceback (spec)
22342    -- system.traceback (body)
22343    -- ada.exceptions (body)
22344    -- system.unsigned_types (spec)
22345    -- system.stream_attributes (spec)
22346    -- system.stream_attributes (body)
22347    -- system.finalization_implementation (spec)
22348    -- system.finalization_implementation (body)
22349    -- ada.finalization (spec)
22350    -- ada.finalization (body)
22351    -- ada.finalization.list_controller (spec)
22352    -- ada.finalization.list_controller (body)
22353    -- system.file_control_block (spec)
22354    -- system.file_io (spec)
22355    -- system.file_io (body)
22356    -- ada.text_io (spec)
22357    -- ada.text_io (body)
22358    -- hello (body)
22359    -- END ELABORATION ORDER
22361 @b{end} ada_main;
22363 --  The following source file name pragmas allow the generated file
22364 --  names to be unique for different main programs. They are needed
22365 --  since the package name will always be Ada_Main.
22367 @b{pragma} Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22368 @b{pragma} Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22370 --  Generated package body for Ada_Main starts here
22372 @b{package} @b{body} ada_main @b{is}
22374    --  The actual finalization is performed by calling the
22375    --  library routine in System.Standard_Library.Adafinal
22377    @b{procedure} Do_Finalize;
22378    @b{pragma} Import (C, Do_Finalize, "system__standard_library__adafinal");
22380    -------------
22381    -- adainit --
22382    -------------
22384 @findex adainit
22385    @b{procedure} adainit @b{is}
22387       --  These booleans are set to True once the associated unit has
22388       --  been elaborated. It is also used to avoid elaborating the
22389       --  same unit twice.
22391       E040 : Boolean;
22392       @b{pragma} Import (Ada, E040, "interfaces__c_streams_E");
22394       E008 : Boolean;
22395       @b{pragma} Import (Ada, E008, "ada__exceptions_E");
22397       E014 : Boolean;
22398       @b{pragma} Import (Ada, E014, "system__exception_table_E");
22400       E053 : Boolean;
22401       @b{pragma} Import (Ada, E053, "ada__io_exceptions_E");
22403       E017 : Boolean;
22404       @b{pragma} Import (Ada, E017, "system__exceptions_E");
22406       E024 : Boolean;
22407       @b{pragma} Import (Ada, E024, "system__secondary_stack_E");
22409       E030 : Boolean;
22410       @b{pragma} Import (Ada, E030, "system__stack_checking_E");
22412       E028 : Boolean;
22413       @b{pragma} Import (Ada, E028, "system__soft_links_E");
22415       E035 : Boolean;
22416       @b{pragma} Import (Ada, E035, "ada__tags_E");
22418       E033 : Boolean;
22419       @b{pragma} Import (Ada, E033, "ada__streams_E");
22421       E046 : Boolean;
22422       @b{pragma} Import (Ada, E046, "system__finalization_root_E");
22424       E048 : Boolean;
22425       @b{pragma} Import (Ada, E048, "system__finalization_implementation_E");
22427       E044 : Boolean;
22428       @b{pragma} Import (Ada, E044, "ada__finalization_E");
22430       E057 : Boolean;
22431       @b{pragma} Import (Ada, E057, "ada__finalization__list_controller_E");
22433       E055 : Boolean;
22434       @b{pragma} Import (Ada, E055, "system__file_control_block_E");
22436       E042 : Boolean;
22437       @b{pragma} Import (Ada, E042, "system__file_io_E");
22439       E006 : Boolean;
22440       @b{pragma} Import (Ada, E006, "ada__text_io_E");
22442       --  Set_Globals is a library routine that stores away the
22443       --  value of the indicated set of global values in global
22444       --  variables within the library.
22446       @b{procedure} Set_Globals
22447         (Main_Priority            : Integer;
22448          Time_Slice_Value         : Integer;
22449          WC_Encoding              : Character;
22450          Locking_Policy           : Character;
22451          Queuing_Policy           : Character;
22452          Task_Dispatching_Policy  : Character;
22453          Adafinal                 : System.Address;
22454          Unreserve_All_Interrupts : Integer;
22455          Exception_Tracebacks     : Integer);
22456 @findex __gnat_set_globals
22457       @b{pragma} Import (C, Set_Globals, "__gnat_set_globals");
22459       --  SDP_Table_Build is a library routine used to build the
22460       --  exception tables. See unit Ada.Exceptions in files
22461       --  a-except.ads/adb for full details of how zero cost
22462       --  exception handling works. This procedure, the call to
22463       --  it, and the two following tables are all omitted if the
22464       --  build is in longjmp/setjmp exception mode.
22466 @findex SDP_Table_Build
22467 @findex Zero Cost Exceptions
22468       @b{procedure} SDP_Table_Build
22469         (SDP_Addresses   : System.Address;
22470          SDP_Count       : Natural;
22471          Elab_Addresses  : System.Address;
22472          Elab_Addr_Count : Natural);
22473       @b{pragma} Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22475       --  Table of Unit_Exception_Table addresses. Used for zero
22476       --  cost exception handling to build the top level table.
22478       ST : @b{aliased} @b{constant} @b{array} (1 .. 23) @b{of} System.Address := (
22479         Hello'UET_Address,
22480         Ada.Text_Io'UET_Address,
22481         Ada.Exceptions'UET_Address,
22482         Gnat.Heap_Sort_A'UET_Address,
22483         System.Exception_Table'UET_Address,
22484         System.Machine_State_Operations'UET_Address,
22485         System.Secondary_Stack'UET_Address,
22486         System.Parameters'UET_Address,
22487         System.Soft_Links'UET_Address,
22488         System.Stack_Checking'UET_Address,
22489         System.Traceback'UET_Address,
22490         Ada.Streams'UET_Address,
22491         Ada.Tags'UET_Address,
22492         System.String_Ops'UET_Address,
22493         Interfaces.C_Streams'UET_Address,
22494         System.File_Io'UET_Address,
22495         Ada.Finalization'UET_Address,
22496         System.Finalization_Root'UET_Address,
22497         System.Finalization_Implementation'UET_Address,
22498         System.String_Ops_Concat_3'UET_Address,
22499         System.Stream_Attributes'UET_Address,
22500         System.File_Control_Block'UET_Address,
22501         Ada.Finalization.List_Controller'UET_Address);
22503       --  Table of addresses of elaboration routines. Used for
22504       --  zero cost exception handling to make sure these
22505       --  addresses are included in the top level procedure
22506       --  address table.
22508       EA : @b{aliased} @b{constant} @b{array} (1 .. 23) @b{of} System.Address := (
22509         adainit'Code_Address,
22510         Do_Finalize'Code_Address,
22511         Ada.Exceptions'Elab_Spec'Address,
22512         System.Exceptions'Elab_Spec'Address,
22513         Interfaces.C_Streams'Elab_Spec'Address,
22514         System.Exception_Table'Elab_Body'Address,
22515         Ada.Io_Exceptions'Elab_Spec'Address,
22516         System.Stack_Checking'Elab_Spec'Address,
22517         System.Soft_Links'Elab_Body'Address,
22518         System.Secondary_Stack'Elab_Body'Address,
22519         Ada.Tags'Elab_Spec'Address,
22520         Ada.Tags'Elab_Body'Address,
22521         Ada.Streams'Elab_Spec'Address,
22522         System.Finalization_Root'Elab_Spec'Address,
22523         Ada.Exceptions'Elab_Body'Address,
22524         System.Finalization_Implementation'Elab_Spec'Address,
22525         System.Finalization_Implementation'Elab_Body'Address,
22526         Ada.Finalization'Elab_Spec'Address,
22527         Ada.Finalization.List_Controller'Elab_Spec'Address,
22528         System.File_Control_Block'Elab_Spec'Address,
22529         System.File_Io'Elab_Body'Address,
22530         Ada.Text_Io'Elab_Spec'Address,
22531         Ada.Text_Io'Elab_Body'Address);
22533    --  Start of processing for adainit
22535    @b{begin}
22537       --  Call SDP_Table_Build to build the top level procedure
22538       --  table for zero cost exception handling (omitted in
22539       --  longjmp/setjmp mode).
22541       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22543       --  Call Set_Globals to record various information for
22544       --  this partition.  The values are derived by the binder
22545       --  from information stored in the ali files by the compiler.
22547 @findex __gnat_set_globals
22548       Set_Globals
22549         (Main_Priority            => -1,
22550          --  Priority of main program, -1 if no pragma Priority used
22552          Time_Slice_Value         => -1,
22553          --  Time slice from Time_Slice pragma, -1 if none used
22555          WC_Encoding              => 'b',
22556          --  Wide_Character encoding used, default is brackets
22558          Locking_Policy           => ' ',
22559          --  Locking_Policy used, default of space means not
22560          --  specified, otherwise it is the first character of
22561          --  the policy name.
22563          Queuing_Policy           => ' ',
22564          --  Queuing_Policy used, default of space means not
22565          --  specified, otherwise it is the first character of
22566          --  the policy name.
22568          Task_Dispatching_Policy  => ' ',
22569          --  Task_Dispatching_Policy used, default of space means
22570          --  not specified, otherwise first character of the
22571          --  policy name.
22573          Adafinal                 => System.Null_Address,
22574          --  Address of Adafinal routine, not used anymore
22576          Unreserve_All_Interrupts => 0,
22577          --  Set true if pragma Unreserve_All_Interrupts was used
22579          Exception_Tracebacks     => 0);
22580          --  Indicates if exception tracebacks are enabled
22582       Elab_Final_Code := 1;
22584       --  Now we have the elaboration calls for all units in the partition.
22585       --  The Elab_Spec and Elab_Body attributes generate references to the
22586       --  implicit elaboration procedures generated by the compiler for
22587       --  each unit that requires elaboration.
22589       @b{if} @b{not} E040 @b{then}
22590          Interfaces.C_Streams'Elab_Spec;
22591       @b{end} @b{if};
22592       E040 := True;
22593       @b{if} @b{not} E008 @b{then}
22594          Ada.Exceptions'Elab_Spec;
22595       @b{end} @b{if};
22596       @b{if} @b{not} E014 @b{then}
22597          System.Exception_Table'Elab_Body;
22598          E014 := True;
22599       @b{end} @b{if};
22600       @b{if} @b{not} E053 @b{then}
22601          Ada.Io_Exceptions'Elab_Spec;
22602          E053 := True;
22603       @b{end} @b{if};
22604       @b{if} @b{not} E017 @b{then}
22605          System.Exceptions'Elab_Spec;
22606          E017 := True;
22607       @b{end} @b{if};
22608       @b{if} @b{not} E030 @b{then}
22609          System.Stack_Checking'Elab_Spec;
22610       @b{end} @b{if};
22611       @b{if} @b{not} E028 @b{then}
22612          System.Soft_Links'Elab_Body;
22613          E028 := True;
22614       @b{end} @b{if};
22615       E030 := True;
22616       @b{if} @b{not} E024 @b{then}
22617          System.Secondary_Stack'Elab_Body;
22618          E024 := True;
22619       @b{end} @b{if};
22620       @b{if} @b{not} E035 @b{then}
22621          Ada.Tags'Elab_Spec;
22622       @b{end} @b{if};
22623       @b{if} @b{not} E035 @b{then}
22624          Ada.Tags'Elab_Body;
22625          E035 := True;
22626       @b{end} @b{if};
22627       @b{if} @b{not} E033 @b{then}
22628          Ada.Streams'Elab_Spec;
22629          E033 := True;
22630       @b{end} @b{if};
22631       @b{if} @b{not} E046 @b{then}
22632          System.Finalization_Root'Elab_Spec;
22633       @b{end} @b{if};
22634       E046 := True;
22635       @b{if} @b{not} E008 @b{then}
22636          Ada.Exceptions'Elab_Body;
22637          E008 := True;
22638       @b{end} @b{if};
22639       @b{if} @b{not} E048 @b{then}
22640          System.Finalization_Implementation'Elab_Spec;
22641       @b{end} @b{if};
22642       @b{if} @b{not} E048 @b{then}
22643          System.Finalization_Implementation'Elab_Body;
22644          E048 := True;
22645       @b{end} @b{if};
22646       @b{if} @b{not} E044 @b{then}
22647          Ada.Finalization'Elab_Spec;
22648       @b{end} @b{if};
22649       E044 := True;
22650       @b{if} @b{not} E057 @b{then}
22651          Ada.Finalization.List_Controller'Elab_Spec;
22652       @b{end} @b{if};
22653       E057 := True;
22654       @b{if} @b{not} E055 @b{then}
22655          System.File_Control_Block'Elab_Spec;
22656          E055 := True;
22657       @b{end} @b{if};
22658       @b{if} @b{not} E042 @b{then}
22659          System.File_Io'Elab_Body;
22660          E042 := True;
22661       @b{end} @b{if};
22662       @b{if} @b{not} E006 @b{then}
22663          Ada.Text_Io'Elab_Spec;
22664       @b{end} @b{if};
22665       @b{if} @b{not} E006 @b{then}
22666          Ada.Text_Io'Elab_Body;
22667          E006 := True;
22668       @b{end} @b{if};
22670       Elab_Final_Code := 0;
22671    @b{end} adainit;
22673    --------------
22674    -- adafinal --
22675    --------------
22677 @findex adafinal
22678    @b{procedure} adafinal @b{is}
22679    @b{begin}
22680       Do_Finalize;
22681    @b{end} adafinal;
22683    ----------
22684    -- main --
22685    ----------
22687    --  main is actually a function, as in the ANSI C standard,
22688    --  defined to return the exit status. The three parameters
22689    --  are the argument count, argument values and environment
22690    --  pointer.
22692 @findex Main Program
22693    @b{function} main
22694      (argc : Integer;
22695       argv : System.Address;
22696       envp : System.Address)
22697       @b{return} Integer
22698    @b{is}
22699       --  The initialize routine performs low level system
22700       --  initialization using a standard library routine which
22701       --  sets up signal handling and performs any other
22702       --  required setup. The routine can be found in file
22703       --  a-init.c.
22705 @findex __gnat_initialize
22706       @b{procedure} initialize;
22707       @b{pragma} Import (C, initialize, "__gnat_initialize");
22709       --  The finalize routine performs low level system
22710       --  finalization using a standard library routine. The
22711       --  routine is found in file a-final.c and in the standard
22712       --  distribution is a dummy routine that does nothing, so
22713       --  really this is a hook for special user finalization.
22715 @findex __gnat_finalize
22716       @b{procedure} finalize;
22717       @b{pragma} Import (C, finalize, "__gnat_finalize");
22719       --  We get to the main program of the partition by using
22720       --  pragma Import because if we try to with the unit and
22721       --  call it Ada style, then not only do we waste time
22722       --  recompiling it, but also, we don't really know the right
22723       --  switches (e.g.@: identifier character set) to be used
22724       --  to compile it.
22726       @b{procedure} Ada_Main_Program;
22727       @b{pragma} Import (Ada, Ada_Main_Program, "_ada_hello");
22729    --  Start of processing for main
22731    @b{begin}
22732       --  Save global variables
22734       gnat_argc := argc;
22735       gnat_argv := argv;
22736       gnat_envp := envp;
22738       --  Call low level system initialization
22740       Initialize;
22742       --  Call our generated Ada initialization routine
22744       adainit;
22746       --  This is the point at which we want the debugger to get
22747       --  control
22749       Break_Start;
22751       --  Now we call the main program of the partition
22753       Ada_Main_Program;
22755       --  Perform Ada finalization
22757       adafinal;
22759       --  Perform low level system finalization
22761       Finalize;
22763       --  Return the proper exit status
22764       @b{return} (gnat_exit_status);
22765    @b{end};
22767 --  This section is entirely comments, so it has no effect on the
22768 --  compilation of the Ada_Main package. It provides the list of
22769 --  object files and linker options, as well as some standard
22770 --  libraries needed for the link. The gnatlink utility parses
22771 --  this b~hello.adb file to read these comment lines to generate
22772 --  the appropriate command line arguments for the call to the
22773 --  system linker. The BEGIN/END lines are used for sentinels for
22774 --  this parsing operation.
22776 --  The exact file names will of course depend on the environment,
22777 --  host/target and location of files on the host system.
22779 @findex Object file list
22780 -- BEGIN Object file/option list
22781    --   ./hello.o
22782    --   -L./
22783    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22784    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22785 -- END Object file/option list
22787 @b{end} ada_main;
22788 @end smallexample
22790 @noindent
22791 The Ada code in the above example is exactly what is generated by the
22792 binder. We have added comments to more clearly indicate the function
22793 of each part of the generated @code{Ada_Main} package.
22795 The code is standard Ada in all respects, and can be processed by any
22796 tools that handle Ada. In particular, it is possible to use the debugger
22797 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22798 suppose that for reasons that you do not understand, your program is crashing
22799 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22800 you can place a breakpoint on the call:
22802 @smallexample @c ada
22803 Ada.Text_Io'Elab_Body;
22804 @end smallexample
22806 @noindent
22807 and trace the elaboration routine for this package to find out where
22808 the problem might be (more usually of course you would be debugging
22809 elaboration code in your own application).
22811 @node Elaboration Order Handling in GNAT
22812 @appendix Elaboration Order Handling in GNAT
22813 @cindex Order of elaboration
22814 @cindex Elaboration control
22816 @menu
22817 * Elaboration Code::
22818 * Checking the Elaboration Order::
22819 * Controlling the Elaboration Order::
22820 * Controlling Elaboration in GNAT - Internal Calls::
22821 * Controlling Elaboration in GNAT - External Calls::
22822 * Default Behavior in GNAT - Ensuring Safety::
22823 * Treatment of Pragma Elaborate::
22824 * Elaboration Issues for Library Tasks::
22825 * Mixing Elaboration Models::
22826 * What to Do If the Default Elaboration Behavior Fails::
22827 * Elaboration for Indirect Calls::
22828 * Summary of Procedures for Elaboration Control::
22829 * Other Elaboration Order Considerations::
22830 * Determining the Chosen Elaboration Order::
22831 @end menu
22833 @noindent
22834 This chapter describes the handling of elaboration code in Ada and
22835 in GNAT, and discusses how the order of elaboration of program units can
22836 be controlled in GNAT, either automatically or with explicit programming
22837 features.
22839 @node Elaboration Code
22840 @section Elaboration Code
22842 @noindent
22843 Ada provides rather general mechanisms for executing code at elaboration
22844 time, that is to say before the main program starts executing. Such code arises
22845 in three contexts:
22847 @table @asis
22848 @item Initializers for variables.
22849 Variables declared at the library level, in package specs or bodies, can
22850 require initialization that is performed at elaboration time, as in:
22851 @smallexample @c ada
22852 @cartouche
22853 Sqrt_Half : Float := Sqrt (0.5);
22854 @end cartouche
22855 @end smallexample
22857 @item Package initialization code
22858 Code in a @code{BEGIN-END} section at the outer level of a package body is
22859 executed as part of the package body elaboration code.
22861 @item Library level task allocators
22862 Tasks that are declared using task allocators at the library level
22863 start executing immediately and hence can execute at elaboration time.
22864 @end table
22866 @noindent
22867 Subprogram calls are possible in any of these contexts, which means that
22868 any arbitrary part of the program may be executed as part of the elaboration
22869 code. It is even possible to write a program which does all its work at
22870 elaboration time, with a null main program, although stylistically this
22871 would usually be considered an inappropriate way to structure
22872 a program.
22874 An important concern arises in the context of elaboration code:
22875 we have to be sure that it is executed in an appropriate order. What we
22876 have is a series of elaboration code sections, potentially one section
22877 for each unit in the program. It is important that these execute
22878 in the correct order. Correctness here means that, taking the above
22879 example of the declaration of @code{Sqrt_Half},
22880 if some other piece of
22881 elaboration code references @code{Sqrt_Half},
22882 then it must run after the
22883 section of elaboration code that contains the declaration of
22884 @code{Sqrt_Half}.
22886 There would never be any order of elaboration problem if we made a rule
22887 that whenever you @code{with} a unit, you must elaborate both the spec and body
22888 of that unit before elaborating the unit doing the @code{with}'ing:
22890 @smallexample @c ada
22891 @group
22892 @cartouche
22893 @b{with} Unit_1;
22894 @b{package} Unit_2 @b{is} @dots{}
22895 @end cartouche
22896 @end group
22897 @end smallexample
22899 @noindent
22900 would require that both the body and spec of @code{Unit_1} be elaborated
22901 before the spec of @code{Unit_2}. However, a rule like that would be far too
22902 restrictive. In particular, it would make it impossible to have routines
22903 in separate packages that were mutually recursive.
22905 You might think that a clever enough compiler could look at the actual
22906 elaboration code and determine an appropriate correct order of elaboration,
22907 but in the general case, this is not possible. Consider the following
22908 example.
22910 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22911 that references
22912 the variable @code{Sqrt_1}, which is declared in the elaboration code
22913 of the body of @code{Unit_1}:
22915 @smallexample @c ada
22916 @cartouche
22917 Sqrt_1 : Float := Sqrt (0.1);
22918 @end cartouche
22919 @end smallexample
22921 @noindent
22922 The elaboration code of the body of @code{Unit_1} also contains:
22924 @smallexample @c ada
22925 @group
22926 @cartouche
22927 @b{if} expression_1 = 1 @b{then}
22928    Q := Unit_2.Func_2;
22929 @b{end} @b{if};
22930 @end cartouche
22931 @end group
22932 @end smallexample
22934 @noindent
22935 @code{Unit_2} is exactly parallel,
22936 it has a procedure @code{Func_2} that references
22937 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22938 the body @code{Unit_2}:
22940 @smallexample @c ada
22941 @cartouche
22942 Sqrt_2 : Float := Sqrt (0.1);
22943 @end cartouche
22944 @end smallexample
22946 @noindent
22947 The elaboration code of the body of @code{Unit_2} also contains:
22949 @smallexample @c ada
22950 @group
22951 @cartouche
22952 @b{if} expression_2 = 2 @b{then}
22953    Q := Unit_1.Func_1;
22954 @b{end} @b{if};
22955 @end cartouche
22956 @end group
22957 @end smallexample
22959 @noindent
22960 Now the question is, which of the following orders of elaboration is
22961 acceptable:
22963 @smallexample
22964 @group
22965 Spec of Unit_1
22966 Spec of Unit_2
22967 Body of Unit_1
22968 Body of Unit_2
22969 @end group
22970 @end smallexample
22972 @noindent
22975 @smallexample
22976 @group
22977 Spec of Unit_2
22978 Spec of Unit_1
22979 Body of Unit_2
22980 Body of Unit_1
22981 @end group
22982 @end smallexample
22984 @noindent
22985 If you carefully analyze the flow here, you will see that you cannot tell
22986 at compile time the answer to this question.
22987 If @code{expression_1} is not equal to 1,
22988 and @code{expression_2} is not equal to 2,
22989 then either order is acceptable, because neither of the function calls is
22990 executed. If both tests evaluate to true, then neither order is acceptable
22991 and in fact there is no correct order.
22993 If one of the two expressions is true, and the other is false, then one
22994 of the above orders is correct, and the other is incorrect. For example,
22995 if @code{expression_1} /= 1 and @code{expression_2} = 2,
22996 then the call to @code{Func_1}
22997 will occur, but not the call to @code{Func_2.}
22998 This means that it is essential
22999 to elaborate the body of @code{Unit_1} before
23000 the body of @code{Unit_2}, so the first
23001 order of elaboration is correct and the second is wrong.
23003 By making @code{expression_1} and @code{expression_2}
23004 depend on input data, or perhaps
23005 the time of day, we can make it impossible for the compiler or binder
23006 to figure out which of these expressions will be true, and hence it
23007 is impossible to guarantee a safe order of elaboration at run time.
23009 @node Checking the Elaboration Order
23010 @section Checking the Elaboration Order
23012 @noindent
23013 In some languages that involve the same kind of elaboration problems,
23014 e.g.@: Java and C++, the programmer is expected to worry about these
23015 ordering problems himself, and it is common to
23016 write a program in which an incorrect elaboration order  gives
23017 surprising results, because it references variables before they
23018 are initialized.
23019 Ada is designed to be a safe language, and a programmer-beware approach is
23020 clearly not sufficient. Consequently, the language provides three lines
23021 of defense:
23023 @table @asis
23024 @item Standard rules
23025 Some standard rules restrict the possible choice of elaboration
23026 order. In particular, if you @code{with} a unit, then its spec is always
23027 elaborated before the unit doing the @code{with}. Similarly, a parent
23028 spec is always elaborated before the child spec, and finally
23029 a spec is always elaborated before its corresponding body.
23031 @item Dynamic elaboration checks
23032 @cindex Elaboration checks
23033 @cindex Checks, elaboration
23034 Dynamic checks are made at run time, so that if some entity is accessed
23035 before it is elaborated (typically  by means of a subprogram call)
23036 then the exception (@code{Program_Error}) is raised.
23038 @item Elaboration control
23039 Facilities are provided for the programmer to specify the desired order
23040 of elaboration.
23041 @end table
23043 Let's look at these facilities in more detail. First, the rules for
23044 dynamic checking. One possible rule would be simply to say that the
23045 exception is raised if you access a variable which has not yet been
23046 elaborated. The trouble with this approach is that it could require
23047 expensive checks on every variable reference. Instead Ada has two
23048 rules which are a little more restrictive, but easier to check, and
23049 easier to state:
23051 @table @asis
23052 @item Restrictions on calls
23053 A subprogram can only be called at elaboration time if its body
23054 has been elaborated. The rules for elaboration given above guarantee
23055 that the spec of the subprogram has been elaborated before the
23056 call, but not the body. If this rule is violated, then the
23057 exception @code{Program_Error} is raised.
23059 @item Restrictions on instantiations
23060 A generic unit can only be instantiated if the body of the generic
23061 unit has been elaborated. Again, the rules for elaboration given above
23062 guarantee that the spec of the generic unit has been elaborated
23063 before the instantiation, but not the body. If this rule is
23064 violated, then the exception @code{Program_Error} is raised.
23065 @end table
23067 @noindent
23068 The idea is that if the body has been elaborated, then any variables
23069 it references must have been elaborated; by checking for the body being
23070 elaborated we guarantee that none of its references causes any
23071 trouble. As we noted above, this is a little too restrictive, because a
23072 subprogram that has no non-local references in its body may in fact be safe
23073 to call. However, it really would be unsafe to rely on this, because
23074 it would mean that the caller was aware of details of the implementation
23075 in the body. This goes against the basic tenets of Ada.
23077 A plausible implementation can be described as follows.
23078 A Boolean variable is associated with each subprogram
23079 and each generic unit. This variable is initialized to False, and is set to
23080 True at the point body is elaborated. Every call or instantiation checks the
23081 variable, and raises @code{Program_Error} if the variable is False.
23083 Note that one might think that it would be good enough to have one Boolean
23084 variable for each package, but that would not deal with cases of trying
23085 to call a body in the same package as the call
23086 that has not been elaborated yet.
23087 Of course a compiler may be able to do enough analysis to optimize away
23088 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23089 does such optimizations, but still the easiest conceptual model is to
23090 think of there being one variable per subprogram.
23092 @node Controlling the Elaboration Order
23093 @section Controlling the Elaboration Order
23095 @noindent
23096 In the previous section we discussed the rules in Ada which ensure
23097 that @code{Program_Error} is raised if an incorrect elaboration order is
23098 chosen. This prevents erroneous executions, but we need mechanisms to
23099 specify a correct execution and avoid the exception altogether.
23100 To achieve this, Ada provides a number of features for controlling
23101 the order of elaboration. We discuss these features in this section.
23103 First, there are several ways of indicating to the compiler that a given
23104 unit has no elaboration problems:
23106 @table @asis
23107 @item packages that do not require a body
23108 A library package that does not require a body does not permit
23109 a body (this rule was introduced in Ada 95).
23110 Thus if we have a such a package, as in:
23112 @smallexample @c ada
23113 @group
23114 @cartouche
23115 @b{package} Definitions @b{is}
23116    @b{generic}
23117       @b{type} m @b{is} @b{new} integer;
23118    @b{package} Subp @b{is}
23119       @b{type} a @b{is} @b{array} (1 .. 10) @b{of} m;
23120       @b{type} b @b{is} @b{array} (1 .. 20) @b{of} m;
23121    @b{end} Subp;
23122 @b{end} Definitions;
23123 @end cartouche
23124 @end group
23125 @end smallexample
23127 @noindent
23128 A package that @code{with}'s @code{Definitions} may safely instantiate
23129 @code{Definitions.Subp} because the compiler can determine that there
23130 definitely is no package body to worry about in this case
23132 @item pragma Pure
23133 @cindex pragma Pure
23134 @findex Pure
23135 Places sufficient restrictions on a unit to guarantee that
23136 no call to any subprogram in the unit can result in an
23137 elaboration problem. This means that the compiler does not need
23138 to worry about the point of elaboration of such units, and in
23139 particular, does not need to check any calls to any subprograms
23140 in this unit.
23142 @item pragma Preelaborate
23143 @findex Preelaborate
23144 @cindex pragma Preelaborate
23145 This pragma places slightly less stringent restrictions on a unit than
23146 does pragma Pure,
23147 but these restrictions are still sufficient to ensure that there
23148 are no elaboration problems with any calls to the unit.
23150 @item pragma Elaborate_Body
23151 @findex Elaborate_Body
23152 @cindex pragma Elaborate_Body
23153 This pragma requires that the body of a unit be elaborated immediately
23154 after its spec. Suppose a unit @code{A} has such a pragma,
23155 and unit @code{B} does
23156 a @code{with} of unit @code{A}. Recall that the standard rules require
23157 the spec of unit @code{A}
23158 to be elaborated before the @code{with}'ing unit; given the pragma in
23159 @code{A}, we also know that the body of @code{A}
23160 will be elaborated before @code{B}, so
23161 that calls to @code{A} are safe and do not need a check.
23162 @end table
23164 @noindent
23165 Note that,
23166 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23167 the use of
23168 @code{Elaborate_Body} does not guarantee that the program is
23169 free of elaboration problems, because it may not be possible
23170 to satisfy the requested elaboration order.
23171 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23172 If a programmer
23173 marks @code{Unit_1} as @code{Elaborate_Body},
23174 and not @code{Unit_2,} then the order of
23175 elaboration will be:
23177 @smallexample
23178 @group
23179 Spec of Unit_2
23180 Spec of Unit_1
23181 Body of Unit_1
23182 Body of Unit_2
23183 @end group
23184 @end smallexample
23186 @noindent
23187 Now that means that the call to @code{Func_1} in @code{Unit_2}
23188 need not be checked,
23189 it must be safe. But the call to @code{Func_2} in
23190 @code{Unit_1} may still fail if
23191 @code{Expression_1} is equal to 1,
23192 and the programmer must still take
23193 responsibility for this not being the case.
23195 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23196 eliminated, except for calls entirely within a body, which are
23197 in any case fully under programmer control. However, using the pragma
23198 everywhere is not always possible.
23199 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23200 we marked both of them as having pragma @code{Elaborate_Body}, then
23201 clearly there would be no possible elaboration order.
23203 The above pragmas allow a server to guarantee safe use by clients, and
23204 clearly this is the preferable approach. Consequently a good rule
23205 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23206 and if this is not possible,
23207 mark them as @code{Elaborate_Body} if possible.
23208 As we have seen, there are situations where neither of these
23209 three pragmas can be used.
23210 So we also provide methods for clients to control the
23211 order of elaboration of the servers on which they depend:
23213 @table @asis
23214 @item pragma Elaborate (unit)
23215 @findex Elaborate
23216 @cindex pragma Elaborate
23217 This pragma is placed in the context clause, after a @code{with} clause,
23218 and it requires that the body of the named unit be elaborated before
23219 the unit in which the pragma occurs. The idea is to use this pragma
23220 if the current unit calls at elaboration time, directly or indirectly,
23221 some subprogram in the named unit.
23223 @item pragma Elaborate_All (unit)
23224 @findex Elaborate_All
23225 @cindex pragma Elaborate_All
23226 This is a stronger version of the Elaborate pragma. Consider the
23227 following example:
23229 @smallexample
23230 Unit A @code{with}'s unit B and calls B.Func in elab code
23231 Unit B @code{with}'s unit C, and B.Func calls C.Func
23232 @end smallexample
23234 @noindent
23235 Now if we put a pragma @code{Elaborate (B)}
23236 in unit @code{A}, this ensures that the
23237 body of @code{B} is elaborated before the call, but not the
23238 body of @code{C}, so
23239 the call to @code{C.Func} could still cause @code{Program_Error} to
23240 be raised.
23242 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23243 not only that the body of the named unit be elaborated before the
23244 unit doing the @code{with}, but also the bodies of all units that the
23245 named unit uses, following @code{with} links transitively. For example,
23246 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23247 then it requires
23248 not only that the body of @code{B} be elaborated before @code{A},
23249 but also the
23250 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23251 @end table
23253 @noindent
23254 We are now in a position to give a usage rule in Ada for avoiding
23255 elaboration problems, at least if dynamic dispatching and access to
23256 subprogram values are not used. We will handle these cases separately
23257 later.
23259 The rule is simple. If a unit has elaboration code that can directly or
23260 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23261 a generic package in a @code{with}'ed unit,
23262 then if the @code{with}'ed unit does not have
23263 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23264 a pragma @code{Elaborate_All}
23265 for the @code{with}'ed unit. By following this rule a client is
23266 assured that calls can be made without risk of an exception.
23268 For generic subprogram instantiations, the rule can be relaxed to
23269 require only a pragma @code{Elaborate} since elaborating the body
23270 of a subprogram cannot cause any transitive elaboration (we are
23271 not calling the subprogram in this case, just elaborating its
23272 declaration).
23274 If this rule is not followed, then a program may be in one of four
23275 states:
23277 @table @asis
23278 @item No order exists
23279 No order of elaboration exists which follows the rules, taking into
23280 account any @code{Elaborate}, @code{Elaborate_All},
23281 or @code{Elaborate_Body} pragmas. In
23282 this case, an Ada compiler must diagnose the situation at bind
23283 time, and refuse to build an executable program.
23285 @item One or more orders exist, all incorrect
23286 One or more acceptable elaboration orders exist, and all of them
23287 generate an elaboration order problem. In this case, the binder
23288 can build an executable program, but @code{Program_Error} will be raised
23289 when the program is run.
23291 @item Several orders exist, some right, some incorrect
23292 One or more acceptable elaboration orders exists, and some of them
23293 work, and some do not. The programmer has not controlled
23294 the order of elaboration, so the binder may or may not pick one of
23295 the correct orders, and the program may or may not raise an
23296 exception when it is run. This is the worst case, because it means
23297 that the program may fail when moved to another compiler, or even
23298 another version of the same compiler.
23300 @item One or more orders exists, all correct
23301 One ore more acceptable elaboration orders exist, and all of them
23302 work. In this case the program runs successfully. This state of
23303 affairs can be guaranteed by following the rule we gave above, but
23304 may be true even if the rule is not followed.
23305 @end table
23307 @noindent
23308 Note that one additional advantage of following our rules on the use
23309 of @code{Elaborate} and @code{Elaborate_All}
23310 is that the program continues to stay in the ideal (all orders OK) state
23311 even if maintenance
23312 changes some bodies of some units. Conversely, if a program that does
23313 not follow this rule happens to be safe at some point, this state of affairs
23314 may deteriorate silently as a result of maintenance changes.
23316 You may have noticed that the above discussion did not mention
23317 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23318 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23319 code in the body makes calls to some other unit, so it is still necessary
23320 to use @code{Elaborate_All} on such units.
23322 @node Controlling Elaboration in GNAT - Internal Calls
23323 @section Controlling Elaboration in GNAT - Internal Calls
23325 @noindent
23326 In the case of internal calls, i.e., calls within a single package, the
23327 programmer has full control over the order of elaboration, and it is up
23328 to the programmer to elaborate declarations in an appropriate order. For
23329 example writing:
23331 @smallexample @c ada
23332 @group
23333 @cartouche
23334 @b{function} One @b{return} Float;
23336 Q : Float := One;
23338 @b{function} One @b{return} Float @b{is}
23339 @b{begin}
23340      @b{return} 1.0;
23341 @b{end} One;
23342 @end cartouche
23343 @end group
23344 @end smallexample
23346 @noindent
23347 will obviously raise @code{Program_Error} at run time, because function
23348 One will be called before its body is elaborated. In this case GNAT will
23349 generate a warning that the call will raise @code{Program_Error}:
23351 @smallexample
23352 @group
23353 @cartouche
23354  1. procedure y is
23355  2.    function One return Float;
23356  3.
23357  4.    Q : Float := One;
23358                     |
23359     >>> warning: cannot call "One" before body is elaborated
23360     >>> warning: Program_Error will be raised at run time
23362  5.
23363  6.    function One return Float is
23364  7.    begin
23365  8.         return 1.0;
23366  9.    end One;
23368 11. begin
23369 12.    null;
23370 13. end;
23371 @end cartouche
23372 @end group
23373 @end smallexample
23375 @noindent
23376 Note that in this particular case, it is likely that the call is safe, because
23377 the function @code{One} does not access any global variables.
23378 Nevertheless in Ada, we do not want the validity of the check to depend on
23379 the contents of the body (think about the separate compilation case), so this
23380 is still wrong, as we discussed in the previous sections.
23382 The error is easily corrected by rearranging the declarations so that the
23383 body of @code{One} appears before the declaration containing the call
23384 (note that in Ada 95 and Ada 2005,
23385 declarations can appear in any order, so there is no restriction that
23386 would prevent this reordering, and if we write:
23388 @smallexample @c ada
23389 @group
23390 @cartouche
23391 @b{function} One @b{return} Float;
23393 @b{function} One @b{return} Float @b{is}
23394 @b{begin}
23395      @b{return} 1.0;
23396 @b{end} One;
23398 Q : Float := One;
23399 @end cartouche
23400 @end group
23401 @end smallexample
23403 @noindent
23404 then all is well, no warning is generated, and no
23405 @code{Program_Error} exception
23406 will be raised.
23407 Things are more complicated when a chain of subprograms is executed:
23409 @smallexample @c ada
23410 @group
23411 @cartouche
23412 @b{function} A @b{return} Integer;
23413 @b{function} B @b{return} Integer;
23414 @b{function} C @b{return} Integer;
23416 @b{function} B @b{return} Integer @b{is} @b{begin} @b{return} A; @b{end};
23417 @b{function} C @b{return} Integer @b{is} @b{begin} @b{return} B; @b{end};
23419 X : Integer := C;
23421 @b{function} A @b{return} Integer @b{is} @b{begin} @b{return} 1; @b{end};
23422 @end cartouche
23423 @end group
23424 @end smallexample
23426 @noindent
23427 Now the call to @code{C}
23428 at elaboration time in the declaration of @code{X} is correct, because
23429 the body of @code{C} is already elaborated,
23430 and the call to @code{B} within the body of
23431 @code{C} is correct, but the call
23432 to @code{A} within the body of @code{B} is incorrect, because the body
23433 of @code{A} has not been elaborated, so @code{Program_Error}
23434 will be raised on the call to @code{A}.
23435 In this case GNAT will generate a
23436 warning that @code{Program_Error} may be
23437 raised at the point of the call. Let's look at the warning:
23439 @smallexample
23440 @group
23441 @cartouche
23442  1. procedure x is
23443  2.    function A return Integer;
23444  3.    function B return Integer;
23445  4.    function C return Integer;
23446  5.
23447  6.    function B return Integer is begin return A; end;
23448                                                     |
23449     >>> warning: call to "A" before body is elaborated may
23450                  raise Program_Error
23451     >>> warning: "B" called at line 7
23452     >>> warning: "C" called at line 9
23454  7.    function C return Integer is begin return B; end;
23455  8.
23456  9.    X : Integer := C;
23458 11.    function A return Integer is begin return 1; end;
23460 13. begin
23461 14.    null;
23462 15. end;
23463 @end cartouche
23464 @end group
23465 @end smallexample
23467 @noindent
23468 Note that the message here says ``may raise'', instead of the direct case,
23469 where the message says ``will be raised''. That's because whether
23470 @code{A} is
23471 actually called depends in general on run-time flow of control.
23472 For example, if the body of @code{B} said
23474 @smallexample @c ada
23475 @group
23476 @cartouche
23477 @b{function} B @b{return} Integer @b{is}
23478 @b{begin}
23479    @b{if} some-condition-depending-on-input-data @b{then}
23480       @b{return} A;
23481    @b{else}
23482       @b{return} 1;
23483    @b{end} @b{if};
23484 @b{end} B;
23485 @end cartouche
23486 @end group
23487 @end smallexample
23489 @noindent
23490 then we could not know until run time whether the incorrect call to A would
23491 actually occur, so @code{Program_Error} might
23492 or might not be raised. It is possible for a compiler to
23493 do a better job of analyzing bodies, to
23494 determine whether or not @code{Program_Error}
23495 might be raised, but it certainly
23496 couldn't do a perfect job (that would require solving the halting problem
23497 and is provably impossible), and because this is a warning anyway, it does
23498 not seem worth the effort to do the analysis. Cases in which it
23499 would be relevant are rare.
23501 In practice, warnings of either of the forms given
23502 above will usually correspond to
23503 real errors, and should be examined carefully and eliminated.
23504 In the rare case where a warning is bogus, it can be suppressed by any of
23505 the following methods:
23507 @itemize @bullet
23508 @item
23509 Compile with the @option{-gnatws} switch set
23511 @item
23512 Suppress @code{Elaboration_Check} for the called subprogram
23514 @item
23515 Use pragma @code{Warnings_Off} to turn warnings off for the call
23516 @end itemize
23518 @noindent
23519 For the internal elaboration check case,
23520 GNAT by default generates the
23521 necessary run-time checks to ensure
23522 that @code{Program_Error} is raised if any
23523 call fails an elaboration check. Of course this can only happen if a
23524 warning has been issued as described above. The use of pragma
23525 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23526 some of these checks, meaning that it may be possible (but is not
23527 guaranteed) for a program to be able to call a subprogram whose body
23528 is not yet elaborated, without raising a @code{Program_Error} exception.
23530 @node Controlling Elaboration in GNAT - External Calls
23531 @section Controlling Elaboration in GNAT - External Calls
23533 @noindent
23534 The previous section discussed the case in which the execution of a
23535 particular thread of elaboration code occurred entirely within a
23536 single unit. This is the easy case to handle, because a programmer
23537 has direct and total control over the order of elaboration, and
23538 furthermore, checks need only be generated in cases which are rare
23539 and which the compiler can easily detect.
23540 The situation is more complex when separate compilation is taken into account.
23541 Consider the following:
23543 @smallexample @c ada
23544 @cartouche
23545 @group
23546 @b{package} Math @b{is}
23547    @b{function} Sqrt (Arg : Float) @b{return} Float;
23548 @b{end} Math;
23550 @b{package} @b{body} Math @b{is}
23551    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
23552    @b{begin}
23553          @dots{}
23554    @b{end} Sqrt;
23555 @b{end} Math;
23556 @end group
23557 @group
23558 @b{with} Math;
23559 @b{package} Stuff @b{is}
23560    X : Float := Math.Sqrt (0.5);
23561 @b{end} Stuff;
23563 @b{with} Stuff;
23564 @b{procedure} Main @b{is}
23565 @b{begin}
23566    @dots{}
23567 @b{end} Main;
23568 @end group
23569 @end cartouche
23570 @end smallexample
23572 @noindent
23573 where @code{Main} is the main program. When this program is executed, the
23574 elaboration code must first be executed, and one of the jobs of the
23575 binder is to determine the order in which the units of a program are
23576 to be elaborated. In this case we have four units: the spec and body
23577 of @code{Math},
23578 the spec of @code{Stuff} and the body of @code{Main}).
23579 In what order should the four separate sections of elaboration code
23580 be executed?
23582 There are some restrictions in the order of elaboration that the binder
23583 can choose. In particular, if unit U has a @code{with}
23584 for a package @code{X}, then you
23585 are assured that the spec of @code{X}
23586 is elaborated before U , but you are
23587 not assured that the body of @code{X}
23588 is elaborated before U.
23589 This means that in the above case, the binder is allowed to choose the
23590 order:
23592 @smallexample
23593 spec of Math
23594 spec of Stuff
23595 body of Math
23596 body of Main
23597 @end smallexample
23599 @noindent
23600 but that's not good, because now the call to @code{Math.Sqrt}
23601 that happens during
23602 the elaboration of the @code{Stuff}
23603 spec happens before the body of @code{Math.Sqrt} is
23604 elaborated, and hence causes @code{Program_Error} exception to be raised.
23605 At first glance, one might say that the binder is misbehaving, because
23606 obviously you want to elaborate the body of something you @code{with}
23607 first, but
23608 that is not a general rule that can be followed in all cases. Consider
23610 @smallexample @c ada
23611 @group
23612 @cartouche
23613 @b{package} X @b{is} @dots{}
23615 @b{package} Y @b{is} @dots{}
23617 @b{with} X;
23618 @b{package} @b{body} Y @b{is} @dots{}
23620 @b{with} Y;
23621 @b{package} @b{body} X @b{is} @dots{}
23622 @end cartouche
23623 @end group
23624 @end smallexample
23626 @noindent
23627 This is a common arrangement, and, apart from the order of elaboration
23628 problems that might arise in connection with elaboration code, this works fine.
23629 A rule that says that you must first elaborate the body of anything you
23630 @code{with} cannot work in this case:
23631 the body of @code{X} @code{with}'s @code{Y},
23632 which means you would have to
23633 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23634 which means
23635 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23636 loop that cannot be broken.
23638 It is true that the binder can in many cases guess an order of elaboration
23639 that is unlikely to cause a @code{Program_Error}
23640 exception to be raised, and it tries to do so (in the
23641 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23642 by default
23643 elaborate the body of @code{Math} right after its spec, so all will be well).
23645 However, a program that blindly relies on the binder to be helpful can
23646 get into trouble, as we discussed in the previous sections, so
23647 GNAT
23648 provides a number of facilities for assisting the programmer in
23649 developing programs that are robust with respect to elaboration order.
23651 @node Default Behavior in GNAT - Ensuring Safety
23652 @section Default Behavior in GNAT - Ensuring Safety
23654 @noindent
23655 The default behavior in GNAT ensures elaboration safety. In its
23656 default mode GNAT implements the
23657 rule we previously described as the right approach. Let's restate it:
23659 @itemize
23660 @item
23661 @emph{If a unit has elaboration code that can directly or indirectly make a
23662 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23663 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23664 does not have pragma @code{Pure} or
23665 @code{Preelaborate}, then the client should have an
23666 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23668 @emph{In the case of instantiating a generic subprogram, it is always
23669 sufficient to have only an @code{Elaborate} pragma for the
23670 @code{with}'ed unit.}
23671 @end itemize
23673 @noindent
23674 By following this rule a client is assured that calls and instantiations
23675 can be made without risk of an exception.
23677 In this mode GNAT traces all calls that are potentially made from
23678 elaboration code, and puts in any missing implicit @code{Elaborate}
23679 and @code{Elaborate_All} pragmas.
23680 The advantage of this approach is that no elaboration problems
23681 are possible if the binder can find an elaboration order that is
23682 consistent with these implicit @code{Elaborate} and
23683 @code{Elaborate_All} pragmas. The
23684 disadvantage of this approach is that no such order may exist.
23686 If the binder does not generate any diagnostics, then it means that it has
23687 found an elaboration order that is guaranteed to be safe. However, the binder
23688 may still be relying on implicitly generated @code{Elaborate} and
23689 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23690 guaranteed.
23692 If it is important to guarantee portability, then the compilations should
23693 use the
23694 @option{-gnatel}
23695 (info messages for elaboration prag mas) switch. This will cause info messages
23696 to be generated indicating the missing @code{Elaborate} and
23697 @code{Elaborate_All} pragmas.
23698 Consider the following source program:
23700 @smallexample @c ada
23701 @group
23702 @cartouche
23703 @b{with} k;
23704 @b{package} j @b{is}
23705   m : integer := k.r;
23706 @b{end};
23707 @end cartouche
23708 @end group
23709 @end smallexample
23711 @noindent
23712 where it is clear that there
23713 should be a pragma @code{Elaborate_All}
23714 for unit @code{k}. An implicit pragma will be generated, and it is
23715 likely that the binder will be able to honor it. However, if you want
23716 to port this program to some other Ada compiler than GNAT.
23717 it is safer to include the pragma explicitly in the source. If this
23718 unit is compiled with the
23719 @option{-gnatel}
23720 switch, then the compiler outputs an information message:
23722 @smallexample
23723 @group
23724 @cartouche
23725 1. with k;
23726 2. package j is
23727 3.   m : integer := k.r;
23728                      |
23729    >>> info: call to "r" may raise Program_Error
23730    >>> info: missing pragma Elaborate_All for "k"
23732 4. end;
23733 @end cartouche
23734 @end group
23735 @end smallexample
23737 @noindent
23738 and these messages can be used as a guide for supplying manually
23739 the missing pragmas. It is usually a bad idea to use this
23740 option during development. That's because it will tell you when
23741 you need to put in a pragma, but cannot tell you when it is time
23742 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23743 unnecessary dependencies and even false circularities.
23745 This default mode is more restrictive than the Ada Reference
23746 Manual, and it is possible to construct programs which will compile
23747 using the dynamic model described there, but will run into a
23748 circularity using the safer static model we have described.
23750 Of course any Ada compiler must be able to operate in a mode
23751 consistent with the requirements of the Ada Reference Manual,
23752 and in particular must have the capability of implementing the
23753 standard dynamic model of elaboration with run-time checks.
23755 In GNAT, this standard mode can be achieved either by the use of
23756 the @option{-gnatE} switch on the compiler (@command{gcc} or
23757 @command{gnatmake}) command, or by the use of the configuration pragma:
23759 @smallexample @c ada
23760 @b{pragma} Elaboration_Checks (DYNAMIC);
23761 @end smallexample
23763 @noindent
23764 Either approach will cause the unit affected to be compiled using the
23765 standard dynamic run-time elaboration checks described in the Ada
23766 Reference Manual. The static model is generally preferable, since it
23767 is clearly safer to rely on compile and link time checks rather than
23768 run-time checks. However, in the case of legacy code, it may be
23769 difficult to meet the requirements of the static model. This
23770 issue is further discussed in
23771 @ref{What to Do If the Default Elaboration Behavior Fails}.
23773 Note that the static model provides a strict subset of the allowed
23774 behavior and programs of the Ada Reference Manual, so if you do
23775 adhere to the static model and no circularities exist,
23776 then you are assured that your program will
23777 work using the dynamic model, providing that you remove any
23778 pragma Elaborate statements from the source.
23780 @node Treatment of Pragma Elaborate
23781 @section Treatment of Pragma Elaborate
23782 @cindex Pragma Elaborate
23784 @noindent
23785 The use of @code{pragma Elaborate}
23786 should generally be avoided in Ada 95 and Ada 2005 programs,
23787 since there is no guarantee that transitive calls
23788 will be properly handled. Indeed at one point, this pragma was placed
23789 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23791 Now that's a bit restrictive. In practice, the case in which
23792 @code{pragma Elaborate} is useful is when the caller knows that there
23793 are no transitive calls, or that the called unit contains all necessary
23794 transitive @code{pragma Elaborate} statements, and legacy code often
23795 contains such uses.
23797 Strictly speaking the static mode in GNAT should ignore such pragmas,
23798 since there is no assurance at compile time that the necessary safety
23799 conditions are met. In practice, this would cause GNAT to be incompatible
23800 with correctly written Ada 83 code that had all necessary
23801 @code{pragma Elaborate} statements in place. Consequently, we made the
23802 decision that GNAT in its default mode will believe that if it encounters
23803 a @code{pragma Elaborate} then the programmer knows what they are doing,
23804 and it will trust that no elaboration errors can occur.
23806 The result of this decision is two-fold. First to be safe using the
23807 static mode, you should remove all @code{pragma Elaborate} statements.
23808 Second, when fixing circularities in existing code, you can selectively
23809 use @code{pragma Elaborate} statements to convince the static mode of
23810 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23811 statement.
23813 When using the static mode with @option{-gnatwl}, any use of
23814 @code{pragma Elaborate} will generate a warning about possible
23815 problems.
23817 @node Elaboration Issues for Library Tasks
23818 @section Elaboration Issues for Library Tasks
23819 @cindex Library tasks, elaboration issues
23820 @cindex Elaboration of library tasks
23822 @noindent
23823 In this section we examine special elaboration issues that arise for
23824 programs that declare library level tasks.
23826 Generally the model of execution of an Ada program is that all units are
23827 elaborated, and then execution of the program starts. However, the
23828 declaration of library tasks definitely does not fit this model. The
23829 reason for this is that library tasks start as soon as they are declared
23830 (more precisely, as soon as the statement part of the enclosing package
23831 body is reached), that is to say before elaboration
23832 of the program is complete. This means that if such a task calls a
23833 subprogram, or an entry in another task, the callee may or may not be
23834 elaborated yet, and in the standard
23835 Reference Manual model of dynamic elaboration checks, you can even
23836 get timing dependent Program_Error exceptions, since there can be
23837 a race between the elaboration code and the task code.
23839 The static model of elaboration in GNAT seeks to avoid all such
23840 dynamic behavior, by being conservative, and the conservative
23841 approach in this particular case is to assume that all the code
23842 in a task body is potentially executed at elaboration time if
23843 a task is declared at the library level.
23845 This can definitely result in unexpected circularities. Consider
23846 the following example
23848 @smallexample @c ada
23849 @b{package} Decls @b{is}
23850   @b{task} Lib_Task @b{is}
23851      @b{entry} Start;
23852   @b{end} Lib_Task;
23854   @b{type} My_Int @b{is} @b{new} Integer;
23856   @b{function} Ident (M : My_Int) @b{return} My_Int;
23857 @b{end} Decls;
23859 @b{with} Utils;
23860 @b{package} @b{body} Decls @b{is}
23861   @b{task} @b{body} Lib_Task @b{is}
23862   @b{begin}
23863      @b{accept} Start;
23864      Utils.Put_Val (2);
23865   @b{end} Lib_Task;
23867   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
23868   @b{begin}
23869      @b{return} M;
23870   @b{end} Ident;
23871 @b{end} Decls;
23873 @b{with} Decls;
23874 @b{package} Utils @b{is}
23875   @b{procedure} Put_Val (Arg : Decls.My_Int);
23876 @b{end} Utils;
23878 @b{with} Text_IO;
23879 @b{package} @b{body} Utils @b{is}
23880   @b{procedure} Put_Val (Arg : Decls.My_Int) @b{is}
23881   @b{begin}
23882      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23883   @b{end} Put_Val;
23884 @b{end} Utils;
23886 @b{with} Decls;
23887 @b{procedure} Main @b{is}
23888 @b{begin}
23889    Decls.Lib_Task.Start;
23890 @b{end};
23891 @end smallexample
23893 @noindent
23894 If the above example is compiled in the default static elaboration
23895 mode, then a circularity occurs. The circularity comes from the call
23896 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23897 this call occurs in elaboration code, we need an implicit pragma
23898 @code{Elaborate_All} for @code{Utils}. This means that not only must
23899 the spec and body of @code{Utils} be elaborated before the body
23900 of @code{Decls}, but also the spec and body of any unit that is
23901 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23902 the body of @code{Decls}. This is the transitive implication of
23903 pragma @code{Elaborate_All} and it makes sense, because in general
23904 the body of @code{Put_Val} might have a call to something in a
23905 @code{with'ed} unit.
23907 In this case, the body of Utils (actually its spec) @code{with's}
23908 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23909 must be elaborated before itself, in case there is a call from the
23910 body of @code{Utils}.
23912 Here is the exact chain of events we are worrying about:
23914 @enumerate
23915 @item
23916 In the body of @code{Decls} a call is made from within the body of a library
23917 task to a subprogram in the package @code{Utils}. Since this call may
23918 occur at elaboration time (given that the task is activated at elaboration
23919 time), we have to assume the worst, i.e., that the
23920 call does happen at elaboration time.
23922 @item
23923 This means that the body and spec of @code{Util} must be elaborated before
23924 the body of @code{Decls} so that this call does not cause an access before
23925 elaboration.
23927 @item
23928 Within the body of @code{Util}, specifically within the body of
23929 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23930 by this package.
23932 @item
23933 One such @code{with}'ed package is package @code{Decls}, so there
23934 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23935 In fact there is such a call in this example, but we would have to
23936 assume that there was such a call even if it were not there, since
23937 we are not supposed to write the body of @code{Decls} knowing what
23938 is in the body of @code{Utils}; certainly in the case of the
23939 static elaboration model, the compiler does not know what is in
23940 other bodies and must assume the worst.
23942 @item
23943 This means that the spec and body of @code{Decls} must also be
23944 elaborated before we elaborate the unit containing the call, but
23945 that unit is @code{Decls}! This means that the body of @code{Decls}
23946 must be elaborated before itself, and that's a circularity.
23947 @end enumerate
23949 @noindent
23950 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23951 the body of @code{Decls} you will get a true Ada Reference Manual
23952 circularity that makes the program illegal.
23954 In practice, we have found that problems with the static model of
23955 elaboration in existing code often arise from library tasks, so
23956 we must address this particular situation.
23958 Note that if we compile and run the program above, using the dynamic model of
23959 elaboration (that is to say use the @option{-gnatE} switch),
23960 then it compiles, binds,
23961 links, and runs, printing the expected result of 2. Therefore in some sense
23962 the circularity here is only apparent, and we need to capture
23963 the properties of this program that  distinguish it from other library-level
23964 tasks that have real elaboration problems.
23966 We have four possible answers to this question:
23968 @itemize @bullet
23970 @item
23971 Use the dynamic model of elaboration.
23973 If we use the @option{-gnatE} switch, then as noted above, the program works.
23974 Why is this? If we examine the task body, it is apparent that the task cannot
23975 proceed past the
23976 @code{accept} statement until after elaboration has been completed, because
23977 the corresponding entry call comes from the main program, not earlier.
23978 This is why the dynamic model works here. But that's really giving
23979 up on a precise analysis, and we prefer to take this approach only if we cannot
23980 solve the
23981 problem in any other manner. So let us examine two ways to reorganize
23982 the program to avoid the potential elaboration problem.
23984 @item
23985 Split library tasks into separate packages.
23987 Write separate packages, so that library tasks are isolated from
23988 other declarations as much as possible. Let us look at a variation on
23989 the above program.
23991 @smallexample @c ada
23992 @b{package} Decls1 @b{is}
23993   @b{task} Lib_Task @b{is}
23994      @b{entry} Start;
23995   @b{end} Lib_Task;
23996 @b{end} Decls1;
23998 @b{with} Utils;
23999 @b{package} @b{body} Decls1 @b{is}
24000   @b{task} @b{body} Lib_Task @b{is}
24001   @b{begin}
24002      @b{accept} Start;
24003      Utils.Put_Val (2);
24004   @b{end} Lib_Task;
24005 @b{end} Decls1;
24007 @b{package} Decls2 @b{is}
24008   @b{type} My_Int @b{is} @b{new} Integer;
24009   @b{function} Ident (M : My_Int) @b{return} My_Int;
24010 @b{end} Decls2;
24012 @b{with} Utils;
24013 @b{package} @b{body} Decls2 @b{is}
24014   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24015   @b{begin}
24016      @b{return} M;
24017   @b{end} Ident;
24018 @b{end} Decls2;
24020 @b{with} Decls2;
24021 @b{package} Utils @b{is}
24022   @b{procedure} Put_Val (Arg : Decls2.My_Int);
24023 @b{end} Utils;
24025 @b{with} Text_IO;
24026 @b{package} @b{body} Utils @b{is}
24027   @b{procedure} Put_Val (Arg : Decls2.My_Int) @b{is}
24028   @b{begin}
24029      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24030   @b{end} Put_Val;
24031 @b{end} Utils;
24033 @b{with} Decls1;
24034 @b{procedure} Main @b{is}
24035 @b{begin}
24036    Decls1.Lib_Task.Start;
24037 @b{end};
24038 @end smallexample
24040 @noindent
24041 All we have done is to split @code{Decls} into two packages, one
24042 containing the library task, and one containing everything else. Now
24043 there is no cycle, and the program compiles, binds, links and executes
24044 using the default static model of elaboration.
24046 @item
24047 Declare separate task types.
24049 A significant part of the problem arises because of the use of the
24050 single task declaration form. This means that the elaboration of
24051 the task type, and the elaboration of the task itself (i.e.@: the
24052 creation of the task) happen at the same time. A good rule
24053 of style in Ada is to always create explicit task types. By
24054 following the additional step of placing task objects in separate
24055 packages from the task type declaration, many elaboration problems
24056 are avoided. Here is another modified example of the example program:
24058 @smallexample @c ada
24059 @b{package} Decls @b{is}
24060   @b{task} @b{type} Lib_Task_Type @b{is}
24061      @b{entry} Start;
24062   @b{end} Lib_Task_Type;
24064   @b{type} My_Int @b{is} @b{new} Integer;
24066   @b{function} Ident (M : My_Int) @b{return} My_Int;
24067 @b{end} Decls;
24069 @b{with} Utils;
24070 @b{package} @b{body} Decls @b{is}
24071   @b{task} @b{body} Lib_Task_Type @b{is}
24072   @b{begin}
24073      @b{accept} Start;
24074      Utils.Put_Val (2);
24075   @b{end} Lib_Task_Type;
24077   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24078   @b{begin}
24079      @b{return} M;
24080   @b{end} Ident;
24081 @b{end} Decls;
24083 @b{with} Decls;
24084 @b{package} Utils @b{is}
24085   @b{procedure} Put_Val (Arg : Decls.My_Int);
24086 @b{end} Utils;
24088 @b{with} Text_IO;
24089 @b{package} @b{body} Utils @b{is}
24090   @b{procedure} Put_Val (Arg : Decls.My_Int) @b{is}
24091   @b{begin}
24092      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24093   @b{end} Put_Val;
24094 @b{end} Utils;
24096 @b{with} Decls;
24097 @b{package} Declst @b{is}
24098    Lib_Task : Decls.Lib_Task_Type;
24099 @b{end} Declst;
24101 @b{with} Declst;
24102 @b{procedure} Main @b{is}
24103 @b{begin}
24104    Declst.Lib_Task.Start;
24105 @b{end};
24106 @end smallexample
24108 @noindent
24109 What we have done here is to replace the @code{task} declaration in
24110 package @code{Decls} with a @code{task type} declaration. Then we
24111 introduce a separate package @code{Declst} to contain the actual
24112 task object. This separates the elaboration issues for
24113 the @code{task type}
24114 declaration, which causes no trouble, from the elaboration issues
24115 of the task object, which is also unproblematic, since it is now independent
24116 of the elaboration of  @code{Utils}.
24117 This separation of concerns also corresponds to
24118 a generally sound engineering principle of separating declarations
24119 from instances. This version of the program also compiles, binds, links,
24120 and executes, generating the expected output.
24122 @item
24123 Use No_Entry_Calls_In_Elaboration_Code restriction.
24124 @cindex No_Entry_Calls_In_Elaboration_Code
24126 The previous two approaches described how a program can be restructured
24127 to avoid the special problems caused by library task bodies. in practice,
24128 however, such restructuring may be difficult to apply to existing legacy code,
24129 so we must consider solutions that do not require massive rewriting.
24131 Let us consider more carefully why our original sample program works
24132 under the dynamic model of elaboration. The reason is that the code
24133 in the task body blocks immediately on the @code{accept}
24134 statement. Now of course there is nothing to prohibit elaboration
24135 code from making entry calls (for example from another library level task),
24136 so we cannot tell in isolation that
24137 the task will not execute the accept statement  during elaboration.
24139 However, in practice it is very unusual to see elaboration code
24140 make any entry calls, and the pattern of tasks starting
24141 at elaboration time and then immediately blocking on @code{accept} or
24142 @code{select} statements is very common. What this means is that
24143 the compiler is being too pessimistic when it analyzes the
24144 whole package body as though it might be executed at elaboration
24145 time.
24147 If we know that the elaboration code contains no entry calls, (a very safe
24148 assumption most of the time, that could almost be made the default
24149 behavior), then we can compile all units of the program under control
24150 of the following configuration pragma:
24152 @smallexample
24153 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24154 @end smallexample
24156 @noindent
24157 This pragma can be placed in the @file{gnat.adc} file in the usual
24158 manner. If we take our original unmodified program and compile it
24159 in the presence of a @file{gnat.adc} containing the above pragma,
24160 then once again, we can compile, bind, link, and execute, obtaining
24161 the expected result. In the presence of this pragma, the compiler does
24162 not trace calls in a task body, that appear after the first @code{accept}
24163 or @code{select} statement, and therefore does not report a potential
24164 circularity in the original program.
24166 The compiler will check to the extent it can that the above
24167 restriction is not violated, but it is not always possible to do a
24168 complete check at compile time, so it is important to use this
24169 pragma only if the stated restriction is in fact met, that is to say
24170 no task receives an entry call before elaboration of all units is completed.
24172 @end itemize
24174 @node Mixing Elaboration Models
24175 @section Mixing Elaboration Models
24176 @noindent
24177 So far, we have assumed that the entire program is either compiled
24178 using the dynamic model or static model, ensuring consistency. It
24179 is possible to mix the two models, but rules have to be followed
24180 if this mixing is done to ensure that elaboration checks are not
24181 omitted.
24183 The basic rule is that @emph{a unit compiled with the static model cannot
24184 be @code{with'ed} by a unit compiled with the dynamic model}. The
24185 reason for this is that in the static model, a unit assumes that
24186 its clients guarantee to use (the equivalent of) pragma
24187 @code{Elaborate_All} so that no elaboration checks are required
24188 in inner subprograms, and this assumption is violated if the
24189 client is compiled with dynamic checks.
24191 The precise rule is as follows. A unit that is compiled with dynamic
24192 checks can only @code{with} a unit that meets at least one of the
24193 following criteria:
24195 @itemize @bullet
24197 @item
24198 The @code{with'ed} unit is itself compiled with dynamic elaboration
24199 checks (that is with the @option{-gnatE} switch.
24201 @item
24202 The @code{with'ed} unit is an internal GNAT implementation unit from
24203 the System, Interfaces, Ada, or GNAT hierarchies.
24205 @item
24206 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24208 @item
24209 The @code{with'ing} unit (that is the client) has an explicit pragma
24210 @code{Elaborate_All} for the @code{with'ed} unit.
24212 @end itemize
24214 @noindent
24215 If this rule is violated, that is if a unit with dynamic elaboration
24216 checks @code{with's} a unit that does not meet one of the above four
24217 criteria, then the binder (@code{gnatbind}) will issue a warning
24218 similar to that in the following example:
24220 @smallexample
24221 warning: "x.ads" has dynamic elaboration checks and with's
24222 warning:   "y.ads" which has static elaboration checks
24223 @end smallexample
24225 @noindent
24226 These warnings indicate that the rule has been violated, and that as a result
24227 elaboration checks may be missed in the resulting executable file.
24228 This warning may be suppressed using the @option{-ws} binder switch
24229 in the usual manner.
24231 One useful application of this mixing rule is in the case of a subsystem
24232 which does not itself @code{with} units from the remainder of the
24233 application. In this case, the entire subsystem can be compiled with
24234 dynamic checks to resolve a circularity in the subsystem, while
24235 allowing the main application that uses this subsystem to be compiled
24236 using the more reliable default static model.
24238 @node What to Do If the Default Elaboration Behavior Fails
24239 @section What to Do If the Default Elaboration Behavior Fails
24241 @noindent
24242 If the binder cannot find an acceptable order, it outputs detailed
24243 diagnostics. For example:
24244 @smallexample
24245 @group
24246 @iftex
24247 @leftskip=0cm
24248 @end iftex
24249 error: elaboration circularity detected
24250 info:   "proc (body)" must be elaborated before "pack (body)"
24251 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24252 info:     recompile "pack (body)" with -gnatel
24253 info:                             for full details
24254 info:       "proc (body)"
24255 info:         is needed by its spec:
24256 info:       "proc (spec)"
24257 info:         which is withed by:
24258 info:       "pack (body)"
24259 info:  "pack (body)" must be elaborated before "proc (body)"
24260 info:     reason: pragma Elaborate in unit "proc (body)"
24261 @end group
24263 @end smallexample
24265 @noindent
24266 In this case we have a cycle that the binder cannot break. On the one
24267 hand, there is an explicit pragma Elaborate in @code{proc} for
24268 @code{pack}. This means that the body of @code{pack} must be elaborated
24269 before the body of @code{proc}. On the other hand, there is elaboration
24270 code in @code{pack} that calls a subprogram in @code{proc}. This means
24271 that for maximum safety, there should really be a pragma
24272 Elaborate_All in @code{pack} for @code{proc} which would require that
24273 the body of @code{proc} be elaborated before the body of
24274 @code{pack}. Clearly both requirements cannot be satisfied.
24275 Faced with a circularity of this kind, you have three different options.
24277 @table @asis
24278 @item Fix the program
24279 The most desirable option from the point of view of long-term maintenance
24280 is to rearrange the program so that the elaboration problems are avoided.
24281 One useful technique is to place the elaboration code into separate
24282 child packages. Another is to move some of the initialization code to
24283 explicitly called subprograms, where the program controls the order
24284 of initialization explicitly. Although this is the most desirable option,
24285 it may be impractical and involve too much modification, especially in
24286 the case of complex legacy code.
24288 @item Perform dynamic checks
24289 If the compilations are done using the
24290 @option{-gnatE}
24291 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24292 manner. Dynamic checks are generated for all calls that could possibly result
24293 in raising an exception. With this switch, the compiler does not generate
24294 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24295 exactly as specified in the @cite{Ada Reference Manual}.
24296 The binder will generate
24297 an executable program that may or may not raise @code{Program_Error}, and then
24298 it is the programmer's job to ensure that it does not raise an exception. Note
24299 that it is important to compile all units with the switch, it cannot be used
24300 selectively.
24302 @item Suppress checks
24303 The drawback of dynamic checks is that they generate a
24304 significant overhead at run time, both in space and time. If you
24305 are absolutely sure that your program cannot raise any elaboration
24306 exceptions, and you still want to use the dynamic elaboration model,
24307 then you can use the configuration pragma
24308 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24309 example this pragma could be placed in the @file{gnat.adc} file.
24311 @item Suppress checks selectively
24312 When you know that certain calls or instantiations in elaboration code cannot
24313 possibly lead to an elaboration error, and the binder nevertheless complains
24314 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24315 elaboration circularities, it is possible to remove those warnings locally and
24316 obtain a program that will bind. Clearly this can be unsafe, and it is the
24317 responsibility of the programmer to make sure that the resulting program has no
24318 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24319 used with different granularity to suppress warnings and break elaboration
24320 circularities:
24322 @itemize @bullet
24323 @item
24324 Place the pragma that names the called subprogram in the declarative part
24325 that contains the call.
24327 @item
24328 Place the pragma in the declarative part, without naming an entity. This
24329 disables warnings on all calls in the corresponding  declarative region.
24331 @item
24332 Place the pragma in the package spec that declares the called subprogram,
24333 and name the subprogram. This disables warnings on all elaboration calls to
24334 that subprogram.
24336 @item
24337 Place the pragma in the package spec that declares the called subprogram,
24338 without naming any entity. This disables warnings on all elaboration calls to
24339 all subprograms declared in this spec.
24341 @item Use Pragma Elaborate
24342 As previously described in section @xref{Treatment of Pragma Elaborate},
24343 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24344 that no elaboration checks are required on calls to the designated unit.
24345 There may be cases in which the caller knows that no transitive calls
24346 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24347 case where @code{pragma Elaborate_All} would cause a circularity.
24348 @end itemize
24350 @noindent
24351 These five cases are listed in order of decreasing safety, and therefore
24352 require increasing programmer care in their application. Consider the
24353 following program:
24355 @smallexample @c adanocomment
24356 @b{package} Pack1 @b{is}
24357   @b{function} F1 @b{return} Integer;
24358   X1 : Integer;
24359 @b{end} Pack1;
24361 @b{package} Pack2 @b{is}
24362   @b{function} F2 @b{return} Integer;
24363   @b{function} Pure (x : integer) @b{return} integer;
24364   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24365   --  pragma Suppress (Elaboration_Check);              -- (4)
24366 @b{end} Pack2;
24368 @b{with} Pack2;
24369 @b{package} @b{body} Pack1 @b{is}
24370   @b{function} F1 @b{return} Integer @b{is}
24371   @b{begin}
24372     @b{return} 100;
24373   @b{end} F1;
24374   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24375 @b{begin}
24376   @b{declare}
24377     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24378     --  pragma Suppress(Elaboration_Check);             -- (2)
24379   @b{begin}
24380     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24381   @b{end};
24382 @b{end} Pack1;
24384 @b{with} Pack1;
24385 @b{package} @b{body} Pack2 @b{is}
24386   @b{function} F2 @b{return} Integer @b{is}
24387   @b{begin}
24388      @b{return} Pack1.F1;
24389   @b{end} F2;
24390   @b{function} Pure (x : integer) @b{return} integer @b{is}
24391   @b{begin}
24392      @b{return} x ** 3 - 3 * x;
24393   @b{end};
24394 @b{end} Pack2;
24396 @b{with} Pack1, Ada.Text_IO;
24397 @b{procedure} Proc3 @b{is}
24398 @b{begin}
24399   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24400 @b{end} Proc3;
24401 @end smallexample
24402 In the absence of any pragmas, an attempt to bind this program produces
24403 the following diagnostics:
24404 @smallexample
24405 @group
24406 @iftex
24407 @leftskip=.5cm
24408 @end iftex
24409 error: elaboration circularity detected
24410 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24411 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24412 info:       recompile "pack1 (body)" with -gnatel for full details
24413 info:          "pack1 (body)"
24414 info:             must be elaborated along with its spec:
24415 info:          "pack1 (spec)"
24416 info:             which is withed by:
24417 info:          "pack2 (body)"
24418 info:             which must be elaborated along with its spec:
24419 info:          "pack2 (spec)"
24420 info:             which is withed by:
24421 info:          "pack1 (body)"
24422 @end group
24423 @end smallexample
24424 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24425 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24426 F2 is safe, even though F2 calls F1, because the call appears after the
24427 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24428 remove the warning on the call. It is also possible to use pragma (2)
24429 because there are no other potentially unsafe calls in the block.
24431 @noindent
24432 The call to @code{Pure} is safe because this function does not depend on the
24433 state of @code{Pack2}. Therefore any call to this function is safe, and it
24434 is correct to place pragma (3) in the corresponding package spec.
24436 @noindent
24437 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24438 warnings on all calls to functions declared therein. Note that this is not
24439 necessarily safe, and requires more detailed examination of the subprogram
24440 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24441 be already elaborated.
24442 @end table
24444 @noindent
24445 It is hard to generalize on which of these four approaches should be
24446 taken. Obviously if it is possible to fix the program so that the default
24447 treatment works, this is preferable, but this may not always be practical.
24448 It is certainly simple enough to use
24449 @option{-gnatE}
24450 but the danger in this case is that, even if the GNAT binder
24451 finds a correct elaboration order, it may not always do so,
24452 and certainly a binder from another Ada compiler might not. A
24453 combination of testing and analysis (for which the
24454 information messages generated with the
24455 @option{-gnatel}
24456 switch can be useful) must be used to ensure that the program is free
24457 of errors. One switch that is useful in this testing is the
24458 @option{-p (pessimistic elaboration order)}
24459 switch for
24460 @code{gnatbind}.
24461 Normally the binder tries to find an order that has the best chance
24462 of avoiding elaboration problems. However, if this switch is used, the binder
24463 plays a devil's advocate role, and tries to choose the order that
24464 has the best chance of failing. If your program works even with this
24465 switch, then it has a better chance of being error free, but this is still
24466 not a guarantee.
24468 For an example of this approach in action, consider the C-tests (executable
24469 tests) from the ACVC suite. If these are compiled and run with the default
24470 treatment, then all but one of them succeed without generating any error
24471 diagnostics from the binder. However, there is one test that fails, and
24472 this is not surprising, because the whole point of this test is to ensure
24473 that the compiler can handle cases where it is impossible to determine
24474 a correct order statically, and it checks that an exception is indeed
24475 raised at run time.
24477 This one test must be compiled and run using the
24478 @option{-gnatE}
24479 switch, and then it passes. Alternatively, the entire suite can
24480 be run using this switch. It is never wrong to run with the dynamic
24481 elaboration switch if your code is correct, and we assume that the
24482 C-tests are indeed correct (it is less efficient, but efficiency is
24483 not a factor in running the ACVC tests.)
24485 @node Elaboration for Indirect Calls
24486 @section Elaboration for Indirect Calls
24487 @cindex Dispatching calls
24488 @cindex Indirect calls
24490 @noindent
24491 In rare cases, the static elaboration model fails to prevent
24492 dispatching calls to not-yet-elaborated subprograms. In such cases, we
24493 fall back to run-time checks; premature calls to any primitive
24494 operation of a tagged type before the body of the operation has been
24495 elaborated will raise @code{Program_Error}.
24497 Access-to-subprogram types, however, are handled conservatively, and
24498 do not require run-time checks. This was not true in earlier versions
24499 of the compiler; you can use the @option{-gnatd.U} debug switch to
24500 revert to the old behavior if the new conservative behavior causes
24501 elaboration cycles. Here, ``conservative'' means that if you do
24502 @code{P'Access} during elaboration, the compiler will assume that you
24503 might call @code{P} indirectly during elaboration, so it adds an
24504 implicit @code{pragma Elaborate_All} on the library unit containing
24505 @code{P}. The @option{-gnatd.U} switch is safe if you know there are
24506 no such calls. If the program worked before, it will continue to work
24507 with @option{-gnatd.U}. But beware that code modifications such as
24508 adding an indirect call can cause erroneous behavior in the presence
24509 of @option{-gnatd.U}.
24511 @node Summary of Procedures for Elaboration Control
24512 @section Summary of Procedures for Elaboration Control
24513 @cindex Elaboration control
24515 @noindent
24516 First, compile your program with the default options, using none of
24517 the special elaboration control switches. If the binder successfully
24518 binds your program, then you can be confident that, apart from issues
24519 raised by the use of access-to-subprogram types and dynamic dispatching,
24520 the program is free of elaboration errors. If it is important that the
24521 program be portable to other compilers than GNAT, then use the
24522 @option{-gnatel}
24523 switch to generate messages about missing @code{Elaborate} or
24524 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24526 If the program fails to bind using the default static elaboration
24527 handling, then you can fix the program to eliminate the binder
24528 message, or recompile the entire program with the
24529 @option{-gnatE} switch to generate dynamic elaboration checks,
24530 and, if you are sure there really are no elaboration problems,
24531 use a global pragma @code{Suppress (Elaboration_Check)}.
24533 @node Other Elaboration Order Considerations
24534 @section Other Elaboration Order Considerations
24535 @noindent
24536 This section has been entirely concerned with the issue of finding a valid
24537 elaboration order, as defined by the Ada Reference Manual. In a case
24538 where several elaboration orders are valid, the task is to find one
24539 of the possible valid elaboration orders (and the static model in GNAT
24540 will ensure that this is achieved).
24542 The purpose of the elaboration rules in the Ada Reference Manual is to
24543 make sure that no entity is accessed before it has been elaborated. For
24544 a subprogram, this means that the spec and body must have been elaborated
24545 before the subprogram is called. For an object, this means that the object
24546 must have been elaborated before its value is read or written. A violation
24547 of either of these two requirements is an access before elaboration order,
24548 and this section has been all about avoiding such errors.
24550 In the case where more than one order of elaboration is possible, in the
24551 sense that access before elaboration errors are avoided, then any one of
24552 the orders is ``correct'' in the sense that it meets the requirements of
24553 the Ada Reference Manual, and no such error occurs.
24555 However, it may be the case for a given program, that there are
24556 constraints on the order of elaboration that come not from consideration
24557 of avoiding elaboration errors, but rather from extra-lingual logic
24558 requirements. Consider this example:
24560 @smallexample @c ada
24561 @b{with} Init_Constants;
24562 @b{package} Constants @b{is}
24563    X : Integer := 0;
24564    Y : Integer := 0;
24565 @b{end} Constants;
24567 @b{package} Init_Constants @b{is}
24568    @b{procedure} P; --@i{ require a body}
24569 @b{end} Init_Constants;
24571 @b{with} Constants;
24572 @b{package} @b{body} Init_Constants @b{is}
24573    @b{procedure} P @b{is} @b{begin} @b{null}; @b{end};
24574 @b{begin}
24575    Constants.X := 3;
24576    Constants.Y := 4;
24577 @b{end} Init_Constants;
24579 @b{with} Constants;
24580 @b{package} Calc @b{is}
24581    Z : Integer := Constants.X + Constants.Y;
24582 @b{end} Calc;
24584 @b{with} Calc;
24585 @b{with} Text_IO; @b{use} Text_IO;
24586 @b{procedure} Main @b{is}
24587 @b{begin}
24588    Put_Line (Calc.Z'Img);
24589 @b{end} Main;
24590 @end smallexample
24592 @noindent
24593 In this example, there is more than one valid order of elaboration. For
24594 example both the following are correct orders:
24596 @smallexample
24597 Init_Constants spec
24598 Constants spec
24599 Calc spec
24600 Init_Constants body
24601 Main body
24603   and
24605 Init_Constants spec
24606 Init_Constants body
24607 Constants spec
24608 Calc spec
24609 Main body
24610 @end smallexample
24612 @noindent
24613 There is no language rule to prefer one or the other, both are correct
24614 from an order of elaboration point of view. But the programmatic effects
24615 of the two orders are very different. In the first, the elaboration routine
24616 of @code{Calc} initializes @code{Z} to zero, and then the main program
24617 runs with this value of zero. But in the second order, the elaboration
24618 routine of @code{Calc} runs after the body of Init_Constants has set
24619 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24620 runs.
24622 One could perhaps by applying pretty clever non-artificial intelligence
24623 to the situation guess that it is more likely that the second order of
24624 elaboration is the one desired, but there is no formal linguistic reason
24625 to prefer one over the other. In fact in this particular case, GNAT will
24626 prefer the second order, because of the rule that bodies are elaborated
24627 as soon as possible, but it's just luck that this is what was wanted
24628 (if indeed the second order was preferred).
24630 If the program cares about the order of elaboration routines in a case like
24631 this, it is important to specify the order required. In this particular
24632 case, that could have been achieved by adding to the spec of Calc:
24634 @smallexample @c ada
24635 @b{pragma} Elaborate_All (Constants);
24636 @end smallexample
24638 @noindent
24639 which requires that the body (if any) and spec of @code{Constants},
24640 as well as the body and spec of any unit @code{with}'ed by
24641 @code{Constants} be elaborated before @code{Calc} is elaborated.
24643 Clearly no automatic method can always guess which alternative you require,
24644 and if you are working with legacy code that had constraints of this kind
24645 which were not properly specified by adding @code{Elaborate} or
24646 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24647 compilers can choose different orders.
24649 However, GNAT does attempt to diagnose the common situation where there
24650 are uninitialized variables in the visible part of a package spec, and the
24651 corresponding package body has an elaboration block that directly or
24652 indirectly initialized one or more of these variables. This is the situation
24653 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24654 a warning that suggests this addition if it detects this situation.
24656 The @code{gnatbind}
24657 @option{-p} switch may be useful in smoking
24658 out problems. This switch causes bodies to be elaborated as late as possible
24659 instead of as early as possible. In the example above, it would have forced
24660 the choice of the first elaboration order. If you get different results
24661 when using this switch, and particularly if one set of results is right,
24662 and one is wrong as far as you are concerned, it shows that you have some
24663 missing @code{Elaborate} pragmas. For the example above, we have the
24664 following output:
24666 @smallexample
24667 gnatmake -f -q main
24668 main
24670 gnatmake -f -q main -bargs -p
24671 main
24673 @end smallexample
24675 @noindent
24676 It is of course quite unlikely that both these results are correct, so
24677 it is up to you in a case like this to investigate the source of the
24678 difference, by looking at the two elaboration orders that are chosen,
24679 and figuring out which is correct, and then adding the necessary
24680 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24682 @node Determining the Chosen Elaboration Order
24683 @section Determining the Chosen Elaboration Order
24684 @noindent
24686 To see the elaboration order that the binder chooses, you can look at
24687 the last part of the b~xxx.adb binder output file. Here is an example:
24689 @smallexample @c ada
24690 System.Soft_Links'Elab_Body;
24691 E14 := True;
24692 System.Secondary_Stack'Elab_Body;
24693 E18 := True;
24694 System.Exception_Table'Elab_Body;
24695 E24 := True;
24696 Ada.Io_Exceptions'Elab_Spec;
24697 E67 := True;
24698 Ada.Tags'Elab_Spec;
24699 Ada.Streams'Elab_Spec;
24700 E43 := True;
24701 Interfaces.C'Elab_Spec;
24702 E69 := True;
24703 System.Finalization_Root'Elab_Spec;
24704 E60 := True;
24705 System.Os_Lib'Elab_Body;
24706 E71 := True;
24707 System.Finalization_Implementation'Elab_Spec;
24708 System.Finalization_Implementation'Elab_Body;
24709 E62 := True;
24710 Ada.Finalization'Elab_Spec;
24711 E58 := True;
24712 Ada.Finalization.List_Controller'Elab_Spec;
24713 E76 := True;
24714 System.File_Control_Block'Elab_Spec;
24715 E74 := True;
24716 System.File_Io'Elab_Body;
24717 E56 := True;
24718 Ada.Tags'Elab_Body;
24719 E45 := True;
24720 Ada.Text_Io'Elab_Spec;
24721 Ada.Text_Io'Elab_Body;
24722 E07 := True;
24723 @end smallexample
24725 @noindent
24726 Here Elab_Spec elaborates the spec
24727 and Elab_Body elaborates the body. The assignments to the Exx flags
24728 flag that the corresponding body is now elaborated.
24730 You can also ask the binder to generate a more
24731 readable list of the elaboration order using the
24732 @code{-l} switch when invoking the binder. Here is
24733 an example of the output generated by this switch:
24735 @smallexample
24736 ada (spec)
24737 interfaces (spec)
24738 system (spec)
24739 system.case_util (spec)
24740 system.case_util (body)
24741 system.concat_2 (spec)
24742 system.concat_2 (body)
24743 system.concat_3 (spec)
24744 system.concat_3 (body)
24745 system.htable (spec)
24746 system.parameters (spec)
24747 system.parameters (body)
24748 system.crtl (spec)
24749 interfaces.c_streams (spec)
24750 interfaces.c_streams (body)
24751 system.restrictions (spec)
24752 system.restrictions (body)
24753 system.standard_library (spec)
24754 system.exceptions (spec)
24755 system.exceptions (body)
24756 system.storage_elements (spec)
24757 system.storage_elements (body)
24758 system.secondary_stack (spec)
24759 system.stack_checking (spec)
24760 system.stack_checking (body)
24761 system.string_hash (spec)
24762 system.string_hash (body)
24763 system.htable (body)
24764 system.strings (spec)
24765 system.strings (body)
24766 system.traceback (spec)
24767 system.traceback (body)
24768 system.traceback_entries (spec)
24769 system.traceback_entries (body)
24770 ada.exceptions (spec)
24771 ada.exceptions.last_chance_handler (spec)
24772 system.soft_links (spec)
24773 system.soft_links (body)
24774 ada.exceptions.last_chance_handler (body)
24775 system.secondary_stack (body)
24776 system.exception_table (spec)
24777 system.exception_table (body)
24778 ada.io_exceptions (spec)
24779 ada.tags (spec)
24780 ada.streams (spec)
24781 interfaces.c (spec)
24782 interfaces.c (body)
24783 system.finalization_root (spec)
24784 system.finalization_root (body)
24785 system.memory (spec)
24786 system.memory (body)
24787 system.standard_library (body)
24788 system.os_lib (spec)
24789 system.os_lib (body)
24790 system.unsigned_types (spec)
24791 system.stream_attributes (spec)
24792 system.stream_attributes (body)
24793 system.finalization_implementation (spec)
24794 system.finalization_implementation (body)
24795 ada.finalization (spec)
24796 ada.finalization (body)
24797 ada.finalization.list_controller (spec)
24798 ada.finalization.list_controller (body)
24799 system.file_control_block (spec)
24800 system.file_io (spec)
24801 system.file_io (body)
24802 system.val_uns (spec)
24803 system.val_util (spec)
24804 system.val_util (body)
24805 system.val_uns (body)
24806 system.wch_con (spec)
24807 system.wch_con (body)
24808 system.wch_cnv (spec)
24809 system.wch_jis (spec)
24810 system.wch_jis (body)
24811 system.wch_cnv (body)
24812 system.wch_stw (spec)
24813 system.wch_stw (body)
24814 ada.tags (body)
24815 ada.exceptions (body)
24816 ada.text_io (spec)
24817 ada.text_io (body)
24818 text_io (spec)
24819 gdbstr (body)
24820 @end smallexample
24822 @c **********************************
24823 @node Overflow Check Handling in GNAT
24824 @appendix Overflow Check Handling in GNAT
24825 @cindex Overflow checks
24826 @cindex Checks (overflow)
24827 @c **********************************
24829 @menu
24830 * Background::
24831 * Overflow Checking Modes in GNAT::
24832 * Specifying the Desired Mode::
24833 * Default Settings::
24834 * Implementation Notes::
24835 @end menu
24838 @node Background
24839 @section Background
24841 @noindent
24842 Overflow checks are checks that the compiler may make to ensure
24843 that intermediate results are not out of range. For example:
24845 @smallexample @c ada
24846    A : Integer;
24847    ...
24848    A := A + 1;
24849 @end smallexample
24851 @noindent
24852 if @code{A} has the value @code{Integer'Last}, then the addition may cause
24853 overflow since the result is out of range of the type @code{Integer}.
24854 In this case @code{Constraint_Error} will be raised if checks are
24855 enabled.
24857 A trickier situation arises in examples like the following:
24859 @smallexample @c ada
24860   A, C : Integer;
24861   ...
24862   A := (A + 1) + C;
24863 @end smallexample
24865 @noindent
24866 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
24867 Now the final result of the expression on the right hand side is
24868 @code{Integer'Last} which is in range, but the question arises whether the
24869 intermediate addition of @code{(A + 1)} raises an overflow error.
24871 The (perhaps surprising) answer is that the Ada language
24872 definition does not answer this question. Instead it leaves
24873 it up to the implementation to do one of two things if overflow
24874 checks are enabled.
24876 @itemize @bullet
24877 @item
24878 raise an exception (@code{Constraint_Error}), or
24880 @item
24881 yield the correct mathematical result which is then used in
24882 subsequent operations.
24883 @end itemize
24885 @noindent
24886 If the compiler chooses the first approach, then the assignment of this
24887 example will indeed raise @code{Constraint_Error} if overflow checking is
24888 enabled, or result in erroneous execution if overflow checks are suppressed.
24890 But if the compiler
24891 chooses the second approach, then it can perform both additions yielding
24892 the correct mathematical result, which is in range, so no exception
24893 will be raised, and the right result is obtained, regardless of whether
24894 overflow checks are suppressed.
24896 Note that in the first example an
24897 exception will be raised in either case, since if the compiler
24898 gives the correct mathematical result for the addition, it will
24899 be out of range of the target type of the assignment, and thus
24900 fails the range check.
24902 This lack of specified behavior in the handling of overflow for
24903 intermediate results is a source of non-portability, and can thus
24904 be problematic when programs are ported. Most typically this arises
24905 in a situation where the original compiler did not raise an exception,
24906 and then the application is moved to a compiler where the check is
24907 performed on the intermediate result and an unexpected exception is
24908 raised.
24910 Furthermore, when using Ada 2012's preconditions and other
24911 assertion forms, another issue arises. Consider:
24913 @smallexample @c ada
24914      @b{procedure} P (A, B : Integer) @b{with}
24915        Pre => A + B <= Integer'Last;
24916 @end smallexample
24918 @noindent
24919 One often wants to regard arithmetic in a context like this from
24920 a mathematical point of view. So for example, if the two actual parameters
24921 for a call to @code{P} are both @code{Integer'Last}, then
24922 the precondition should be regarded as False. If we are executing
24923 in a mode with run-time checks enabled for preconditions, then we would
24924 like this precondition to fail, rather than raising an exception
24925 because of the intermediate overflow.
24927 However, the language definition leaves the specification of
24928 whether the above condition fails (raising @code{Assert_Error}) or
24929 causes an intermediate overflow (raising @code{Constraint_Error})
24930 up to the implementation.
24932 The situation is worse in a case such as the following:
24934 @smallexample @c ada
24935      @b{procedure} Q (A, B, C : Integer) @b{with}
24936        Pre => A + B + C <= Integer'Last;
24937 @end smallexample
24939 @noindent
24940 Consider the call
24942 @smallexample @c ada
24943      Q (A => Integer'Last, B => 1, C => -1);
24944 @end smallexample
24946 @noindent
24947 From a mathematical point of view the precondition
24948 is True, but at run time we may (but are not guaranteed to) get an
24949 exception raised because of the intermediate overflow (and we really
24950 would prefer this precondition to be considered True at run time).
24952 @node Overflow Checking Modes in GNAT
24953 @section Overflow Checking Modes in GNAT
24955 @noindent
24956 To deal with the portability issue, and with the problem of
24957 mathematical versus run-time interpretation of the expressions in
24958 assertions, GNAT provides comprehensive control over the handling
24959 of intermediate overflow. GNAT can operate in three modes, and
24960 furthemore, permits separate selection of operating modes for
24961 the expressions within assertions (here the term ``assertions''
24962 is used in the technical sense, which includes preconditions and so forth)
24963 and for expressions appearing outside assertions.
24965 The three modes are:
24967 @itemize @bullet
24968 @item   @i{Use base type for intermediate operations} (@code{STRICT})
24970      In this mode, all intermediate results for predefined arithmetic
24971      operators are computed using the base type, and the result must
24972      be in range of the base type. If this is not the
24973      case then either an exception is raised (if overflow checks are
24974      enabled) or the execution is erroneous (if overflow checks are suppressed).
24975      This is the normal default mode.
24977 @item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
24979      In this mode, the compiler attempts to avoid intermediate overflows by
24980      using a larger integer type, typically @code{Long_Long_Integer},
24981      as the type in which arithmetic is
24982      performed for predefined arithmetic operators. This may be slightly more
24983      expensive at
24984      run time (compared to suppressing intermediate overflow checks), though
24985      the cost is negligible on modern 64-bit machines. For the examples given
24986      earlier, no intermediate overflows would have resulted in exceptions,
24987      since the intermediate results are all in the range of
24988      @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
24989      of GNAT). In addition, if checks are enabled, this reduces the number of
24990      checks that must be made, so this choice may actually result in an
24991      improvement in space and time behavior.
24993      However, there are cases where @code{Long_Long_Integer} is not large
24994      enough, consider the following example:
24996 @smallexample @c ada
24997        @b{procedure} R (A, B, C, D : Integer) @b{with}
24998          Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
24999 @end smallexample
25001      where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
25002      Now the intermediate results are
25003      out of the range of @code{Long_Long_Integer} even though the final result
25004      is in range and the precondition is True (from a mathematical point
25005      of view). In such a case, operating in this mode, an overflow occurs
25006      for the intermediate computation (which is why this mode
25007      says @i{most} intermediate overflows are avoided). In this case,
25008      an exception is raised if overflow checks are enabled, and the
25009      execution is erroneous if overflow checks are suppressed.
25011 @item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
25013      In this mode, the compiler  avoids all intermediate overflows
25014      by using arbitrary precision arithmetic as required. In this
25015      mode, the above example with @code{A**2 * B**2} would
25016      not cause intermediate overflow, because the intermediate result
25017      would be evaluated using sufficient precision, and the result
25018      of evaluating the precondition would be True.
25020      This mode has the advantage of avoiding any intermediate
25021      overflows, but at the expense of significant run-time overhead,
25022      including the use of a library (included automatically in this
25023      mode) for multiple-precision arithmetic.
25025      This mode provides cleaner semantics for assertions, since now
25026      the run-time behavior emulates true arithmetic behavior for the
25027      predefined arithmetic operators, meaning that there is never a
25028      conflict between the mathematical view of the assertion, and its
25029      run-time behavior.
25031      Note that in this mode, the behavior is unaffected by whether or
25032      not overflow checks are suppressed, since overflow does not occur.
25033      It is possible for gigantic intermediate expressions to raise
25034      @code{Storage_Error} as a result of attempting to compute the
25035      results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
25036      but overflow is impossible.
25039 @end itemize
25041 @noindent
25042   Note that these modes apply only to the evaluation of predefined
25043   arithmetic, membership, and comparison operators for signed integer
25044   aritmetic.
25046   For fixed-point arithmetic, checks can be suppressed. But if checks
25047   are enabled
25048   then fixed-point values are always checked for overflow against the
25049   base type for intermediate expressions (that is such checks always
25050   operate in the equivalent of @code{STRICT} mode).
25052   For floating-point, on nearly all architectures, @code{Machine_Overflows}
25053   is False, and IEEE infinities are generated, so overflow exceptions
25054   are never raised. If you want to avoid infinities, and check that
25055   final results of expressions are in range, then you can declare a
25056   constrained floating-point type, and range checks will be carried
25057   out in the normal manner (with infinite values always failing all
25058   range checks).
25061 @c -------------------------
25062 @node Specifying the Desired Mode
25063 @section Specifying the Desired Mode
25065 @noindent
25066 The desired mode of for handling intermediate overflow can be specified using
25067 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
25068 The pragma has the form
25069 @cindex pragma @code{Overflow_Mode}
25071 @smallexample @c ada
25072     @b{pragma} Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
25073 @end smallexample
25075 @noindent
25076 where @code{MODE} is one of
25078 @itemize @bullet
25079 @item   @code{STRICT}:  intermediate overflows checked (using base type)
25080 @item   @code{MINIMIZED}: minimize intermediate overflows
25081 @item   @code{ELIMINATED}: eliminate intermediate overflows
25082 @end itemize
25084 @noindent
25085 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
25086 @code{minimized} all have the same effect.
25088 If only the @code{General} parameter is present, then the given @code{MODE}
25089 applies
25090 to expressions both within and outside assertions. If both arguments
25091 are present, then @code{General} applies to expressions outside assertions,
25092 and @code{Assertions} applies to expressions within assertions. For example:
25094 @smallexample @c ada
25095    @b{pragma} Overflow_Mode
25096      (General => Minimized, Assertions => Eliminated);
25097 @end smallexample
25099 @noindent
25100 specifies that general expressions outside assertions be evaluated
25101 in ``minimize intermediate overflows'' mode, and expressions within
25102 assertions be evaluated in ``eliminate intermediate overflows'' mode.
25103 This is often a reasonable choice, avoiding excessive overhead
25104 outside assertions, but assuring a high degree of portability
25105 when importing code from another compiler, while incurring
25106 the extra overhead for assertion expressions to ensure that
25107 the behavior at run time matches the expected mathematical
25108 behavior.
25110 The @code{Overflow_Mode} pragma has the same scoping and placement
25111 rules as pragma @code{Suppress}, so it can occur either as a
25112 configuration pragma, specifying a default for the whole
25113 program, or in a declarative scope, where it applies to the
25114 remaining declarations and statements in that scope.
25116 Note that pragma @code{Overflow_Mode} does not affect whether
25117 overflow checks are enabled or suppressed. It only controls the
25118 method used to compute intermediate values. To control whether
25119 overflow checking is enabled or suppressed, use pragma @code{Suppress}
25120 or @code{Unsuppress} in the usual manner
25122 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
25123 can be used to control the checking mode default (which can be subsequently
25124 overridden using pragmas).
25125 @cindex @option{-gnato?} (gcc)
25126 @cindex @option{-gnato??} (gcc)
25128 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
25130 @itemize @bullet
25131 @item   @code{1}:
25132 use base type for intermediate operations (@code{STRICT})
25133 @item   @code{2}:
25134 minimize intermediate overflows (@code{MINIMIZED})
25135 @item   @code{3}:
25136 eliminate intermediate overflows (@code{ELIMINATED})
25137 @end itemize
25139 @noindent
25140 As with the pragma, if only one digit appears then it applies to all
25141 cases; if two digits are given, then the first applies outside
25142 assertions, and the second within assertions. Thus the equivalent
25143 of the example pragma above would be
25144 @option{-gnato23}.
25146 If no digits follow the @option{-gnato}, then it is equivalent to
25147 @option{-gnato11},
25148 causing all intermediate operations to be computed using the base
25149 type (@code{STRICT} mode).
25151 In addition to setting the mode used for computation of intermediate
25152 results, the @code{-gnato} switch also enables overflow checking (which
25153 is suppressed by default). It thus combines the effect of using
25154 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
25157 @c -------------------------
25158 @node Default Settings
25159 @section Default Settings
25161 The default mode for overflow checks is
25163 @smallexample
25164    General => Strict
25165 @end smallexample
25167 @noindent
25168 which causes all computations both inside and outside assertions to use
25169 the base type. In addition overflow checks are suppressed.
25171 This retains compatibility with previous versions of
25172 GNAT which suppressed overflow checks by default and always
25173 used the base type for computation of intermediate results.
25175 The switch @option{-gnato} (with no digits following) is equivalent to
25176 @cindex @option{-gnato} (gcc)
25178 @smallexample
25179    General => Strict
25180 @end smallexample
25182 @noindent
25183 which causes overflow checking of all intermediate overflows
25184 both inside and outside assertions against the base type.
25185 This provides compatibility
25186 with this switch as implemented in previous versions of GNAT.
25188 The pragma @code{Suppress (Overflow_Check)} disables overflow
25189 checking, but it has no effect on the method used for computing
25190 intermediate results.
25192 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
25193 checking, but it has no effect on the method used for computing
25194 intermediate results.
25196 @c -------------------------
25197 @node Implementation Notes
25198 @section Implementation Notes
25200 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
25201 reasonably efficient, and can be generally used. It also helps
25202 to ensure compatibility with code imported from some other
25203 compiler to GNAT.
25205 Setting all intermediate overflows checking (@code{CHECKED} mode)
25206 makes sense if you want to
25207 make sure that your code is compatible with any other possible
25208 Ada implementation. This may be useful in ensuring portability
25209 for code that is to be exported to some other compiler than GNAT.
25212 The Ada standard allows the reassociation of expressions at
25213 the same precedence level if no parentheses are present. For
25214 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
25215 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
25216 introducing or eliminating an overflow exception. The GNAT
25217 compiler never takes advantage of this freedom, and the
25218 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
25219 If you need the other order, you can write the parentheses
25220 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
25222 The use of @code{ELIMINATED} mode will cause the compiler to
25223 automatically include an appropriate arbitrary precision
25224 integer arithmetic package. The compiler will make calls
25225 to this package, though only in cases where it cannot be
25226 sure that @code{Long_Long_Integer} is sufficient to guard against
25227 intermediate overflows. This package does not use dynamic
25228 alllocation, but it does use the secondary stack, so an
25229 appropriate secondary stack package must be present (this
25230 is always true for standard full Ada, but may require
25231 specific steps for restricted run times such as ZFP).
25233 Although @code{ELIMINATED} mode causes expressions to use arbitrary
25234 precision arithmetic, avoiding overflow, the final result
25235 must be in an appropriate range. This is true even if the
25236 final result is of type @code{[Long_[Long_]]Integer'Base}, which
25237 still has the same bounds as its associated constrained
25238 type at run-time.
25240 Currently, the @code{ELIMINATED} mode is only available on target
25241 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
25242 platforms).
25244 @c *******************************
25245 @node Conditional Compilation
25246 @appendix Conditional Compilation
25247 @c *******************************
25248 @cindex Conditional compilation
25250 @noindent
25251 It is often necessary to arrange for a single source program
25252 to serve multiple purposes, where it is compiled in different
25253 ways to achieve these different goals. Some examples of the
25254 need for this feature are
25256 @itemize @bullet
25257 @item  Adapting a program to a different hardware environment
25258 @item  Adapting a program to a different target architecture
25259 @item  Turning debugging features on and off
25260 @item  Arranging for a program to compile with different compilers
25261 @end itemize
25263 @noindent
25264 In C, or C++, the typical approach would be to use the preprocessor
25265 that is defined as part of the language. The Ada language does not
25266 contain such a feature. This is not an oversight, but rather a very
25267 deliberate design decision, based on the experience that overuse of
25268 the preprocessing features in C and C++ can result in programs that
25269 are extremely difficult to maintain. For example, if we have ten
25270 switches that can be on or off, this means that there are a thousand
25271 separate programs, any one of which might not even be syntactically
25272 correct, and even if syntactically correct, the resulting program
25273 might not work correctly. Testing all combinations can quickly become
25274 impossible.
25276 Nevertheless, the need to tailor programs certainly exists, and in
25277 this Appendix we will discuss how this can
25278 be achieved using Ada in general, and GNAT in particular.
25280 @menu
25281 * Use of Boolean Constants::
25282 * Debugging - A Special Case::
25283 * Conditionalizing Declarations::
25284 * Use of Alternative Implementations::
25285 * Preprocessing::
25286 @end menu
25288 @node Use of Boolean Constants
25289 @section Use of Boolean Constants
25291 @noindent
25292 In the case where the difference is simply which code
25293 sequence is executed, the cleanest solution is to use Boolean
25294 constants to control which code is executed.
25296 @smallexample @c ada
25297 @group
25298 FP_Initialize_Required : @b{constant} Boolean := True;
25299 @dots{}
25300 @b{if} FP_Initialize_Required @b{then}
25301 @dots{}
25302 @b{end} @b{if};
25303 @end group
25304 @end smallexample
25306 @noindent
25307 Not only will the code inside the @code{if} statement not be executed if
25308 the constant Boolean is @code{False}, but it will also be completely
25309 deleted from the program.
25310 However, the code is only deleted after the @code{if} statement
25311 has been checked for syntactic and semantic correctness.
25312 (In contrast, with preprocessors the code is deleted before the
25313 compiler ever gets to see it, so it is not checked until the switch
25314 is turned on.)
25315 @cindex Preprocessors (contrasted with conditional compilation)
25317 Typically the Boolean constants will be in a separate package,
25318 something like:
25320 @smallexample @c ada
25321 @group
25322 @b{package} Config @b{is}
25323    FP_Initialize_Required : @b{constant} Boolean := True;
25324    Reset_Available        : @b{constant} Boolean := False;
25325    @dots{}
25326 @b{end} Config;
25327 @end group
25328 @end smallexample
25330 @noindent
25331 The @code{Config} package exists in multiple forms for the various targets,
25332 with an appropriate script selecting the version of @code{Config} needed.
25333 Then any other unit requiring conditional compilation can do a @code{with}
25334 of @code{Config} to make the constants visible.
25337 @node Debugging - A Special Case
25338 @section Debugging - A Special Case
25340 @noindent
25341 A common use of conditional code is to execute statements (for example
25342 dynamic checks, or output of intermediate results) under control of a
25343 debug switch, so that the debugging behavior can be turned on and off.
25344 This can be done using a Boolean constant to control whether the code
25345 is active:
25347 @smallexample @c ada
25348 @group
25349 @b{if} Debugging @b{then}
25350    Put_Line ("got to the first stage!");
25351 @b{end} @b{if};
25352 @end group
25353 @end smallexample
25355 @noindent
25358 @smallexample @c ada
25359 @group
25360 @b{if} Debugging @b{and} @b{then} Temperature > 999.0 @b{then}
25361    @b{raise} Temperature_Crazy;
25362 @b{end} @b{if};
25363 @end group
25364 @end smallexample
25366 @noindent
25367 Since this is a common case, there are special features to deal with
25368 this in a convenient manner. For the case of tests, Ada 2005 has added
25369 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25370 @cindex pragma @code{Assert}
25371 on the @code{Assert} pragma that has always been available in GNAT, so this
25372 feature may be used with GNAT even if you are not using Ada 2005 features.
25373 The use of pragma @code{Assert} is described in
25374 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25375 example, the last test could be written:
25377 @smallexample @c ada
25378 @b{pragma} Assert (Temperature <= 999.0, "Temperature Crazy");
25379 @end smallexample
25381 @noindent
25382 or simply
25384 @smallexample @c ada
25385 @b{pragma} Assert (Temperature <= 999.0);
25386 @end smallexample
25388 @noindent
25389 In both cases, if assertions are active and the temperature is excessive,
25390 the exception @code{Assert_Failure} will be raised, with the given string in
25391 the first case or a string indicating the location of the pragma in the second
25392 case used as the exception message.
25394 You can turn assertions on and off by using the @code{Assertion_Policy}
25395 pragma.
25396 @cindex pragma @code{Assertion_Policy}
25397 This is an Ada 2005 pragma which is implemented in all modes by
25398 GNAT, but only in the latest versions of GNAT which include Ada 2005
25399 capability. Alternatively, you can use the @option{-gnata} switch
25400 @cindex @option{-gnata} switch
25401 to enable assertions from the command line (this is recognized by all versions
25402 of GNAT).
25404 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25405 @code{Debug} can be used:
25406 @cindex pragma @code{Debug}
25408 @smallexample @c ada
25409 @b{pragma} Debug (Put_Line ("got to the first stage!"));
25410 @end smallexample
25412 @noindent
25413 If debug pragmas are enabled, the argument, which must be of the form of
25414 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25415 Only one call can be present, but of course a special debugging procedure
25416 containing any code you like can be included in the program and then
25417 called in a pragma @code{Debug} argument as needed.
25419 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25420 construct is that pragma @code{Debug} can appear in declarative contexts,
25421 such as at the very beginning of a procedure, before local declarations have
25422 been elaborated.
25424 Debug pragmas are enabled using either the @option{-gnata} switch that also
25425 controls assertions, or with a separate Debug_Policy pragma.
25426 @cindex pragma @code{Debug_Policy}
25427 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25428 in Ada 95 and Ada 83 programs as well), and is analogous to
25429 pragma @code{Assertion_Policy} to control assertions.
25431 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25432 and thus they can appear in @file{gnat.adc} if you are not using a
25433 project file, or in the file designated to contain configuration pragmas
25434 in a project file.
25435 They then apply to all subsequent compilations. In practice the use of
25436 the @option{-gnata} switch is often the most convenient method of controlling
25437 the status of these pragmas.
25439 Note that a pragma is not a statement, so in contexts where a statement
25440 sequence is required, you can't just write a pragma on its own. You have
25441 to add a @code{null} statement.
25443 @smallexample @c ada
25444 @group
25445 @b{if} @dots{} @b{then}
25446    @dots{} -- some statements
25447 @b{else}
25448    @b{pragma} Assert (Num_Cases < 10);
25449    @b{null};
25450 @b{end} @b{if};
25451 @end group
25452 @end smallexample
25455 @node Conditionalizing Declarations
25456 @section Conditionalizing Declarations
25458 @noindent
25459 In some cases, it may be necessary to conditionalize declarations to meet
25460 different requirements. For example we might want a bit string whose length
25461 is set to meet some hardware message requirement.
25463 In some cases, it may be possible to do this using declare blocks controlled
25464 by conditional constants:
25466 @smallexample @c ada
25467 @group
25468 @b{if} Small_Machine @b{then}
25469    @b{declare}
25470       X : Bit_String (1 .. 10);
25471    @b{begin}
25472       @dots{}
25473    @b{end};
25474 @b{else}
25475    @b{declare}
25476       X : Large_Bit_String (1 .. 1000);
25477    @b{begin}
25478       @dots{}
25479    @b{end};
25480 @b{end} @b{if};
25481 @end group
25482 @end smallexample
25484 @noindent
25485 Note that in this approach, both declarations are analyzed by the
25486 compiler so this can only be used where both declarations are legal,
25487 even though one of them will not be used.
25489 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25490 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25491 that are parameterized by these constants. For example
25493 @smallexample @c ada
25494 @group
25495 @b{for} Rec @b{use}
25496   Field1 @b{at} 0 @b{range} Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25497 @b{end} @b{record};
25498 @end group
25499 @end smallexample
25501 @noindent
25502 If @code{Bits_Per_Word} is set to 32, this generates either
25504 @smallexample @c ada
25505 @group
25506 @b{for} Rec @b{use}
25507   Field1 @b{at} 0 @b{range} 0 .. 32;
25508 @b{end} @b{record};
25509 @end group
25510 @end smallexample
25512 @noindent
25513 for the big endian case, or
25515 @smallexample @c ada
25516 @group
25517 @b{for} Rec @b{use} @b{record}
25518   Field1 @b{at} 0 @b{range} 10 .. 32;
25519 @b{end} @b{record};
25520 @end group
25521 @end smallexample
25523 @noindent
25524 for the little endian case. Since a powerful subset of Ada expression
25525 notation is usable for creating static constants, clever use of this
25526 feature can often solve quite difficult problems in conditionalizing
25527 compilation (note incidentally that in Ada 95, the little endian
25528 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25529 need to define this one yourself).
25532 @node Use of Alternative Implementations
25533 @section Use of Alternative Implementations
25535 @noindent
25536 In some cases, none of the approaches described above are adequate. This
25537 can occur for example if the set of declarations required is radically
25538 different for two different configurations.
25540 In this situation, the official Ada way of dealing with conditionalizing
25541 such code is to write separate units for the different cases. As long as
25542 this does not result in excessive duplication of code, this can be done
25543 without creating maintenance problems. The approach is to share common
25544 code as far as possible, and then isolate the code and declarations
25545 that are different. Subunits are often a convenient method for breaking
25546 out a piece of a unit that is to be conditionalized, with separate files
25547 for different versions of the subunit for different targets, where the
25548 build script selects the right one to give to the compiler.
25549 @cindex Subunits (and conditional compilation)
25551 As an example, consider a situation where a new feature in Ada 2005
25552 allows something to be done in a really nice way. But your code must be able
25553 to compile with an Ada 95 compiler. Conceptually you want to say:
25555 @smallexample @c ada
25556 @group
25557 @b{if} Ada_2005 @b{then}
25558    @dots{} neat Ada 2005 code
25559 @b{else}
25560    @dots{} not quite as neat Ada 95 code
25561 @b{end} @b{if};
25562 @end group
25563 @end smallexample
25565 @noindent
25566 where @code{Ada_2005} is a Boolean constant.
25568 But this won't work when @code{Ada_2005} is set to @code{False},
25569 since the @code{then} clause will be illegal for an Ada 95 compiler.
25570 (Recall that although such unreachable code would eventually be deleted
25571 by the compiler, it still needs to be legal.  If it uses features
25572 introduced in Ada 2005, it will be illegal in Ada 95.)
25574 So instead we write
25576 @smallexample @c ada
25577 @b{procedure} Insert @b{is} @b{separate};
25578 @end smallexample
25580 @noindent
25581 Then we have two files for the subunit @code{Insert}, with the two sets of
25582 code.
25583 If the package containing this is called @code{File_Queries}, then we might
25584 have two files
25586 @itemize @bullet
25587 @item    @file{file_queries-insert-2005.adb}
25588 @item    @file{file_queries-insert-95.adb}
25589 @end itemize
25591 @noindent
25592 and the build script renames the appropriate file to
25594 @smallexample
25595 file_queries-insert.adb
25596 @end smallexample
25598 @noindent
25599 and then carries out the compilation.
25601 This can also be done with project files' naming schemes. For example:
25603 @smallexample @c project
25604 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25605 @end smallexample
25607 @noindent
25608 Note also that with project files it is desirable to use a different extension
25609 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25610 conflict may arise through another commonly used feature: to declare as part
25611 of the project a set of directories containing all the sources obeying the
25612 default naming scheme.
25614 The use of alternative units is certainly feasible in all situations,
25615 and for example the Ada part of the GNAT run-time is conditionalized
25616 based on the target architecture using this approach. As a specific example,
25617 consider the implementation of the AST feature in VMS. There is one
25618 spec:
25620 @smallexample
25621 s-asthan.ads
25622 @end smallexample
25624 @noindent
25625 which is the same for all architectures, and three bodies:
25627 @table @file
25628 @item    s-asthan.adb
25629 used for all non-VMS operating systems
25630 @item    s-asthan-vms-alpha.adb
25631 used for VMS on the Alpha
25632 @item    s-asthan-vms-ia64.adb
25633 used for VMS on the ia64
25634 @end table
25636 @noindent
25637 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25638 this operating system feature is not available, and the two remaining
25639 versions interface with the corresponding versions of VMS to provide
25640 VMS-compatible AST handling. The GNAT build script knows the architecture
25641 and operating system, and automatically selects the right version,
25642 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25644 Another style for arranging alternative implementations is through Ada's
25645 access-to-subprogram facility.
25646 In case some functionality is to be conditionally included,
25647 you can declare an access-to-procedure variable @code{Ref} that is initialized
25648 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25649 when appropriate.
25650 In some library package, set @code{Ref} to @code{Proc'Access} for some
25651 procedure @code{Proc} that performs the relevant processing.
25652 The initialization only occurs if the library package is included in the
25653 program.
25654 The same idea can also be implemented using tagged types and dispatching
25655 calls.
25658 @node Preprocessing
25659 @section Preprocessing
25660 @cindex Preprocessing
25662 @noindent
25663 Although it is quite possible to conditionalize code without the use of
25664 C-style preprocessing, as described earlier in this section, it is
25665 nevertheless convenient in some cases to use the C approach. Moreover,
25666 older Ada compilers have often provided some preprocessing capability,
25667 so legacy code may depend on this approach, even though it is not
25668 standard.
25670 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25671 extent on the various preprocessors that have been used
25672 with legacy code on other compilers, to enable easier transition).
25674 The preprocessor may be used in two separate modes. It can be used quite
25675 separately from the compiler, to generate a separate output source file
25676 that is then fed to the compiler as a separate step. This is the
25677 @code{gnatprep} utility, whose use is fully described in
25678 @ref{Preprocessing with gnatprep}.
25679 @cindex @code{gnatprep}
25681 The preprocessing language allows such constructs as
25683 @smallexample
25684 @group
25685 #if DEBUG or else (PRIORITY > 4) then
25686    bunch of declarations
25687 #else
25688    completely different bunch of declarations
25689 #end if;
25690 @end group
25691 @end smallexample
25693 @noindent
25694 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25695 defined either on the command line or in a separate file.
25697 The other way of running the preprocessor is even closer to the C style and
25698 often more convenient. In this approach the preprocessing is integrated into
25699 the compilation process. The compiler is fed the preprocessor input which
25700 includes @code{#if} lines etc, and then the compiler carries out the
25701 preprocessing internally and processes the resulting output.
25702 For more details on this approach, see @ref{Integrated Preprocessing}.
25705 @c *******************************
25706 @node Inline Assembler
25707 @appendix Inline Assembler
25708 @c *******************************
25710 @noindent
25711 If you need to write low-level software that interacts directly
25712 with the hardware, Ada provides two ways to incorporate assembly
25713 language code into your program.  First, you can import and invoke
25714 external routines written in assembly language, an Ada feature fully
25715 supported by GNAT@.  However, for small sections of code it may be simpler
25716 or more efficient to include assembly language statements directly
25717 in your Ada source program, using the facilities of the implementation-defined
25718 package @code{System.Machine_Code}, which incorporates the gcc
25719 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25720 including the following:
25722 @itemize @bullet
25723 @item No need to use non-Ada tools
25724 @item Consistent interface over different targets
25725 @item Automatic usage of the proper calling conventions
25726 @item Access to Ada constants and variables
25727 @item Definition of intrinsic routines
25728 @item Possibility of inlining a subprogram comprising assembler code
25729 @item Code optimizer can take Inline Assembler code into account
25730 @end itemize
25732 This chapter presents a series of examples to show you how to use
25733 the Inline Assembler.  Although it focuses on the Intel x86,
25734 the general approach applies also to other processors.
25735 It is assumed that you are familiar with Ada
25736 and with assembly language programming.
25738 @menu
25739 * Basic Assembler Syntax::
25740 * A Simple Example of Inline Assembler::
25741 * Output Variables in Inline Assembler::
25742 * Input Variables in Inline Assembler::
25743 * Inlining Inline Assembler Code::
25744 * Other Asm Functionality::
25745 @end menu
25747 @c ---------------------------------------------------------------------------
25748 @node Basic Assembler Syntax
25749 @section Basic Assembler Syntax
25751 @noindent
25752 The assembler used by GNAT and gcc is based not on the Intel assembly
25753 language, but rather on a language that descends from the AT&T Unix
25754 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25755 The following table summarizes the main features of @emph{as} syntax
25756 and points out the differences from the Intel conventions.
25757 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25758 pre-processor) documentation for further information.
25760 @table @asis
25761 @item Register names
25762 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25764 Intel: No extra punctuation; for example @code{eax}
25766 @item Immediate operand
25767 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25769 Intel: No extra punctuation; for example @code{4}
25771 @item Address
25772 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25774 Intel: No extra punctuation; for example @code{loc}
25776 @item Memory contents
25777 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25779 Intel: Square brackets; for example @code{[loc]}
25781 @item Register contents
25782 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25784 Intel: Square brackets; for example @code{[eax]}
25786 @item Hexadecimal numbers
25787 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25789 Intel: Trailing ``h''; for example @code{A0h}
25791 @item Operand size
25792 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25793 a 16-bit word
25795 Intel: Implicit, deduced by assembler; for example @code{mov}
25797 @item Instruction repetition
25798 gcc / @emph{as}: Split into two lines; for example
25800 @code{rep}
25802 @code{stosl}
25804 Intel: Keep on one line; for example @code{rep stosl}
25806 @item Order of operands
25807 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25809 Intel: Destination first; for example @code{mov eax, 4}
25810 @end table
25812 @c ---------------------------------------------------------------------------
25813 @node A Simple Example of Inline Assembler
25814 @section A Simple Example of Inline Assembler
25816 @noindent
25817 The following example will generate a single assembly language statement,
25818 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25819 the example will be useful in illustrating the basics of
25820 the Inline Assembler facility.
25822 @smallexample @c ada
25823 @group
25824 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
25825 @b{procedure} Nothing @b{is}
25826 @b{begin}
25827    Asm ("nop");
25828 @b{end} Nothing;
25829 @end group
25830 @end smallexample
25832 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25833 here it takes one parameter, a @emph{template string} that must be a static
25834 expression and that will form the generated instruction.
25835 @code{Asm} may be regarded as a compile-time procedure that parses
25836 the template string and additional parameters (none here),
25837 from which it generates a sequence of assembly language instructions.
25839 The examples in this chapter will illustrate several of the forms
25840 for invoking @code{Asm}; a complete specification of the syntax
25841 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25842 Manual}.
25844 Under the standard GNAT conventions, the @code{Nothing} procedure
25845 should be in a file named @file{nothing.adb}.
25846 You can build the executable in the usual way:
25847 @smallexample
25848 gnatmake nothing
25849 @end smallexample
25850 However, the interesting aspect of this example is not its run-time behavior
25851 but rather the generated assembly code.
25852 To see this output, invoke the compiler as follows:
25853 @smallexample
25854    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25855 @end smallexample
25856 where the options are:
25858 @table @code
25859 @item -c
25860 compile only (no bind or link)
25861 @item -S
25862 generate assembler listing
25863 @item -fomit-frame-pointer
25864 do not set up separate stack frames
25865 @item -gnatp
25866 do not add runtime checks
25867 @end table
25869 This gives a human-readable assembler version of the code. The resulting
25870 file will have the same name as the Ada source file, but with a @code{.s}
25871 extension. In our example, the file @file{nothing.s} has the following
25872 contents:
25874 @smallexample
25875 @group
25876 .file "nothing.adb"
25877 gcc2_compiled.:
25878 ___gnu_compiled_ada:
25879 .text
25880    .align 4
25881 .globl __ada_nothing
25882 __ada_nothing:
25883 #APP
25884    nop
25885 #NO_APP
25886    jmp L1
25887    .align 2,0x90
25889    ret
25890 @end group
25891 @end smallexample
25893 The assembly code you included is clearly indicated by
25894 the compiler, between the @code{#APP} and @code{#NO_APP}
25895 delimiters. The character before the 'APP' and 'NOAPP'
25896 can differ on different targets. For example, GNU/Linux uses '#APP' while
25897 on NT you will see '/APP'.
25899 If you make a mistake in your assembler code (such as using the
25900 wrong size modifier, or using a wrong operand for the instruction) GNAT
25901 will report this error in a temporary file, which will be deleted when
25902 the compilation is finished.  Generating an assembler file will help
25903 in such cases, since you can assemble this file separately using the
25904 @emph{as} assembler that comes with gcc.
25906 Assembling the file using the command
25908 @smallexample
25909 as @file{nothing.s}
25910 @end smallexample
25911 @noindent
25912 will give you error messages whose lines correspond to the assembler
25913 input file, so you can easily find and correct any mistakes you made.
25914 If there are no errors, @emph{as} will generate an object file
25915 @file{nothing.out}.
25917 @c ---------------------------------------------------------------------------
25918 @node Output Variables in Inline Assembler
25919 @section Output Variables in Inline Assembler
25921 @noindent
25922 The examples in this section, showing how to access the processor flags,
25923 illustrate how to specify the destination operands for assembly language
25924 statements.
25926 @smallexample @c ada
25927 @group
25928 @b{with} Interfaces; @b{use} Interfaces;
25929 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
25930 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
25931 @b{procedure} Get_Flags @b{is}
25932    Flags : Unsigned_32;
25933    @b{use} ASCII;
25934 @b{begin}
25935    Asm ("pushfl"          & LF & HT & --@i{ push flags on stack}
25936         "popl %%eax"      & LF & HT & --@i{ load eax with flags}
25937         "movl %%eax, %0",             --@i{ store flags in variable}
25938         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25939    Put_Line ("Flags register:" & Flags'Img);
25940 @b{end} Get_Flags;
25941 @end group
25942 @end smallexample
25944 In order to have a nicely aligned assembly listing, we have separated
25945 multiple assembler statements in the Asm template string with linefeed
25946 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25947 The resulting section of the assembly output file is:
25949 @smallexample
25950 @group
25951 #APP
25952    pushfl
25953    popl %eax
25954    movl %eax, -40(%ebp)
25955 #NO_APP
25956 @end group
25957 @end smallexample
25959 It would have been legal to write the Asm invocation as:
25961 @smallexample
25962 Asm ("pushfl popl %%eax movl %%eax, %0")
25963 @end smallexample
25965 but in the generated assembler file, this would come out as:
25967 @smallexample
25968 #APP
25969    pushfl popl %eax movl %eax, -40(%ebp)
25970 #NO_APP
25971 @end smallexample
25973 which is not so convenient for the human reader.
25975 We use Ada comments
25976 at the end of each line to explain what the assembler instructions
25977 actually do.  This is a useful convention.
25979 When writing Inline Assembler instructions, you need to precede each register
25980 and variable name with a percent sign.  Since the assembler already requires
25981 a percent sign at the beginning of a register name, you need two consecutive
25982 percent signs for such names in the Asm template string, thus @code{%%eax}.
25983 In the generated assembly code, one of the percent signs will be stripped off.
25985 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25986 variables: operands you later define using @code{Input} or @code{Output}
25987 parameters to @code{Asm}.
25988 An output variable is illustrated in
25989 the third statement in the Asm template string:
25990 @smallexample
25991 movl %%eax, %0
25992 @end smallexample
25993 The intent is to store the contents of the eax register in a variable that can
25994 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25995 necessarily work, since the compiler might optimize by using a register
25996 to hold Flags, and the expansion of the @code{movl} instruction would not be
25997 aware of this optimization.  The solution is not to store the result directly
25998 but rather to advise the compiler to choose the correct operand form;
25999 that is the purpose of the @code{%0} output variable.
26001 Information about the output variable is supplied in the @code{Outputs}
26002 parameter to @code{Asm}:
26003 @smallexample
26004 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26005 @end smallexample
26007 The output is defined by the @code{Asm_Output} attribute of the target type;
26008 the general format is
26009 @smallexample
26010 Type'Asm_Output (constraint_string, variable_name)
26011 @end smallexample
26013 The constraint string directs the compiler how
26014 to store/access the associated variable.  In the example
26015 @smallexample
26016 Unsigned_32'Asm_Output ("=m", Flags);
26017 @end smallexample
26018 the @code{"m"} (memory) constraint tells the compiler that the variable
26019 @code{Flags} should be stored in a memory variable, thus preventing
26020 the optimizer from keeping it in a register.  In contrast,
26021 @smallexample
26022 Unsigned_32'Asm_Output ("=r", Flags);
26023 @end smallexample
26024 uses the @code{"r"} (register) constraint, telling the compiler to
26025 store the variable in a register.
26027 If the constraint is preceded by the equal character (@strong{=}), it tells
26028 the compiler that the variable will be used to store data into it.
26030 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
26031 allowing the optimizer to choose whatever it deems best.
26033 There are a fairly large number of constraints, but the ones that are
26034 most useful (for the Intel x86 processor) are the following:
26036 @table @code
26037 @item =
26038 output constraint
26039 @item g
26040 global (i.e.@: can be stored anywhere)
26041 @item m
26042 in memory
26043 @item I
26044 a constant
26045 @item a
26046 use eax
26047 @item b
26048 use ebx
26049 @item c
26050 use ecx
26051 @item d
26052 use edx
26053 @item S
26054 use esi
26055 @item D
26056 use edi
26057 @item r
26058 use one of eax, ebx, ecx or edx
26059 @item q
26060 use one of eax, ebx, ecx, edx, esi or edi
26061 @end table
26063 The full set of constraints is described in the gcc and @emph{as}
26064 documentation; note that it is possible to combine certain constraints
26065 in one constraint string.
26067 You specify the association of an output variable with an assembler operand
26068 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
26069 integer.  Thus in
26070 @smallexample @c ada
26071 @group
26072 Asm ("pushfl"          & LF & HT & --@i{ push flags on stack}
26073      "popl %%eax"      & LF & HT & --@i{ load eax with flags}
26074      "movl %%eax, %0",             --@i{ store flags in variable}
26075      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26076 @end group
26077 @end smallexample
26078 @noindent
26079 @code{%0} will be replaced in the expanded code by the appropriate operand,
26080 whatever
26081 the compiler decided for the @code{Flags} variable.
26083 In general, you may have any number of output variables:
26084 @itemize @bullet
26085 @item
26086 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26087 @item
26088 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26089 of @code{Asm_Output} attributes
26090 @end itemize
26092 For example:
26093 @smallexample @c ada
26094 @group
26095 Asm ("movl %%eax, %0" & LF & HT &
26096      "movl %%ebx, %1" & LF & HT &
26097      "movl %%ecx, %2",
26098      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --@i{  %0 = Var_A}
26099                  Unsigned_32'Asm_Output ("=g", Var_B),   --@i{  %1 = Var_B}
26100                  Unsigned_32'Asm_Output ("=g", Var_C))); --@i{  %2 = Var_C}
26101 @end group
26102 @end smallexample
26103 @noindent
26104 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26105 in the Ada program.
26107 As a variation on the @code{Get_Flags} example, we can use the constraints
26108 string to direct the compiler to store the eax register into the @code{Flags}
26109 variable, instead of including the store instruction explicitly in the
26110 @code{Asm} template string:
26112 @smallexample @c ada
26113 @group
26114 @b{with} Interfaces; @b{use} Interfaces;
26115 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26116 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26117 @b{procedure} Get_Flags_2 @b{is}
26118    Flags : Unsigned_32;
26119    @b{use} ASCII;
26120 @b{begin}
26121    Asm ("pushfl"      & LF & HT & --@i{ push flags on stack}
26122         "popl %%eax",             --@i{ save flags in eax}
26123         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26124    Put_Line ("Flags register:" & Flags'Img);
26125 @b{end} Get_Flags_2;
26126 @end group
26127 @end smallexample
26129 @noindent
26130 The @code{"a"} constraint tells the compiler that the @code{Flags}
26131 variable will come from the eax register. Here is the resulting code:
26133 @smallexample
26134 @group
26135 #APP
26136    pushfl
26137    popl %eax
26138 #NO_APP
26139    movl %eax,-40(%ebp)
26140 @end group
26141 @end smallexample
26143 @noindent
26144 The compiler generated the store of eax into Flags after
26145 expanding the assembler code.
26147 Actually, there was no need to pop the flags into the eax register;
26148 more simply, we could just pop the flags directly into the program variable:
26150 @smallexample @c ada
26151 @group
26152 @b{with} Interfaces; @b{use} Interfaces;
26153 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26154 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26155 @b{procedure} Get_Flags_3 @b{is}
26156    Flags : Unsigned_32;
26157    @b{use} ASCII;
26158 @b{begin}
26159    Asm ("pushfl"  & LF & HT & --@i{ push flags on stack}
26160         "pop %0",             --@i{ save flags in Flags}
26161         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26162    Put_Line ("Flags register:" & Flags'Img);
26163 @b{end} Get_Flags_3;
26164 @end group
26165 @end smallexample
26167 @c ---------------------------------------------------------------------------
26168 @node Input Variables in Inline Assembler
26169 @section Input Variables in Inline Assembler
26171 @noindent
26172 The example in this section illustrates how to specify the source operands
26173 for assembly language statements.
26174 The program simply increments its input value by 1:
26176 @smallexample @c ada
26177 @group
26178 @b{with} Interfaces; @b{use} Interfaces;
26179 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26180 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26181 @b{procedure} Increment @b{is}
26183    @b{function} Incr (Value : Unsigned_32) @b{return} Unsigned_32 @b{is}
26184       Result : Unsigned_32;
26185    @b{begin}
26186       Asm ("incl %0",
26187            Outputs => Unsigned_32'Asm_Output ("=a", Result),
26188            Inputs  => Unsigned_32'Asm_Input ("a", Value));
26189       @b{return} Result;
26190    @b{end} Incr;
26192    Value : Unsigned_32;
26194 @b{begin}
26195    Value := 5;
26196    Put_Line ("Value before is" & Value'Img);
26197    Value := Incr (Value);
26198    Put_Line ("Value after is" & Value'Img);
26199 @b{end} Increment;
26200 @end group
26201 @end smallexample
26203 The @code{Outputs} parameter to @code{Asm} specifies
26204 that the result will be in the eax register and that it is to be stored
26205 in the @code{Result} variable.
26207 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26208 but with an @code{Asm_Input} attribute.
26209 The @code{"="} constraint, indicating an output value, is not present.
26211 You can have multiple input variables, in the same way that you can have more
26212 than one output variable.
26214 The parameter count (%0, %1) etc, still starts at the first output statement,
26215 and continues with the input statements.
26217 Just as the @code{Outputs} parameter causes the register to be stored into the
26218 target variable after execution of the assembler statements, so does the
26219 @code{Inputs} parameter cause its variable to be loaded into the register
26220 before execution of the assembler statements.
26222 Thus the effect of the @code{Asm} invocation is:
26223 @enumerate
26224 @item load the 32-bit value of @code{Value} into eax
26225 @item execute the @code{incl %eax} instruction
26226 @item store the contents of eax into the @code{Result} variable
26227 @end enumerate
26229 The resulting assembler file (with @option{-O2} optimization) contains:
26230 @smallexample
26231 @group
26232 _increment__incr.1:
26233    subl $4,%esp
26234    movl 8(%esp),%eax
26235 #APP
26236    incl %eax
26237 #NO_APP
26238    movl %eax,%edx
26239    movl %ecx,(%esp)
26240    addl $4,%esp
26241    ret
26242 @end group
26243 @end smallexample
26245 @c ---------------------------------------------------------------------------
26246 @node Inlining Inline Assembler Code
26247 @section Inlining Inline Assembler Code
26249 @noindent
26250 For a short subprogram such as the @code{Incr} function in the previous
26251 section, the overhead of the call and return (creating / deleting the stack
26252 frame) can be significant, compared to the amount of code in the subprogram
26253 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26254 which directs the compiler to expand invocations of the subprogram at the
26255 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26256 Here is the resulting program:
26258 @smallexample @c ada
26259 @group
26260 @b{with} Interfaces; @b{use} Interfaces;
26261 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26262 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26263 @b{procedure} Increment_2 @b{is}
26265    @b{function} Incr (Value : Unsigned_32) @b{return} Unsigned_32 @b{is}
26266       Result : Unsigned_32;
26267    @b{begin}
26268       Asm ("incl %0",
26269            Outputs => Unsigned_32'Asm_Output ("=a", Result),
26270            Inputs  => Unsigned_32'Asm_Input ("a", Value));
26271       @b{return} Result;
26272    @b{end} Incr;
26273    @b{pragma} Inline (Increment);
26275    Value : Unsigned_32;
26277 @b{begin}
26278    Value := 5;
26279    Put_Line ("Value before is" & Value'Img);
26280    Value := Increment (Value);
26281    Put_Line ("Value after is" & Value'Img);
26282 @b{end} Increment_2;
26283 @end group
26284 @end smallexample
26286 Compile the program with both optimization (@option{-O2}) and inlining
26287 (@option{-gnatn}) enabled.
26289 The @code{Incr} function is still compiled as usual, but at the
26290 point in @code{Increment} where our function used to be called:
26292 @smallexample
26293 @group
26294 pushl %edi
26295 call _increment__incr.1
26296 @end group
26297 @end smallexample
26299 @noindent
26300 the code for the function body directly appears:
26302 @smallexample
26303 @group
26304 movl %esi,%eax
26305 #APP
26306    incl %eax
26307 #NO_APP
26308    movl %eax,%edx
26309 @end group
26310 @end smallexample
26312 @noindent
26313 thus saving the overhead of stack frame setup and an out-of-line call.
26315 @c ---------------------------------------------------------------------------
26316 @node Other Asm Functionality
26317 @section Other @code{Asm} Functionality
26319 @noindent
26320 This section describes two important parameters to the @code{Asm}
26321 procedure: @code{Clobber}, which identifies register usage;
26322 and @code{Volatile}, which inhibits unwanted optimizations.
26324 @menu
26325 * The Clobber Parameter::
26326 * The Volatile Parameter::
26327 @end menu
26329 @c ---------------------------------------------------------------------------
26330 @node The Clobber Parameter
26331 @subsection The @code{Clobber} Parameter
26333 @noindent
26334 One of the dangers of intermixing assembly language and a compiled language
26335 such as Ada is that the compiler needs to be aware of which registers are
26336 being used by the assembly code.  In some cases, such as the earlier examples,
26337 the constraint string is sufficient to indicate register usage (e.g.,
26338 @code{"a"} for
26339 the eax register).  But more generally, the compiler needs an explicit
26340 identification of the registers that are used by the Inline Assembly
26341 statements.
26343 Using a register that the compiler doesn't know about
26344 could be a side effect of an instruction (like @code{mull}
26345 storing its result in both eax and edx).
26346 It can also arise from explicit register usage in your
26347 assembly code; for example:
26348 @smallexample
26349 @group
26350 Asm ("movl %0, %%ebx" & LF & HT &
26351      "movl %%ebx, %1",
26352      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26353      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
26354 @end group
26355 @end smallexample
26356 @noindent
26357 where the compiler (since it does not analyze the @code{Asm} template string)
26358 does not know you are using the ebx register.
26360 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26361 to identify the registers that will be used by your assembly code:
26363 @smallexample
26364 @group
26365 Asm ("movl %0, %%ebx" & LF & HT &
26366      "movl %%ebx, %1",
26367      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26368      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26369      Clobber => "ebx");
26370 @end group
26371 @end smallexample
26373 The Clobber parameter is a static string expression specifying the
26374 register(s) you are using.  Note that register names are @emph{not} prefixed
26375 by a percent sign. Also, if more than one register is used then their names
26376 are separated by commas; e.g., @code{"eax, ebx"}
26378 The @code{Clobber} parameter has several additional uses:
26379 @enumerate
26380 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26381 @item Use ``register'' name @code{memory} if you changed a memory location
26382 @end enumerate
26384 @c ---------------------------------------------------------------------------
26385 @node The Volatile Parameter
26386 @subsection The @code{Volatile} Parameter
26387 @cindex Volatile parameter
26389 @noindent
26390 Compiler optimizations in the presence of Inline Assembler may sometimes have
26391 unwanted effects.  For example, when an @code{Asm} invocation with an input
26392 variable is inside a loop, the compiler might move the loading of the input
26393 variable outside the loop, regarding it as a one-time initialization.
26395 If this effect is not desired, you can disable such optimizations by setting
26396 the @code{Volatile} parameter to @code{True}; for example:
26398 @smallexample @c ada
26399 @group
26400 Asm ("movl %0, %%ebx" & LF & HT &
26401      "movl %%ebx, %1",
26402      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26403      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26404      Clobber  => "ebx",
26405      Volatile => True);
26406 @end group
26407 @end smallexample
26409 By default, @code{Volatile} is set to @code{False} unless there is no
26410 @code{Outputs} parameter.
26412 Although setting @code{Volatile} to @code{True} prevents unwanted
26413 optimizations, it will also disable other optimizations that might be
26414 important for efficiency. In general, you should set @code{Volatile}
26415 to @code{True} only if the compiler's optimizations have created
26416 problems.
26417 @c END OF INLINE ASSEMBLER CHAPTER
26418 @c ===============================
26421 @c *****************************************
26422 @c Writing Portable Fixed-Point Declarations
26423 @c *****************************************
26424 @node Writing Portable Fixed-Point Declarations
26425 @appendix Writing Portable Fixed-Point Declarations
26426 @cindex Fixed-point types (writing portable declarations)
26428 @noindent
26429 The Ada Reference Manual gives an implementation freedom to choose bounds
26430 that are narrower by @code{Small} from the given bounds.
26431 For example, if we write
26433 @smallexample @c ada
26434    type F1 is delta 1.0 range -128.0 .. +128.0;
26435 @end smallexample
26437 @noindent
26438 then the implementation is allowed to choose -128.0 .. +127.0 if it
26439 likes, but is not required to do so.
26441 This leads to possible portability problems, so let's have a closer
26442 look at this, and figure out how to avoid these problems.
26444 First, why does this freedom exist, and why would an implementation
26445 take advantage of it? To answer this, take a closer look at the type
26446 declaration for @code{F1} above. If the compiler uses the given bounds,
26447 it would need 9 bits to hold the largest positive value (and typically
26448 that means 16 bits on all machines). But if the implementation chooses
26449 the +127.0 bound then it can fit values of the type in 8 bits.
26451 Why not make the user write +127.0 if that's what is wanted?
26452 The rationale is that if you are thinking of fixed point
26453 as a kind of ``poor man's floating-point'', then you don't want
26454 to be thinking about the scaled integers that are used in its
26455 representation. Let's take another example:
26457 @smallexample @c ada
26458    type F2 is delta 2.0**(-15) range -1.0 .. +1.0;
26459 @end smallexample
26461 @noindent
26462 Looking at this declaration, it seems casually as though
26463 it should fit in 16 bits, but again that extra positive value
26464 +1.0 has the scaled integer equivalent of 2**15 which is one too
26465 big for signed 16 bits. The implementation can treat this as:
26467 @smallexample @c ada
26468    type F2 is delta 2.0**(-15) range -1.0 .. +1.0-(2.0**(-15));
26469 @end smallexample
26471 @noindent
26472 and the Ada language design team felt that this was too annoying
26473 to require. We don't need to debate this decision at this point,
26474 since it is well established (the rule about narrowing the ranges
26475 dates to Ada 83).
26477 But the important point is that an implementation is not required
26478 to do this narrowing, so we have a potential portability problem.
26479 We could imagine three types of implementation:
26481 @enumerate a
26482 @item
26483 those that narrow the range automatically if they can figure
26484 out that the narrower range will allow storage in a smaller machine unit,
26486 @item
26487 those that will narrow only if forced to by a @code{'Size} clause, and
26489 @item
26490 those that will never narrow.
26491 @end enumerate
26493 @noindent
26494 Now if we are language theoreticians, we can imagine a fourth
26495 approach: is to narrow all the time, e.g. to treat
26497 @smallexample @c ada
26498    type F3 is delta 1.0 range -10.0 .. +23.0;
26499 @end smallexample
26501 @noindent
26502 as though it had been written:
26504 @smallexample @c ada
26505    type F3 is delta 1.0 range -9.0 .. +22.0;
26506 @end smallexample
26508 @noindent
26509 But although technically allowed, such a behavior would be hostile and silly,
26510 and no real compiler would do this. All real compilers will fall into one of
26511 the categories (a), (b) or (c) above.
26513 So, how do you get the compiler to do what you want? The answer is give the
26514 actual bounds you want, and then use a @code{'Small} clause and a
26515 @code{'Size} clause to absolutely pin down what the compiler does.
26516 E.g., for @code{F2} above, we will write:
26518 @smallexample @c ada
26519 @group
26520    My_Small : constant := 2.0**(-15);
26521    My_First : constant := -1.0;
26522    My_Last  : constant := +1.0 - My_Small;
26524    type F2 is delta My_Small range My_First .. My_Last;
26525 @end group
26526 @end smallexample
26528 @noindent
26529 and then add
26531 @smallexample @c ada
26532 @group
26533    for F2'Small use my_Small;
26534    for F2'Size  use 16;
26535 @end group
26536 @end smallexample
26538 @noindent
26539 In practice all compilers will do the same thing here and will give you
26540 what you want, so the above declarations are fully portable. If you really
26541 want to play language lawyer and guard against ludicrous behavior by the
26542 compiler you could add
26544 @smallexample @c ada
26545 @group
26546    Test1 : constant := 1 / Boolean'Pos (F2'First = My_First);
26547    Test2 : constant := 1 / Boolean'Pos (F2'Last  = My_Last);
26548 @end group
26549 @end smallexample
26551 @noindent
26552 One or other or both are allowed to be illegal if the compiler is
26553 behaving in a silly manner, but at least the silly compiler will not
26554 get away with silently messing with your (very clear) intentions.
26556 If you follow this scheme you will be guaranteed that your fixed-point
26557 types will be portable.
26560 @c ***********************************
26561 @c * Compatibility and Porting Guide *
26562 @c ***********************************
26563 @node Compatibility and Porting Guide
26564 @appendix Compatibility and Porting Guide
26566 @noindent
26567 This chapter describes the compatibility issues that may arise between
26568 GNAT and other Ada compilation systems (including those for Ada 83),
26569 and shows how GNAT can expedite porting
26570 applications developed in other Ada environments.
26572 @menu
26573 * Compatibility with Ada 83::
26574 * Compatibility between Ada 95 and Ada 2005::
26575 * Implementation-dependent characteristics::
26576 * Compatibility with Other Ada Systems::
26577 * Representation Clauses::
26578 @c Brief section is only in non-VMS version
26579 @c Full chapter is in VMS version
26580 * Compatibility with HP Ada 83::
26581 @end menu
26583 @node Compatibility with Ada 83
26584 @section Compatibility with Ada 83
26585 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26587 @noindent
26588 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
26589 particular, the design intention was that the difficulties associated
26590 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26591 that occur when moving from one Ada 83 system to another.
26593 However, there are a number of points at which there are minor
26594 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26595 full details of these issues,
26596 and should be consulted for a complete treatment.
26597 In practice the
26598 following subsections treat the most likely issues to be encountered.
26600 @menu
26601 * Legal Ada 83 programs that are illegal in Ada 95::
26602 * More deterministic semantics::
26603 * Changed semantics::
26604 * Other language compatibility issues::
26605 @end menu
26607 @node Legal Ada 83 programs that are illegal in Ada 95
26608 @subsection Legal Ada 83 programs that are illegal in Ada 95
26610 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26611 Ada 95 and thus also in Ada 2005:
26613 @table @emph
26614 @item Character literals
26615 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26616 @code{Wide_Character} as a new predefined character type, some uses of
26617 character literals that were legal in Ada 83 are illegal in Ada 95.
26618 For example:
26619 @smallexample @c ada
26620    @b{for} Char @b{in} 'A' .. 'Z' @b{loop} @dots{} @b{end} @b{loop};
26621 @end smallexample
26623 @noindent
26624 The problem is that @code{'A'} and @code{'Z'} could be from either
26625 @code{Character} or @code{Wide_Character}.  The simplest correction
26626 is to make the type explicit; e.g.:
26627 @smallexample @c ada
26628    @b{for} Char @b{in} Character @b{range} 'A' .. 'Z' @b{loop} @dots{} @b{end} @b{loop};
26629 @end smallexample
26631 @item New reserved words
26632 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26633 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26634 Existing Ada 83 code using any of these identifiers must be edited to
26635 use some alternative name.
26637 @item Freezing rules
26638 The rules in Ada 95 are slightly different with regard to the point at
26639 which entities are frozen, and representation pragmas and clauses are
26640 not permitted past the freeze point.  This shows up most typically in
26641 the form of an error message complaining that a representation item
26642 appears too late, and the appropriate corrective action is to move
26643 the item nearer to the declaration of the entity to which it refers.
26645 A particular case is that representation pragmas
26646 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26647 declaration must be introduced to which the pragma can be applied.
26649 @item Optional bodies for library packages
26650 In Ada 83, a package that did not require a package body was nevertheless
26651 allowed to have one.  This lead to certain surprises in compiling large
26652 systems (situations in which the body could be unexpectedly ignored by the
26653 binder).  In Ada 95, if a package does not require a body then it is not
26654 permitted to have a body.  To fix this problem, simply remove a redundant
26655 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26656 into the spec that makes the body required.  One approach is to add a private
26657 part to the package declaration (if necessary), and define a parameterless
26658 procedure called @code{Requires_Body}, which must then be given a dummy
26659 procedure body in the package body, which then becomes required.
26660 Another approach (assuming that this does not introduce elaboration
26661 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26662 since one effect of this pragma is to require the presence of a package body.
26664 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26665 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26666 @code{Constraint_Error}.
26667 This means that it is illegal to have separate exception handlers for
26668 the two exceptions.  The fix is simply to remove the handler for the
26669 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26670 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26672 @item Indefinite subtypes in generics
26673 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26674 as the actual for a generic formal private type, but then the instantiation
26675 would be illegal if there were any instances of declarations of variables
26676 of this type in the generic body.  In Ada 95, to avoid this clear violation
26677 of the methodological principle known as the ``contract model'',
26678 the generic declaration explicitly indicates whether
26679 or not such instantiations are permitted.  If a generic formal parameter
26680 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26681 subtype name, then it can be instantiated with indefinite types, but no
26682 stand-alone variables can be declared of this type.  Any attempt to declare
26683 such a variable will result in an illegality at the time the generic is
26684 declared.  If the @code{(<>)} notation is not used, then it is illegal
26685 to instantiate the generic with an indefinite type.
26686 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26687 It will show up as a compile time error, and
26688 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26689 @end table
26691 @node More deterministic semantics
26692 @subsection More deterministic semantics
26694 @table @emph
26695 @item Conversions
26696 Conversions from real types to integer types round away from 0.  In Ada 83
26697 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26698 implementation freedom was intended to support unbiased rounding in
26699 statistical applications, but in practice it interfered with portability.
26700 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26701 is required.  Numeric code may be affected by this change in semantics.
26702 Note, though, that this issue is no worse than already existed in Ada 83
26703 when porting code from one vendor to another.
26705 @item Tasking
26706 The Real-Time Annex introduces a set of policies that define the behavior of
26707 features that were implementation dependent in Ada 83, such as the order in
26708 which open select branches are executed.
26709 @end table
26711 @node Changed semantics
26712 @subsection Changed semantics
26714 @noindent
26715 The worst kind of incompatibility is one where a program that is legal in
26716 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26717 possible in Ada 83.  Fortunately this is extremely rare, but the one
26718 situation that you should be alert to is the change in the predefined type
26719 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26721 @table @emph
26722 @item Range of type @code{Character}
26723 The range of @code{Standard.Character} is now the full 256 characters
26724 of Latin-1, whereas in most Ada 83 implementations it was restricted
26725 to 128 characters. Although some of the effects of
26726 this change will be manifest in compile-time rejection of legal
26727 Ada 83 programs it is possible for a working Ada 83 program to have
26728 a different effect in Ada 95, one that was not permitted in Ada 83.
26729 As an example, the expression
26730 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26731 delivers @code{255} as its value.
26732 In general, you should look at the logic of any
26733 character-processing Ada 83 program and see whether it needs to be adapted
26734 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26735 character handling package that may be relevant if code needs to be adapted
26736 to account for the additional Latin-1 elements.
26737 The desirable fix is to
26738 modify the program to accommodate the full character set, but in some cases
26739 it may be convenient to define a subtype or derived type of Character that
26740 covers only the restricted range.
26741 @cindex Latin-1
26742 @end table
26744 @node Other language compatibility issues
26745 @subsection Other language compatibility issues
26747 @table @emph
26748 @item @option{-gnat83} switch
26749 All implementations of GNAT provide a switch that causes GNAT to operate
26750 in Ada 83 mode.  In this mode, some but not all compatibility problems
26751 of the type described above are handled automatically.  For example, the
26752 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26753 as identifiers as in Ada 83.
26754 However,
26755 in practice, it is usually advisable to make the necessary modifications
26756 to the program to remove the need for using this switch.
26757 See @ref{Compiling Different Versions of Ada}.
26759 @item Support for removed Ada 83 pragmas and attributes
26760 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26761 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26762 compilers are allowed, but not required, to implement these missing
26763 elements.  In contrast with some other compilers, GNAT implements all
26764 such pragmas and attributes, eliminating this compatibility concern.  These
26765 include @code{pragma Interface} and the floating point type attributes
26766 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26767 @end table
26770 @node Compatibility between Ada 95 and Ada 2005
26771 @section Compatibility between Ada 95 and Ada 2005
26772 @cindex Compatibility between Ada 95 and Ada 2005
26774 @noindent
26775 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26776 a number of incompatibilities. Several are enumerated below;
26777 for a complete description please see the
26778 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26779 @cite{Rationale for Ada 2005}.
26781 @table @emph
26782 @item New reserved words.
26783 The words @code{interface}, @code{overriding} and @code{synchronized} are
26784 reserved in Ada 2005.
26785 A pre-Ada 2005 program that uses any of these as an identifier will be
26786 illegal.
26788 @item New declarations in predefined packages.
26789 A number of packages in the predefined environment contain new declarations:
26790 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26791 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26792 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26793 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26794 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26795 If an Ada 95 program does a @code{with} and @code{use} of any of these
26796 packages, the new declarations may cause name clashes.
26798 @item Access parameters.
26799 A nondispatching subprogram with an access parameter cannot be renamed
26800 as a dispatching operation.  This was permitted in Ada 95.
26802 @item Access types, discriminants, and constraints.
26803 Rule changes in this area have led to some incompatibilities; for example,
26804 constrained subtypes of some access types are not permitted in Ada 2005.
26806 @item Aggregates for limited types.
26807 The allowance of aggregates for limited types in Ada 2005 raises the
26808 possibility of ambiguities in legal Ada 95 programs, since additional types
26809 now need to be considered in expression resolution.
26811 @item Fixed-point multiplication and division.
26812 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26813 were legal in Ada 95 and invoked the predefined versions of these operations,
26814 are now ambiguous.
26815 The ambiguity may be resolved either by applying a type conversion to the
26816 expression, or by explicitly invoking the operation from package
26817 @code{Standard}.
26819 @item Return-by-reference types.
26820 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26821 can declare a function returning a value from an anonymous access type.
26822 @end table
26825 @node Implementation-dependent characteristics
26826 @section Implementation-dependent characteristics
26827 @noindent
26828 Although the Ada language defines the semantics of each construct as
26829 precisely as practical, in some situations (for example for reasons of
26830 efficiency, or where the effect is heavily dependent on the host or target
26831 platform) the implementation is allowed some freedom.  In porting Ada 83
26832 code to GNAT, you need to be aware of whether / how the existing code
26833 exercised such implementation dependencies.  Such characteristics fall into
26834 several categories, and GNAT offers specific support in assisting the
26835 transition from certain Ada 83 compilers.
26837 @menu
26838 * Implementation-defined pragmas::
26839 * Implementation-defined attributes::
26840 * Libraries::
26841 * Elaboration order::
26842 * Target-specific aspects::
26843 @end menu
26845 @node Implementation-defined pragmas
26846 @subsection Implementation-defined pragmas
26848 @noindent
26849 Ada compilers are allowed to supplement the language-defined pragmas, and
26850 these are a potential source of non-portability.  All GNAT-defined pragmas
26851 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26852 Reference Manual}, and these include several that are specifically
26853 intended to correspond to other vendors' Ada 83 pragmas.
26854 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26855 For compatibility with HP Ada 83, GNAT supplies the pragmas
26856 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26857 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26858 and @code{Volatile}.
26859 Other relevant pragmas include @code{External} and @code{Link_With}.
26860 Some vendor-specific
26861 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26862 recognized, thus
26863 avoiding compiler rejection of units that contain such pragmas; they are not
26864 relevant in a GNAT context and hence are not otherwise implemented.
26866 @node Implementation-defined attributes
26867 @subsection Implementation-defined attributes
26869 Analogous to pragmas, the set of attributes may be extended by an
26870 implementation.  All GNAT-defined attributes are described in
26871 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26872 Manual}, and these include several that are specifically intended
26873 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26874 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26875 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26876 @code{Type_Class}.
26878 @node Libraries
26879 @subsection Libraries
26880 @noindent
26881 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26882 code uses vendor-specific libraries then there are several ways to manage
26883 this in Ada 95 or Ada 2005:
26884 @enumerate
26885 @item
26886 If the source code for the libraries (specs and bodies) are
26887 available, then the libraries can be migrated in the same way as the
26888 application.
26889 @item
26890 If the source code for the specs but not the bodies are
26891 available, then you can reimplement the bodies.
26892 @item
26893 Some features introduced by Ada 95 obviate the need for library support.  For
26894 example most Ada 83 vendors supplied a package for unsigned integers.  The
26895 Ada 95 modular type feature is the preferred way to handle this need, so
26896 instead of migrating or reimplementing the unsigned integer package it may
26897 be preferable to retrofit the application using modular types.
26898 @end enumerate
26900 @node Elaboration order
26901 @subsection Elaboration order
26902 @noindent
26903 The implementation can choose any elaboration order consistent with the unit
26904 dependency relationship.  This freedom means that some orders can result in
26905 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26906 to invoke a subprogram its body has been elaborated, or to instantiate a
26907 generic before the generic body has been elaborated.  By default GNAT
26908 attempts to choose a safe order (one that will not encounter access before
26909 elaboration problems) by implicitly inserting @code{Elaborate} or
26910 @code{Elaborate_All} pragmas where
26911 needed.  However, this can lead to the creation of elaboration circularities
26912 and a resulting rejection of the program by gnatbind.  This issue is
26913 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26914 In brief, there are several
26915 ways to deal with this situation:
26917 @itemize @bullet
26918 @item
26919 Modify the program to eliminate the circularities, e.g.@: by moving
26920 elaboration-time code into explicitly-invoked procedures
26921 @item
26922 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26923 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26924 @code{Elaborate_All}
26925 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26926 (by selectively suppressing elaboration checks via pragma
26927 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26928 @end itemize
26930 @node Target-specific aspects
26931 @subsection Target-specific aspects
26932 @noindent
26933 Low-level applications need to deal with machine addresses, data
26934 representations, interfacing with assembler code, and similar issues.  If
26935 such an Ada 83 application is being ported to different target hardware (for
26936 example where the byte endianness has changed) then you will need to
26937 carefully examine the program logic; the porting effort will heavily depend
26938 on the robustness of the original design.  Moreover, Ada 95 (and thus
26939 Ada 2005) are sometimes
26940 incompatible with typical Ada 83 compiler practices regarding implicit
26941 packing, the meaning of the Size attribute, and the size of access values.
26942 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26944 @node Compatibility with Other Ada Systems
26945 @section Compatibility with Other Ada Systems
26947 @noindent
26948 If programs avoid the use of implementation dependent and
26949 implementation defined features, as documented in the @cite{Ada
26950 Reference Manual}, there should be a high degree of portability between
26951 GNAT and other Ada systems.  The following are specific items which
26952 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26953 compilers, but do not affect porting code to GNAT@.
26954 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26955 the following issues may or may not arise for Ada 2005 programs
26956 when other compilers appear.)
26958 @table @emph
26959 @item Ada 83 Pragmas and Attributes
26960 Ada 95 compilers are allowed, but not required, to implement the missing
26961 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26962 GNAT implements all such pragmas and attributes, eliminating this as
26963 a compatibility concern, but some other Ada 95 compilers reject these
26964 pragmas and attributes.
26966 @item Specialized Needs Annexes
26967 GNAT implements the full set of special needs annexes.  At the
26968 current time, it is the only Ada 95 compiler to do so.  This means that
26969 programs making use of these features may not be portable to other Ada
26970 95 compilation systems.
26972 @item Representation Clauses
26973 Some other Ada 95 compilers implement only the minimal set of
26974 representation clauses required by the Ada 95 reference manual.  GNAT goes
26975 far beyond this minimal set, as described in the next section.
26976 @end table
26978 @node Representation Clauses
26979 @section Representation Clauses
26981 @noindent
26982 The Ada 83 reference manual was quite vague in describing both the minimal
26983 required implementation of representation clauses, and also their precise
26984 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26985 minimal set of capabilities required is still quite limited.
26987 GNAT implements the full required set of capabilities in
26988 Ada 95 and Ada 2005, but also goes much further, and in particular
26989 an effort has been made to be compatible with existing Ada 83 usage to the
26990 greatest extent possible.
26992 A few cases exist in which Ada 83 compiler behavior is incompatible with
26993 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26994 intentional or accidental dependence on specific implementation dependent
26995 characteristics of these Ada 83 compilers.  The following is a list of
26996 the cases most likely to arise in existing Ada 83 code.
26998 @table @emph
26999 @item Implicit Packing
27000 Some Ada 83 compilers allowed a Size specification to cause implicit
27001 packing of an array or record.  This could cause expensive implicit
27002 conversions for change of representation in the presence of derived
27003 types, and the Ada design intends to avoid this possibility.
27004 Subsequent AI's were issued to make it clear that such implicit
27005 change of representation in response to a Size clause is inadvisable,
27006 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
27007 Reference Manuals as implementation advice that is followed by GNAT@.
27008 The problem will show up as an error
27009 message rejecting the size clause.  The fix is simply to provide
27010 the explicit pragma @code{Pack}, or for more fine tuned control, provide
27011 a Component_Size clause.
27013 @item Meaning of Size Attribute
27014 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
27015 the minimal number of bits required to hold values of the type.  For example,
27016 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
27017 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
27018 some 32 in this situation.  This problem will usually show up as a compile
27019 time error, but not always.  It is a good idea to check all uses of the
27020 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
27021 Object_Size can provide a useful way of duplicating the behavior of
27022 some Ada 83 compiler systems.
27024 @item Size of Access Types
27025 A common assumption in Ada 83 code is that an access type is in fact a pointer,
27026 and that therefore it will be the same size as a System.Address value.  This
27027 assumption is true for GNAT in most cases with one exception.  For the case of
27028 a pointer to an unconstrained array type (where the bounds may vary from one
27029 value of the access type to another), the default is to use a ``fat pointer'',
27030 which is represented as two separate pointers, one to the bounds, and one to
27031 the array.  This representation has a number of advantages, including improved
27032 efficiency.  However, it may cause some difficulties in porting existing Ada 83
27033 code which makes the assumption that, for example, pointers fit in 32 bits on
27034 a machine with 32-bit addressing.
27036 To get around this problem, GNAT also permits the use of ``thin pointers'' for
27037 access types in this case (where the designated type is an unconstrained array
27038 type).  These thin pointers are indeed the same size as a System.Address value.
27039 To specify a thin pointer, use a size clause for the type, for example:
27041 @smallexample @c ada
27042 @b{type} X @b{is} @b{access} @b{all} String;
27043 @b{for} X'Size @b{use} Standard'Address_Size;
27044 @end smallexample
27046 @noindent
27047 which will cause the type X to be represented using a single pointer.
27048 When using this representation, the bounds are right behind the array.
27049 This representation is slightly less efficient, and does not allow quite
27050 such flexibility in the use of foreign pointers or in using the
27051 Unrestricted_Access attribute to create pointers to non-aliased objects.
27052 But for any standard portable use of the access type it will work in
27053 a functionally correct manner and allow porting of existing code.
27054 Note that another way of forcing a thin pointer representation
27055 is to use a component size clause for the element size in an array,
27056 or a record representation clause for an access field in a record.
27058 See the documentation of Unrestricted_Access in the GNAT RM for a
27059 full discussion of possible problems using this attribute in conjunction
27060 with thin pointers.
27061 @end table
27063 @c This brief section is only in the non-VMS version
27064 @c The complete chapter on HP Ada is in the VMS version
27065 @node Compatibility with HP Ada 83
27066 @section Compatibility with HP Ada 83
27068 @noindent
27069 The VMS version of GNAT fully implements all the pragmas and attributes
27070 provided by HP Ada 83, as well as providing the standard HP Ada 83
27071 libraries, including Starlet.  In addition, data layouts and parameter
27072 passing conventions are highly compatible.  This means that porting
27073 existing HP Ada 83 code to GNAT in VMS systems should be easier than
27074 most other porting efforts.  The following are some of the most
27075 significant differences between GNAT and HP Ada 83.
27077 @table @emph
27078 @item Default floating-point representation
27079 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
27080 it is VMS format.  GNAT does implement the necessary pragmas
27081 (Long_Float, Float_Representation) for changing this default.
27083 @item System
27084 The package System in GNAT exactly corresponds to the definition in the
27085 Ada 95 reference manual, which means that it excludes many of the
27086 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
27087 that contains the additional definitions, and a special pragma,
27088 Extend_System allows this package to be treated transparently as an
27089 extension of package System.
27091 @item To_Address
27092 The definitions provided by Aux_DEC are exactly compatible with those
27093 in the HP Ada 83 version of System, with one exception.
27094 HP Ada provides the following declarations:
27096 @smallexample @c ada
27097 TO_ADDRESS (INTEGER)
27098 TO_ADDRESS (UNSIGNED_LONGWORD)
27099 TO_ADDRESS (@i{universal_integer})
27100 @end smallexample
27102 @noindent
27103 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
27104 an extension to Ada 83 not strictly compatible with the reference manual.
27105 In GNAT, we are constrained to be exactly compatible with the standard,
27106 and this means we cannot provide this capability.  In HP Ada 83, the
27107 point of this definition is to deal with a call like:
27109 @smallexample @c ada
27110 TO_ADDRESS (16#12777#);
27111 @end smallexample
27113 @noindent
27114 Normally, according to the Ada 83 standard, one would expect this to be
27115 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
27116 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
27117 definition using @i{universal_integer} takes precedence.
27119 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
27120 is not possible to be 100% compatible.  Since there are many programs using
27121 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
27122 to change the name of the function in the UNSIGNED_LONGWORD case, so the
27123 declarations provided in the GNAT version of AUX_Dec are:
27125 @smallexample @c ada
27126 @b{function} To_Address (X : Integer) @b{return} Address;
27127 @b{pragma} Pure_Function (To_Address);
27129 @b{function} To_Address_Long (X : Unsigned_Longword)
27130  @b{return} Address;
27131 @b{pragma} Pure_Function (To_Address_Long);
27132 @end smallexample
27134 @noindent
27135 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
27136 change the name to TO_ADDRESS_LONG@.
27138 @item Task_Id values
27139 The Task_Id values assigned will be different in the two systems, and GNAT
27140 does not provide a specified value for the Task_Id of the environment task,
27141 which in GNAT is treated like any other declared task.
27142 @end table
27144 @noindent
27145 For full details on these and other less significant compatibility issues,
27146 see appendix E of the HP publication entitled @cite{HP Ada, Technical
27147 Overview and Comparison on HP Platforms}.
27149 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
27150 attributes are recognized, although only a subset of them can sensibly
27151 be implemented.  The description of pragmas in @ref{Implementation
27152 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
27153 indicates whether or not they are applicable to non-VMS systems.
27156 @c ************************************************
27157 @node Microsoft Windows Topics
27158 @appendix Microsoft Windows Topics
27159 @cindex Windows NT
27160 @cindex Windows 95
27161 @cindex Windows 98
27163 @noindent
27164 This chapter describes topics that are specific to the Microsoft Windows
27165 platforms (NT, 2000, and XP Professional).
27167 @menu
27168 @ifclear FSFEDITION
27169 * Installing from the Command Line::
27170 @end ifclear
27171 * Using GNAT on Windows::
27172 * Using a network installation of GNAT::
27173 * CONSOLE and WINDOWS subsystems::
27174 * Temporary Files::
27175 * Mixed-Language Programming on Windows::
27176 * Windows Calling Conventions::
27177 * Introduction to Dynamic Link Libraries (DLLs)::
27178 * Using DLLs with GNAT::
27179 * Building DLLs with GNAT Project files::
27180 * Building DLLs with GNAT::
27181 * Building DLLs with gnatdll::
27182 * GNAT and Windows Resources::
27183 * Debugging a DLL::
27184 * Setting Stack Size from gnatlink::
27185 * Setting Heap Size from gnatlink::
27186 @end menu
27188 @ifclear FSFEDITION
27189 @node Installing from the Command Line
27190 @section Installing from the Command Line
27191 @cindex Batch installation
27192 @cindex Silent installation
27193 @cindex Unassisted installation
27195 @noindent
27196 By default the @value{EDITION} installers display a GUI that prompts the user
27197 to enter installation path and similar information, and guide him through the
27198 installation process. It is also possible to perform silent installations
27199 using the command-line interface.
27201 In order to install one of the @value{EDITION} installers from the command
27202 line you should pass parameter @code{/S} (and, optionally,
27203 @code{/D=<directory>}) as command-line arguments.
27205 @ifset PROEDITION
27206 For example, for an unattended installation of
27207 @value{EDITION} 7.0.2 into the default directory
27208 @code{C:\GNATPRO\7.0.2} you would run:
27210 @smallexample
27211 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
27212 @end smallexample
27214 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
27216 @smallexample
27217 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
27218 @end smallexample
27219 @end ifset
27221 @ifset GPLEDITION
27222 For example, for an unattended installation of
27223 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
27225 @smallexample
27226 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
27227 @end smallexample
27228 @end ifset
27230 You can use the same syntax for all installers.
27232 Note that unattended installations don't modify system path, nor create file
27233 associations, so such activities need to be done by hand.
27234 @end ifclear
27236 @node Using GNAT on Windows
27237 @section Using GNAT on Windows
27239 @noindent
27240 One of the strengths of the GNAT technology is that its tool set
27241 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27242 @code{gdb} debugger, etc.) is used in the same way regardless of the
27243 platform.
27245 On Windows this tool set is complemented by a number of Microsoft-specific
27246 tools that have been provided to facilitate interoperability with Windows
27247 when this is required. With these tools:
27249 @itemize @bullet
27251 @item
27252 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27253 subsystems.
27255 @item
27256 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27257 relocatable and non-relocatable DLLs are supported).
27259 @item
27260 You can build Ada DLLs for use in other applications. These applications
27261 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27262 relocatable and non-relocatable Ada DLLs are supported.
27264 @item
27265 You can include Windows resources in your Ada application.
27267 @item
27268 You can use or create COM/DCOM objects.
27269 @end itemize
27271 @noindent
27272 Immediately below are listed all known general GNAT-for-Windows restrictions.
27273 Other restrictions about specific features like Windows Resources and DLLs
27274 are listed in separate sections below.
27276 @itemize @bullet
27278 @item
27279 It is not possible to use @code{GetLastError} and @code{SetLastError}
27280 when tasking, protected records, or exceptions are used. In these
27281 cases, in order to implement Ada semantics, the GNAT run-time system
27282 calls certain Win32 routines that set the last error variable to 0 upon
27283 success. It should be possible to use @code{GetLastError} and
27284 @code{SetLastError} when tasking, protected record, and exception
27285 features are not used, but it is not guaranteed to work.
27287 @item
27288 It is not possible to link against Microsoft C++ libraries except for
27289 import libraries. Interfacing must be done by the mean of DLLs.
27291 @item
27292 It is possible to link against Microsoft C libraries. Yet the preferred
27293 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
27294 doesn't require having two different development environments and makes the
27295 inter-language debugging experience smoother.
27297 @item
27298 When the compilation environment is located on FAT32 drives, users may
27299 experience recompilations of the source files that have not changed if
27300 Daylight Saving Time (DST) state has changed since the last time files
27301 were compiled. NTFS drives do not have this problem.
27303 @item
27304 No components of the GNAT toolset use any entries in the Windows
27305 registry. The only entries that can be created are file associations and
27306 PATH settings, provided the user has chosen to create them at installation
27307 time, as well as some minimal book-keeping information needed to correctly
27308 uninstall or integrate different GNAT products.
27309 @end itemize
27311 @node Using a network installation of GNAT
27312 @section Using a network installation of GNAT
27314 @noindent
27315 Make sure the system on which GNAT is installed is accessible from the
27316 current machine, i.e., the install location is shared over the network.
27317 Shared resources are accessed on Windows by means of UNC paths, which
27318 have the format @code{\\server\sharename\path}
27320 In order to use such a network installation, simply add the UNC path of the
27321 @file{bin} directory of your GNAT installation in front of your PATH. For
27322 example, if GNAT is installed in @file{\GNAT} directory of a share location
27323 called @file{c-drive} on a machine @file{LOKI}, the following command will
27324 make it available:
27326 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27328 Be aware that every compilation using the network installation results in the
27329 transfer of large amounts of data across the network and will likely cause
27330 serious performance penalty.
27332 @node CONSOLE and WINDOWS subsystems
27333 @section CONSOLE and WINDOWS subsystems
27334 @cindex CONSOLE Subsystem
27335 @cindex WINDOWS Subsystem
27336 @cindex -mwindows
27338 @noindent
27339 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27340 (which is the default subsystem) will always create a console when
27341 launching the application. This is not something desirable when the
27342 application has a Windows GUI. To get rid of this console the
27343 application must be using the @code{WINDOWS} subsystem. To do so
27344 the @option{-mwindows} linker option must be specified.
27346 @smallexample
27347 $ gnatmake winprog -largs -mwindows
27348 @end smallexample
27350 @node Temporary Files
27351 @section Temporary Files
27352 @cindex Temporary files
27354 @noindent
27355 It is possible to control where temporary files gets created by setting
27356 the @env{TMP} environment variable. The file will be created:
27358 @itemize
27359 @item Under the directory pointed to by the @env{TMP} environment variable if
27360 this directory exists.
27362 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27363 set (or not pointing to a directory) and if this directory exists.
27365 @item Under the current working directory otherwise.
27366 @end itemize
27368 @noindent
27369 This allows you to determine exactly where the temporary
27370 file will be created. This is particularly useful in networked
27371 environments where you may not have write access to some
27372 directories.
27374 @node Mixed-Language Programming on Windows
27375 @section Mixed-Language Programming on Windows
27377 @noindent
27378 Developing pure Ada applications on Windows is no different than on
27379 other GNAT-supported platforms. However, when developing or porting an
27380 application that contains a mix of Ada and C/C++, the choice of your
27381 Windows C/C++ development environment conditions your overall
27382 interoperability strategy.
27384 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
27385 your application, there are no Windows-specific restrictions that
27386 affect the overall interoperability with your Ada code. If you do want
27387 to use the Microsoft tools for your C++ code, you have two choices:
27389 @enumerate
27390 @item
27391 Encapsulate your C++ code in a DLL to be linked with your Ada
27392 application. In this case, use the Microsoft or whatever environment to
27393 build the DLL and use GNAT to build your executable
27394 (@pxref{Using DLLs with GNAT}).
27396 @item
27397 Or you can encapsulate your Ada code in a DLL to be linked with the
27398 other part of your application. In this case, use GNAT to build the DLL
27399 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27400 or whatever environment to build your executable.
27401 @end enumerate
27403 In addition to the description about C main in
27404 @pxref{Mixed Language Programming} section, if the C main uses a
27405 stand-alone library it is required on x86-windows to
27406 setup the SEH context. For this the C main must looks like this:
27408 @smallexample
27409 /* main.c */
27410 extern void adainit (void);
27411 extern void adafinal (void);
27412 extern void __gnat_initialize(void*);
27413 extern void call_to_ada (void);
27415 int main (int argc, char *argv[])
27417   int SEH [2];
27419   /* Initialize the SEH context */
27420   __gnat_initialize (&SEH);
27422   adainit();
27424   /* Then call Ada services in the stand-alone library */
27426   call_to_ada();
27428   adafinal();
27430 @end smallexample
27432 Note that this is not needed on x86_64-windows where the Windows
27433 native SEH support is used.
27435 @node Windows Calling Conventions
27436 @section Windows Calling Conventions
27437 @findex Stdcall
27438 @findex APIENTRY
27440 This section pertain only to Win32. On Win64 there is a single native
27441 calling convention. All convention specifiers are ignored on this
27442 platform.
27444 @menu
27445 * C Calling Convention::
27446 * Stdcall Calling Convention::
27447 * Win32 Calling Convention::
27448 * DLL Calling Convention::
27449 @end menu
27451 @noindent
27452 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27453 (callee), there are several ways to push @code{G}'s parameters on the
27454 stack and there are several possible scenarios to clean up the stack
27455 upon @code{G}'s return. A calling convention is an agreed upon software
27456 protocol whereby the responsibilities between the caller (@code{F}) and
27457 the callee (@code{G}) are clearly defined. Several calling conventions
27458 are available for Windows:
27460 @itemize @bullet
27461 @item
27462 @code{C} (Microsoft defined)
27464 @item
27465 @code{Stdcall} (Microsoft defined)
27467 @item
27468 @code{Win32} (GNAT specific)
27470 @item
27471 @code{DLL} (GNAT specific)
27472 @end itemize
27474 @node C Calling Convention
27475 @subsection @code{C} Calling Convention
27477 @noindent
27478 This is the default calling convention used when interfacing to C/C++
27479 routines compiled with either @command{gcc} or Microsoft Visual C++.
27481 In the @code{C} calling convention subprogram parameters are pushed on the
27482 stack by the caller from right to left. The caller itself is in charge of
27483 cleaning up the stack after the call. In addition, the name of a routine
27484 with @code{C} calling convention is mangled by adding a leading underscore.
27486 The name to use on the Ada side when importing (or exporting) a routine
27487 with @code{C} calling convention is the name of the routine. For
27488 instance the C function:
27490 @smallexample
27491 int get_val (long);
27492 @end smallexample
27494 @noindent
27495 should be imported from Ada as follows:
27497 @smallexample @c ada
27498 @group
27499 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27500 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
27501 @end group
27502 @end smallexample
27504 @noindent
27505 Note that in this particular case the @code{External_Name} parameter could
27506 have been omitted since, when missing, this parameter is taken to be the
27507 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27508 is missing, as in the above example, this parameter is set to be the
27509 @code{External_Name} with a leading underscore.
27511 When importing a variable defined in C, you should always use the @code{C}
27512 calling convention unless the object containing the variable is part of a
27513 DLL (in which case you should use the @code{Stdcall} calling
27514 convention, @pxref{Stdcall Calling Convention}).
27516 @node Stdcall Calling Convention
27517 @subsection @code{Stdcall} Calling Convention
27519 @noindent
27520 This convention, which was the calling convention used for Pascal
27521 programs, is used by Microsoft for all the routines in the Win32 API for
27522 efficiency reasons. It must be used to import any routine for which this
27523 convention was specified.
27525 In the @code{Stdcall} calling convention subprogram parameters are pushed
27526 on the stack by the caller from right to left. The callee (and not the
27527 caller) is in charge of cleaning the stack on routine exit. In addition,
27528 the name of a routine with @code{Stdcall} calling convention is mangled by
27529 adding a leading underscore (as for the @code{C} calling convention) and a
27530 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27531 bytes) of the parameters passed to the routine.
27533 The name to use on the Ada side when importing a C routine with a
27534 @code{Stdcall} calling convention is the name of the C routine. The leading
27535 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27536 the compiler. For instance the Win32 function:
27538 @smallexample
27539 @b{APIENTRY} int get_val (long);
27540 @end smallexample
27542 @noindent
27543 should be imported from Ada as follows:
27545 @smallexample @c ada
27546 @group
27547 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27548 @b{pragma} Import (Stdcall, Get_Val);
27549 --@i{  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"}
27550 @end group
27551 @end smallexample
27553 @noindent
27554 As for the @code{C} calling convention, when the @code{External_Name}
27555 parameter is missing, it is taken to be the name of the Ada entity in lower
27556 case. If instead of writing the above import pragma you write:
27558 @smallexample @c ada
27559 @group
27560 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27561 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27562 @end group
27563 @end smallexample
27565 @noindent
27566 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27567 of specifying the @code{External_Name} parameter you specify the
27568 @code{Link_Name} as in the following example:
27570 @smallexample @c ada
27571 @group
27572 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27573 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27574 @end group
27575 @end smallexample
27577 @noindent
27578 then the imported routine is @code{retrieve_val}, that is, there is no
27579 decoration at all. No leading underscore and no Stdcall suffix
27580 @code{@@}@code{@var{nn}}.
27582 @noindent
27583 This is especially important as in some special cases a DLL's entry
27584 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27585 name generated for a call has it.
27587 @noindent
27588 It is also possible to import variables defined in a DLL by using an
27589 import pragma for a variable. As an example, if a DLL contains a
27590 variable defined as:
27592 @smallexample
27593 int my_var;
27594 @end smallexample
27596 @noindent
27597 then, to access this variable from Ada you should write:
27599 @smallexample @c ada
27600 @group
27601 My_Var : Interfaces.C.int;
27602 @b{pragma} Import (Stdcall, My_Var);
27603 @end group
27604 @end smallexample
27606 @noindent
27607 Note that to ease building cross-platform bindings this convention
27608 will be handled as a @code{C} calling convention on non-Windows platforms.
27610 @node Win32 Calling Convention
27611 @subsection @code{Win32} Calling Convention
27613 @noindent
27614 This convention, which is GNAT-specific is fully equivalent to the
27615 @code{Stdcall} calling convention described above.
27617 @node DLL Calling Convention
27618 @subsection @code{DLL} Calling Convention
27620 @noindent
27621 This convention, which is GNAT-specific is fully equivalent to the
27622 @code{Stdcall} calling convention described above.
27624 @node Introduction to Dynamic Link Libraries (DLLs)
27625 @section Introduction to Dynamic Link Libraries (DLLs)
27626 @findex DLL
27628 @noindent
27629 A Dynamically Linked Library (DLL) is a library that can be shared by
27630 several applications running under Windows. A DLL can contain any number of
27631 routines and variables.
27633 One advantage of DLLs is that you can change and enhance them without
27634 forcing all the applications that depend on them to be relinked or
27635 recompiled. However, you should be aware than all calls to DLL routines are
27636 slower since, as you will understand below, such calls are indirect.
27638 To illustrate the remainder of this section, suppose that an application
27639 wants to use the services of a DLL @file{API.dll}. To use the services
27640 provided by @file{API.dll} you must statically link against the DLL or
27641 an import library which contains a jump table with an entry for each
27642 routine and variable exported by the DLL. In the Microsoft world this
27643 import library is called @file{API.lib}. When using GNAT this import
27644 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27645 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27647 After you have linked your application with the DLL or the import library
27648 and you run your application, here is what happens:
27650 @enumerate
27651 @item
27652 Your application is loaded into memory.
27654 @item
27655 The DLL @file{API.dll} is mapped into the address space of your
27656 application. This means that:
27658 @itemize @bullet
27659 @item
27660 The DLL will use the stack of the calling thread.
27662 @item
27663 The DLL will use the virtual address space of the calling process.
27665 @item
27666 The DLL will allocate memory from the virtual address space of the calling
27667 process.
27669 @item
27670 Handles (pointers) can be safely exchanged between routines in the DLL
27671 routines and routines in the application using the DLL.
27672 @end itemize
27674 @item
27675 The entries in the jump table (from the import library @file{libAPI.dll.a}
27676 or @file{API.lib} or automatically created when linking against a DLL)
27677 which is part of your application are initialized with the addresses
27678 of the routines and variables in @file{API.dll}.
27680 @item
27681 If present in @file{API.dll}, routines @code{DllMain} or
27682 @code{DllMainCRTStartup} are invoked. These routines typically contain
27683 the initialization code needed for the well-being of the routines and
27684 variables exported by the DLL.
27685 @end enumerate
27687 @noindent
27688 There is an additional point which is worth mentioning. In the Windows
27689 world there are two kind of DLLs: relocatable and non-relocatable
27690 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27691 in the target application address space. If the addresses of two
27692 non-relocatable DLLs overlap and these happen to be used by the same
27693 application, a conflict will occur and the application will run
27694 incorrectly. Hence, when possible, it is always preferable to use and
27695 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27696 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27697 User's Guide) removes the debugging symbols from the DLL but the DLL can
27698 still be relocated.
27700 As a side note, an interesting difference between Microsoft DLLs and
27701 Unix shared libraries, is the fact that on most Unix systems all public
27702 routines are exported by default in a Unix shared library, while under
27703 Windows it is possible (but not required) to list exported routines in
27704 a definition file (@pxref{The Definition File}).
27706 @node Using DLLs with GNAT
27707 @section Using DLLs with GNAT
27709 @menu
27710 * Creating an Ada Spec for the DLL Services::
27711 * Creating an Import Library::
27712 @end menu
27714 @noindent
27715 To use the services of a DLL, say @file{API.dll}, in your Ada application
27716 you must have:
27718 @enumerate
27719 @item
27720 The Ada spec for the routines and/or variables you want to access in
27721 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27722 header files provided with the DLL.
27724 @item
27725 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27726 mentioned an import library is a statically linked library containing the
27727 import table which will be filled at load time to point to the actual
27728 @file{API.dll} routines. Sometimes you don't have an import library for the
27729 DLL you want to use. The following sections will explain how to build
27730 one. Note that this is optional.
27732 @item
27733 The actual DLL, @file{API.dll}.
27734 @end enumerate
27736 @noindent
27737 Once you have all the above, to compile an Ada application that uses the
27738 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27739 you simply issue the command
27741 @smallexample
27742 $ gnatmake my_ada_app -largs -lAPI
27743 @end smallexample
27745 @noindent
27746 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27747 tells the GNAT linker to look for an import library. The linker will
27748 look for a library name in this specific order:
27750 @enumerate
27751 @item @file{libAPI.dll.a}
27752 @item @file{API.dll.a}
27753 @item @file{libAPI.a}
27754 @item @file{API.lib}
27755 @item @file{libAPI.dll}
27756 @item @file{API.dll}
27757 @end enumerate
27759 The first three are the GNU style import libraries. The third is the
27760 Microsoft style import libraries. The last two are the actual DLL names.
27762 Note that if the Ada package spec for @file{API.dll} contains the
27763 following pragma
27765 @smallexample @c ada
27766 @b{pragma} Linker_Options ("-lAPI");
27767 @end smallexample
27769 @noindent
27770 you do not have to add @option{-largs -lAPI} at the end of the
27771 @command{gnatmake} command.
27773 If any one of the items above is missing you will have to create it
27774 yourself. The following sections explain how to do so using as an
27775 example a fictitious DLL called @file{API.dll}.
27777 @node Creating an Ada Spec for the DLL Services
27778 @subsection Creating an Ada Spec for the DLL Services
27780 @noindent
27781 A DLL typically comes with a C/C++ header file which provides the
27782 definitions of the routines and variables exported by the DLL. The Ada
27783 equivalent of this header file is a package spec that contains definitions
27784 for the imported entities. If the DLL you intend to use does not come with
27785 an Ada spec you have to generate one such spec yourself. For example if
27786 the header file of @file{API.dll} is a file @file{api.h} containing the
27787 following two definitions:
27789 @smallexample
27790 @group
27791 @cartouche
27792 int some_var;
27793 int get (char *);
27794 @end cartouche
27795 @end group
27796 @end smallexample
27798 @noindent
27799 then the equivalent Ada spec could be:
27801 @smallexample @c ada
27802 @group
27803 @cartouche
27804 @b{with} Interfaces.C.Strings;
27805 @b{package} API @b{is}
27806    @b{use} Interfaces;
27808    Some_Var : C.int;
27809    @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
27811 @b{private}
27812    @b{pragma} Import (C, Get);
27813    @b{pragma} Import (DLL, Some_Var);
27814 @b{end} API;
27815 @end cartouche
27816 @end group
27817 @end smallexample
27819 @node Creating an Import Library
27820 @subsection Creating an Import Library
27821 @cindex Import library
27823 @menu
27824 * The Definition File::
27825 * GNAT-Style Import Library::
27826 * Microsoft-Style Import Library::
27827 @end menu
27829 @noindent
27830 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27831 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27832 with @file{API.dll} you can skip this section. You can also skip this
27833 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27834 as in this case it is possible to link directly against the
27835 DLL. Otherwise read on.
27837 @node The Definition File
27838 @subsubsection The Definition File
27839 @cindex Definition file
27840 @findex .def
27842 @noindent
27843 As previously mentioned, and unlike Unix systems, the list of symbols
27844 that are exported from a DLL must be provided explicitly in Windows.
27845 The main goal of a definition file is precisely that: list the symbols
27846 exported by a DLL. A definition file (usually a file with a @code{.def}
27847 suffix) has the following structure:
27849 @smallexample
27850 @group
27851 @cartouche
27852 @r{[}LIBRARY @var{name}@r{]}
27853 @r{[}DESCRIPTION @var{string}@r{]}
27854 EXPORTS
27855    @var{symbol1}
27856    @var{symbol2}
27857    @dots{}
27858 @end cartouche
27859 @end group
27860 @end smallexample
27862 @table @code
27863 @item LIBRARY @var{name}
27864 This section, which is optional, gives the name of the DLL.
27866 @item DESCRIPTION @var{string}
27867 This section, which is optional, gives a description string that will be
27868 embedded in the import library.
27870 @item EXPORTS
27871 This section gives the list of exported symbols (procedures, functions or
27872 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27873 section of @file{API.def} looks like:
27875 @smallexample
27876 @group
27877 @cartouche
27878 EXPORTS
27879    some_var
27880    get
27881 @end cartouche
27882 @end group
27883 @end smallexample
27884 @end table
27886 @noindent
27887 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27888 (@pxref{Windows Calling Conventions}) for a Stdcall
27889 calling convention function in the exported symbols list.
27891 @noindent
27892 There can actually be other sections in a definition file, but these
27893 sections are not relevant to the discussion at hand.
27895 @node GNAT-Style Import Library
27896 @subsubsection GNAT-Style Import Library
27898 @noindent
27899 To create a static import library from @file{API.dll} with the GNAT tools
27900 you should proceed as follows:
27902 @enumerate
27903 @item
27904 Create the definition file @file{API.def} (@pxref{The Definition File}).
27905 For that use the @code{dll2def} tool as follows:
27907 @smallexample
27908 $ dll2def API.dll > API.def
27909 @end smallexample
27911 @noindent
27912 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27913 to standard output the list of entry points in the DLL. Note that if
27914 some routines in the DLL have the @code{Stdcall} convention
27915 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27916 suffix then you'll have to edit @file{api.def} to add it, and specify
27917 @option{-k} to @command{gnatdll} when creating the import library.
27919 @noindent
27920 Here are some hints to find the right @code{@@}@var{nn} suffix.
27922 @enumerate
27923 @item
27924 If you have the Microsoft import library (.lib), it is possible to get
27925 the right symbols by using Microsoft @code{dumpbin} tool (see the
27926 corresponding Microsoft documentation for further details).
27928 @smallexample
27929 $ dumpbin /exports api.lib
27930 @end smallexample
27932 @item
27933 If you have a message about a missing symbol at link time the compiler
27934 tells you what symbol is expected. You just have to go back to the
27935 definition file and add the right suffix.
27936 @end enumerate
27938 @item
27939 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27940 (@pxref{Using gnatdll}) as follows:
27942 @smallexample
27943 $ gnatdll -e API.def -d API.dll
27944 @end smallexample
27946 @noindent
27947 @code{gnatdll} takes as input a definition file @file{API.def} and the
27948 name of the DLL containing the services listed in the definition file
27949 @file{API.dll}. The name of the static import library generated is
27950 computed from the name of the definition file as follows: if the
27951 definition file name is @var{xyz}@code{.def}, the import library name will
27952 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27953 @option{-e} could have been removed because the name of the definition
27954 file (before the ``@code{.def}'' suffix) is the same as the name of the
27955 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27956 @end enumerate
27958 @node Microsoft-Style Import Library
27959 @subsubsection Microsoft-Style Import Library
27961 @noindent
27962 With GNAT you can either use a GNAT-style or Microsoft-style import
27963 library. A Microsoft import library is needed only if you plan to make an
27964 Ada DLL available to applications developed with Microsoft
27965 tools (@pxref{Mixed-Language Programming on Windows}).
27967 To create a Microsoft-style import library for @file{API.dll} you
27968 should proceed as follows:
27970 @enumerate
27971 @item
27972 Create the definition file @file{API.def} from the DLL. For this use either
27973 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27974 tool (see the corresponding Microsoft documentation for further details).
27976 @item
27977 Build the actual import library using Microsoft's @code{lib} utility:
27979 @smallexample
27980 $ lib -machine:IX86 -def:API.def -out:API.lib
27981 @end smallexample
27983 @noindent
27984 If you use the above command the definition file @file{API.def} must
27985 contain a line giving the name of the DLL:
27987 @smallexample
27988 LIBRARY      "API"
27989 @end smallexample
27991 @noindent
27992 See the Microsoft documentation for further details about the usage of
27993 @code{lib}.
27994 @end enumerate
27996 @node Building DLLs with GNAT Project files
27997 @section Building DLLs with GNAT Project files
27998 @cindex DLLs, building
28000 @noindent
28001 There is nothing specific to Windows in the build process.
28002 @pxref{Library Projects}.
28004 @noindent
28005 Due to a system limitation, it is not possible under Windows to create threads
28006 when inside the @code{DllMain} routine which is used for auto-initialization
28007 of shared libraries, so it is not possible to have library level tasks in SALs.
28009 @node Building DLLs with GNAT
28010 @section Building DLLs with GNAT
28011 @cindex DLLs, building
28013 @noindent
28014 This section explain how to build DLLs using the GNAT built-in DLL
28015 support. With the following procedure it is straight forward to build
28016 and use DLLs with GNAT.
28018 @enumerate
28020 @item building object files
28022 The first step is to build all objects files that are to be included
28023 into the DLL. This is done by using the standard @command{gnatmake} tool.
28025 @item building the DLL
28027 To build the DLL you must use @command{gcc}'s @option{-shared} and
28028 @option{-shared-libgcc} options. It is quite simple to use this method:
28030 @smallexample
28031 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
28032 @end smallexample
28034 It is important to note that in this case all symbols found in the
28035 object files are automatically exported. It is possible to restrict
28036 the set of symbols to export by passing to @command{gcc} a definition
28037 file, @pxref{The Definition File}. For example:
28039 @smallexample
28040 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
28041 @end smallexample
28043 If you use a definition file you must export the elaboration procedures
28044 for every package that required one. Elaboration procedures are named
28045 using the package name followed by "_E".
28047 @item preparing DLL to be used
28049 For the DLL to be used by client programs the bodies must be hidden
28050 from it and the .ali set with read-only attribute. This is very important
28051 otherwise GNAT will recompile all packages and will not actually use
28052 the code in the DLL. For example:
28054 @smallexample
28055 $ mkdir apilib
28056 $ copy *.ads *.ali api.dll apilib
28057 $ attrib +R apilib\*.ali
28058 @end smallexample
28060 @end enumerate
28062 At this point it is possible to use the DLL by directly linking
28063 against it. Note that you must use the GNAT shared runtime when using
28064 GNAT shared libraries. This is achieved by using @option{-shared} binder's
28065 option.
28067 @smallexample
28068 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28069 @end smallexample
28071 @node Building DLLs with gnatdll
28072 @section Building DLLs with gnatdll
28073 @cindex DLLs, building
28075 @menu
28076 * Limitations When Using Ada DLLs from Ada::
28077 * Exporting Ada Entities::
28078 * Ada DLLs and Elaboration::
28079 * Ada DLLs and Finalization::
28080 * Creating a Spec for Ada DLLs::
28081 * Creating the Definition File::
28082 * Using gnatdll::
28083 @end menu
28085 @noindent
28086 Note that it is preferred to use GNAT Project files
28087 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28088 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28090 This section explains how to build DLLs containing Ada code using
28091 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28092 remainder of this section.
28094 The steps required to build an Ada DLL that is to be used by Ada as well as
28095 non-Ada applications are as follows:
28097 @enumerate
28098 @item
28099 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28100 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28101 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28102 skip this step if you plan to use the Ada DLL only from Ada applications.
28104 @item
28105 Your Ada code must export an initialization routine which calls the routine
28106 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28107 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28108 routine exported by the Ada DLL must be invoked by the clients of the DLL
28109 to initialize the DLL.
28111 @item
28112 When useful, the DLL should also export a finalization routine which calls
28113 routine @code{adafinal} generated by @command{gnatbind} to perform the
28114 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28115 The finalization routine exported by the Ada DLL must be invoked by the
28116 clients of the DLL when the DLL services are no further needed.
28118 @item
28119 You must provide a spec for the services exported by the Ada DLL in each
28120 of the programming languages to which you plan to make the DLL available.
28122 @item
28123 You must provide a definition file listing the exported entities
28124 (@pxref{The Definition File}).
28126 @item
28127 Finally you must use @code{gnatdll} to produce the DLL and the import
28128 library (@pxref{Using gnatdll}).
28129 @end enumerate
28131 @noindent
28132 Note that a relocatable DLL stripped using the @code{strip}
28133 binutils tool will not be relocatable anymore. To build a DLL without
28134 debug information pass @code{-largs -s} to @code{gnatdll}. This
28135 restriction does not apply to a DLL built using a Library Project.
28136 @pxref{Library Projects}.
28138 @node Limitations When Using Ada DLLs from Ada
28139 @subsection Limitations When Using Ada DLLs from Ada
28141 @noindent
28142 When using Ada DLLs from Ada applications there is a limitation users
28143 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28144 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28145 each Ada DLL includes the services of the GNAT run time that are necessary
28146 to the Ada code inside the DLL. As a result, when an Ada program uses an
28147 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28148 one in the main program.
28150 It is therefore not possible to exchange GNAT run-time objects between the
28151 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28152 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
28153 types, etc.
28155 It is completely safe to exchange plain elementary, array or record types,
28156 Windows object handles, etc.
28158 @node Exporting Ada Entities
28159 @subsection Exporting Ada Entities
28160 @cindex Export table
28162 @noindent
28163 Building a DLL is a way to encapsulate a set of services usable from any
28164 application. As a result, the Ada entities exported by a DLL should be
28165 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28166 any Ada name mangling. As an example here is an Ada package
28167 @code{API}, spec and body, exporting two procedures, a function, and a
28168 variable:
28170 @smallexample @c ada
28171 @group
28172 @cartouche
28173 @b{with} Interfaces.C; @b{use} Interfaces;
28174 @b{package} API @b{is}
28175    Count : C.int := 0;
28176    @b{function} Factorial (Val : C.int) @b{return} C.int;
28178    @b{procedure} Initialize_API;
28179    @b{procedure} Finalize_API;
28180    --@i{  Initialization & Finalization routines. More in the next section.}
28181 @b{private}
28182    @b{pragma} Export (C, Initialize_API);
28183    @b{pragma} Export (C, Finalize_API);
28184    @b{pragma} Export (C, Count);
28185    @b{pragma} Export (C, Factorial);
28186 @b{end} API;
28187 @end cartouche
28188 @end group
28189 @end smallexample
28191 @smallexample @c ada
28192 @group
28193 @cartouche
28194 @b{package} @b{body} API @b{is}
28195    @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
28196       Fact : C.int := 1;
28197    @b{begin}
28198       Count := Count + 1;
28199       @b{for} K @b{in} 1 .. Val @b{loop}
28200          Fact := Fact * K;
28201       @b{end} @b{loop};
28202       @b{return} Fact;
28203    @b{end} Factorial;
28205    @b{procedure} Initialize_API @b{is}
28206       @b{procedure} Adainit;
28207       @b{pragma} Import (C, Adainit);
28208    @b{begin}
28209       Adainit;
28210    @b{end} Initialize_API;
28212    @b{procedure} Finalize_API @b{is}
28213       @b{procedure} Adafinal;
28214       @b{pragma} Import (C, Adafinal);
28215    @b{begin}
28216       Adafinal;
28217    @b{end} Finalize_API;
28218 @b{end} API;
28219 @end cartouche
28220 @end group
28221 @end smallexample
28223 @noindent
28224 If the Ada DLL you are building will only be used by Ada applications
28225 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28226 convention. As an example, the previous package could be written as
28227 follows:
28229 @smallexample @c ada
28230 @group
28231 @cartouche
28232 @b{package} API @b{is}
28233    Count : Integer := 0;
28234    @b{function} Factorial (Val : Integer) @b{return} Integer;
28236    @b{procedure} Initialize_API;
28237    @b{procedure} Finalize_API;
28238    --@i{  Initialization and Finalization routines.}
28239 @b{end} API;
28240 @end cartouche
28241 @end group
28242 @end smallexample
28244 @smallexample @c ada
28245 @group
28246 @cartouche
28247 @b{package} @b{body} API @b{is}
28248    @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
28249       Fact : Integer := 1;
28250    @b{begin}
28251       Count := Count + 1;
28252       @b{for} K @b{in} 1 .. Val @b{loop}
28253          Fact := Fact * K;
28254       @b{end} @b{loop};
28255       @b{return} Fact;
28256    @b{end} Factorial;
28258    @dots{}
28259    --@i{  The remainder of this package body is unchanged.}
28260 @b{end} API;
28261 @end cartouche
28262 @end group
28263 @end smallexample
28265 @noindent
28266 Note that if you do not export the Ada entities with a @code{C} or
28267 @code{Stdcall} convention you will have to provide the mangled Ada names
28268 in the definition file of the Ada DLL
28269 (@pxref{Creating the Definition File}).
28271 @node Ada DLLs and Elaboration
28272 @subsection Ada DLLs and Elaboration
28273 @cindex DLLs and elaboration
28275 @noindent
28276 The DLL that you are building contains your Ada code as well as all the
28277 routines in the Ada library that are needed by it. The first thing a
28278 user of your DLL must do is elaborate the Ada code
28279 (@pxref{Elaboration Order Handling in GNAT}).
28281 To achieve this you must export an initialization routine
28282 (@code{Initialize_API} in the previous example), which must be invoked
28283 before using any of the DLL services. This elaboration routine must call
28284 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28285 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28286 @code{Initialize_Api} for an example. Note that the GNAT binder is
28287 automatically invoked during the DLL build process by the @code{gnatdll}
28288 tool (@pxref{Using gnatdll}).
28290 When a DLL is loaded, Windows systematically invokes a routine called
28291 @code{DllMain}. It would therefore be possible to call @code{adainit}
28292 directly from @code{DllMain} without having to provide an explicit
28293 initialization routine. Unfortunately, it is not possible to call
28294 @code{adainit} from the @code{DllMain} if your program has library level
28295 tasks because access to the @code{DllMain} entry point is serialized by
28296 the system (that is, only a single thread can execute ``through'' it at a
28297 time), which means that the GNAT run time will deadlock waiting for the
28298 newly created task to complete its initialization.
28300 @node Ada DLLs and Finalization
28301 @subsection Ada DLLs and Finalization
28302 @cindex DLLs and finalization
28304 @noindent
28305 When the services of an Ada DLL are no longer needed, the client code should
28306 invoke the DLL finalization routine, if available. The DLL finalization
28307 routine is in charge of releasing all resources acquired by the DLL. In the
28308 case of the Ada code contained in the DLL, this is achieved by calling
28309 routine @code{adafinal} generated by the GNAT binder
28310 (@pxref{Binding with Non-Ada Main Programs}).
28311 See the body of @code{Finalize_Api} for an
28312 example. As already pointed out the GNAT binder is automatically invoked
28313 during the DLL build process by the @code{gnatdll} tool
28314 (@pxref{Using gnatdll}).
28316 @node Creating a Spec for Ada DLLs
28317 @subsection Creating a Spec for Ada DLLs
28319 @noindent
28320 To use the services exported by the Ada DLL from another programming
28321 language (e.g.@: C), you have to translate the specs of the exported Ada
28322 entities in that language. For instance in the case of @code{API.dll},
28323 the corresponding C header file could look like:
28325 @smallexample
28326 @group
28327 @cartouche
28328 extern int *_imp__count;
28329 #define count (*_imp__count)
28330 int factorial (int);
28331 @end cartouche
28332 @end group
28333 @end smallexample
28335 @noindent
28336 It is important to understand that when building an Ada DLL to be used by
28337 other Ada applications, you need two different specs for the packages
28338 contained in the DLL: one for building the DLL and the other for using
28339 the DLL. This is because the @code{DLL} calling convention is needed to
28340 use a variable defined in a DLL, but when building the DLL, the variable
28341 must have either the @code{Ada} or @code{C} calling convention. As an
28342 example consider a DLL comprising the following package @code{API}:
28344 @smallexample @c ada
28345 @group
28346 @cartouche
28347 @b{package} API @b{is}
28348    Count : Integer := 0;
28349    @dots{}
28350    --@i{  Remainder of the package omitted.}
28351 @b{end} API;
28352 @end cartouche
28353 @end group
28354 @end smallexample
28356 @noindent
28357 After producing a DLL containing package @code{API}, the spec that
28358 must be used to import @code{API.Count} from Ada code outside of the
28359 DLL is:
28361 @smallexample @c ada
28362 @group
28363 @cartouche
28364 @b{package} API @b{is}
28365    Count : Integer;
28366    @b{pragma} Import (DLL, Count);
28367 @b{end} API;
28368 @end cartouche
28369 @end group
28370 @end smallexample
28372 @node Creating the Definition File
28373 @subsection Creating the Definition File
28375 @noindent
28376 The definition file is the last file needed to build the DLL. It lists
28377 the exported symbols. As an example, the definition file for a DLL
28378 containing only package @code{API} (where all the entities are exported
28379 with a @code{C} calling convention) is:
28381 @smallexample
28382 @group
28383 @cartouche
28384 EXPORTS
28385     count
28386     factorial
28387     finalize_api
28388     initialize_api
28389 @end cartouche
28390 @end group
28391 @end smallexample
28393 @noindent
28394 If the @code{C} calling convention is missing from package @code{API},
28395 then the definition file contains the mangled Ada names of the above
28396 entities, which in this case are:
28398 @smallexample
28399 @group
28400 @cartouche
28401 EXPORTS
28402     api__count
28403     api__factorial
28404     api__finalize_api
28405     api__initialize_api
28406 @end cartouche
28407 @end group
28408 @end smallexample
28410 @node Using gnatdll
28411 @subsection Using @code{gnatdll}
28412 @findex gnatdll
28414 @menu
28415 * gnatdll Example::
28416 * gnatdll behind the Scenes::
28417 * Using dlltool::
28418 @end menu
28420 @noindent
28421 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28422 and non-Ada sources that make up your DLL have been compiled.
28423 @code{gnatdll} is actually in charge of two distinct tasks: build the
28424 static import library for the DLL and the actual DLL. The form of the
28425 @code{gnatdll} command is
28427 @smallexample
28428 @cartouche
28429 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28430 @c Expanding @ovar macro inline (explanation in macro def comments)
28431 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28432 @end cartouche
28433 @end smallexample
28435 @noindent
28436 where @var{list-of-files} is a list of ALI and object files. The object
28437 file list must be the exact list of objects corresponding to the non-Ada
28438 sources whose services are to be included in the DLL. The ALI file list
28439 must be the exact list of ALI files for the corresponding Ada sources
28440 whose services are to be included in the DLL. If @var{list-of-files} is
28441 missing, only the static import library is generated.
28443 @noindent
28444 You may specify any of the following switches to @code{gnatdll}:
28446 @table @code
28447 @c @item -a@ovar{address}
28448 @c Expanding @ovar macro inline (explanation in macro def comments)
28449 @item -a@r{[}@var{address}@r{]}
28450 @cindex @option{-a} (@code{gnatdll})
28451 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28452 specified the default address @var{0x11000000} will be used. By default,
28453 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28454 advise the reader to build relocatable DLL.
28456 @item -b @var{address}
28457 @cindex @option{-b} (@code{gnatdll})
28458 Set the relocatable DLL base address. By default the address is
28459 @code{0x11000000}.
28461 @item -bargs @var{opts}
28462 @cindex @option{-bargs} (@code{gnatdll})
28463 Binder options. Pass @var{opts} to the binder.
28465 @item -d @var{dllfile}
28466 @cindex @option{-d} (@code{gnatdll})
28467 @var{dllfile} is the name of the DLL. This switch must be present for
28468 @code{gnatdll} to do anything. The name of the generated import library is
28469 obtained algorithmically from @var{dllfile} as shown in the following
28470 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28471 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28472 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28473 as shown in the following example:
28474 if @var{dllfile} is @code{xyz.dll}, the definition
28475 file used is @code{xyz.def}.
28477 @item -e @var{deffile}
28478 @cindex @option{-e} (@code{gnatdll})
28479 @var{deffile} is the name of the definition file.
28481 @item -g
28482 @cindex @option{-g} (@code{gnatdll})
28483 Generate debugging information. This information is stored in the object
28484 file and copied from there to the final DLL file by the linker,
28485 where it can be read by the debugger. You must use the
28486 @option{-g} switch if you plan on using the debugger or the symbolic
28487 stack traceback.
28489 @item -h
28490 @cindex @option{-h} (@code{gnatdll})
28491 Help mode. Displays @code{gnatdll} switch usage information.
28493 @item -Idir
28494 @cindex @option{-I} (@code{gnatdll})
28495 Direct @code{gnatdll} to search the @var{dir} directory for source and
28496 object files needed to build the DLL.
28497 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28499 @item -k
28500 @cindex @option{-k} (@code{gnatdll})
28501 Removes the @code{@@}@var{nn} suffix from the import library's exported
28502 names, but keeps them for the link names. You must specify this
28503 option if you want to use a @code{Stdcall} function in a DLL for which
28504 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28505 of the Windows NT DLL for example. This option has no effect when
28506 @option{-n} option is specified.
28508 @item -l @var{file}
28509 @cindex @option{-l} (@code{gnatdll})
28510 The list of ALI and object files used to build the DLL are listed in
28511 @var{file}, instead of being given in the command line. Each line in
28512 @var{file} contains the name of an ALI or object file.
28514 @item -n
28515 @cindex @option{-n} (@code{gnatdll})
28516 No Import. Do not create the import library.
28518 @item -q
28519 @cindex @option{-q} (@code{gnatdll})
28520 Quiet mode. Do not display unnecessary messages.
28522 @item -v
28523 @cindex @option{-v} (@code{gnatdll})
28524 Verbose mode. Display extra information.
28526 @item -largs @var{opts}
28527 @cindex @option{-largs} (@code{gnatdll})
28528 Linker options. Pass @var{opts} to the linker.
28529 @end table
28531 @node gnatdll Example
28532 @subsubsection @code{gnatdll} Example
28534 @noindent
28535 As an example the command to build a relocatable DLL from @file{api.adb}
28536 once @file{api.adb} has been compiled and @file{api.def} created is
28538 @smallexample
28539 $ gnatdll -d api.dll api.ali
28540 @end smallexample
28542 @noindent
28543 The above command creates two files: @file{libapi.dll.a} (the import
28544 library) and @file{api.dll} (the actual DLL). If you want to create
28545 only the DLL, just type:
28547 @smallexample
28548 $ gnatdll -d api.dll -n api.ali
28549 @end smallexample
28551 @noindent
28552 Alternatively if you want to create just the import library, type:
28554 @smallexample
28555 $ gnatdll -d api.dll
28556 @end smallexample
28558 @node gnatdll behind the Scenes
28559 @subsubsection @code{gnatdll} behind the Scenes
28561 @noindent
28562 This section details the steps involved in creating a DLL. @code{gnatdll}
28563 does these steps for you. Unless you are interested in understanding what
28564 goes on behind the scenes, you should skip this section.
28566 We use the previous example of a DLL containing the Ada package @code{API},
28567 to illustrate the steps necessary to build a DLL. The starting point is a
28568 set of objects that will make up the DLL and the corresponding ALI
28569 files. In the case of this example this means that @file{api.o} and
28570 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28571 the following:
28573 @enumerate
28574 @item
28575 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28576 the information necessary to generate relocation information for the
28577 DLL.
28579 @smallexample
28580 @group
28581 $ gnatbind -n api
28582 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28583 @end group
28584 @end smallexample
28586 @noindent
28587 In addition to the base file, the @command{gnatlink} command generates an
28588 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28589 asks @command{gnatlink} to generate the routines @code{DllMain} and
28590 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28591 is loaded into memory.
28593 @item
28594 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28595 export table (@file{api.exp}). The export table contains the relocation
28596 information in a form which can be used during the final link to ensure
28597 that the Windows loader is able to place the DLL anywhere in memory.
28599 @smallexample
28600 @group
28601 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28602           --output-exp api.exp
28603 @end group
28604 @end smallexample
28606 @item
28607 @code{gnatdll} builds the base file using the new export table. Note that
28608 @command{gnatbind} must be called once again since the binder generated file
28609 has been deleted during the previous call to @command{gnatlink}.
28611 @smallexample
28612 @group
28613 $ gnatbind -n api
28614 $ gnatlink api -o api.jnk api.exp -mdll
28615       -Wl,--base-file,api.base
28616 @end group
28617 @end smallexample
28619 @item
28620 @code{gnatdll} builds the new export table using the new base file and
28621 generates the DLL import library @file{libAPI.dll.a}.
28623 @smallexample
28624 @group
28625 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28626           --output-exp api.exp --output-lib libAPI.a
28627 @end group
28628 @end smallexample
28630 @item
28631 Finally @code{gnatdll} builds the relocatable DLL using the final export
28632 table.
28634 @smallexample
28635 @group
28636 $ gnatbind -n api
28637 $ gnatlink api api.exp -o api.dll -mdll
28638 @end group
28639 @end smallexample
28640 @end enumerate
28642 @node Using dlltool
28643 @subsubsection Using @code{dlltool}
28645 @noindent
28646 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28647 DLLs and static import libraries. This section summarizes the most
28648 common @code{dlltool} switches. The form of the @code{dlltool} command
28651 @smallexample
28652 @c $ dlltool @ovar{switches}
28653 @c Expanding @ovar macro inline (explanation in macro def comments)
28654 $ dlltool @r{[}@var{switches}@r{]}
28655 @end smallexample
28657 @noindent
28658 @code{dlltool} switches include:
28660 @table @option
28661 @item --base-file @var{basefile}
28662 @cindex @option{--base-file} (@command{dlltool})
28663 Read the base file @var{basefile} generated by the linker. This switch
28664 is used to create a relocatable DLL.
28666 @item --def @var{deffile}
28667 @cindex @option{--def} (@command{dlltool})
28668 Read the definition file.
28670 @item --dllname @var{name}
28671 @cindex @option{--dllname} (@command{dlltool})
28672 Gives the name of the DLL. This switch is used to embed the name of the
28673 DLL in the static import library generated by @code{dlltool} with switch
28674 @option{--output-lib}.
28676 @item -k
28677 @cindex @option{-k} (@command{dlltool})
28678 Kill @code{@@}@var{nn} from exported names
28679 (@pxref{Windows Calling Conventions}
28680 for a discussion about @code{Stdcall}-style symbols.
28682 @item --help
28683 @cindex @option{--help} (@command{dlltool})
28684 Prints the @code{dlltool} switches with a concise description.
28686 @item --output-exp @var{exportfile}
28687 @cindex @option{--output-exp} (@command{dlltool})
28688 Generate an export file @var{exportfile}. The export file contains the
28689 export table (list of symbols in the DLL) and is used to create the DLL.
28691 @item --output-lib @var{libfile}
28692 @cindex @option{--output-lib} (@command{dlltool})
28693 Generate a static import library @var{libfile}.
28695 @item -v
28696 @cindex @option{-v} (@command{dlltool})
28697 Verbose mode.
28699 @item --as @var{assembler-name}
28700 @cindex @option{--as} (@command{dlltool})
28701 Use @var{assembler-name} as the assembler. The default is @code{as}.
28702 @end table
28704 @node GNAT and Windows Resources
28705 @section GNAT and Windows Resources
28706 @cindex Resources, windows
28708 @menu
28709 * Building Resources::
28710 * Compiling Resources::
28711 * Using Resources::
28712 @end menu
28714 @noindent
28715 Resources are an easy way to add Windows specific objects to your
28716 application. The objects that can be added as resources include:
28718 @itemize @bullet
28719 @item menus
28721 @item accelerators
28723 @item dialog boxes
28725 @item string tables
28727 @item bitmaps
28729 @item cursors
28731 @item icons
28733 @item fonts
28735 @item version information
28736 @end itemize
28738 For example, a version information resource can be defined as follow and
28739 embedded into an executable or DLL:
28741 A version information resource can be used to embed information into an
28742 executable or a DLL. These information can be viewed using the file properties
28743 from the Windows Explorer. Here is an example of a version information
28744 resource:
28746 @smallexample
28747 @group
28748 1 VERSIONINFO
28749 FILEVERSION     1,0,0,0
28750 PRODUCTVERSION  1,0,0,0
28751 BEGIN
28752   BLOCK "StringFileInfo"
28753   BEGIN
28754     BLOCK "080904E4"
28755     BEGIN
28756       VALUE "CompanyName", "My Company Name"
28757       VALUE "FileDescription", "My application"
28758       VALUE "FileVersion", "1.0"
28759       VALUE "InternalName", "my_app"
28760       VALUE "LegalCopyright", "My Name"
28761       VALUE "OriginalFilename", "my_app.exe"
28762       VALUE "ProductName", "My App"
28763       VALUE "ProductVersion", "1.0"
28764     END
28765   END
28767   BLOCK "VarFileInfo"
28768   BEGIN
28769     VALUE "Translation", 0x809, 1252
28770   END
28772 @end group
28773 @end smallexample
28775 The value @code{0809} (langID) is for the U.K English language and
28776 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28777 multilingual.
28779 @noindent
28780 This section explains how to build, compile and use resources. Note that this
28781 section does not cover all resource objects, for a complete description see
28782 the corresponding Microsoft documentation.
28784 @node Building Resources
28785 @subsection Building Resources
28786 @cindex Resources, building
28788 @noindent
28789 A resource file is an ASCII file. By convention resource files have an
28790 @file{.rc} extension.
28791 The easiest way to build a resource file is to use Microsoft tools
28792 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28793 @code{dlgedit.exe} to build dialogs.
28794 It is always possible to build an @file{.rc} file yourself by writing a
28795 resource script.
28797 It is not our objective to explain how to write a resource file. A
28798 complete description of the resource script language can be found in the
28799 Microsoft documentation.
28801 @node Compiling Resources
28802 @subsection Compiling Resources
28803 @findex rc
28804 @findex windres
28805 @cindex Resources, compiling
28807 @noindent
28808 This section describes how to build a GNAT-compatible (COFF) object file
28809 containing the resources. This is done using the Resource Compiler
28810 @code{windres} as follows:
28812 @smallexample
28813 $ windres -i myres.rc -o myres.o
28814 @end smallexample
28816 @noindent
28817 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28818 file. You can specify an alternate preprocessor (usually named
28819 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28820 parameter. A list of all possible options may be obtained by entering
28821 the command @code{windres} @option{--help}.
28823 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28824 to produce a @file{.res} file (binary resource file). See the
28825 corresponding Microsoft documentation for further details. In this case
28826 you need to use @code{windres} to translate the @file{.res} file to a
28827 GNAT-compatible object file as follows:
28829 @smallexample
28830 $ windres -i myres.res -o myres.o
28831 @end smallexample
28833 @node Using Resources
28834 @subsection Using Resources
28835 @cindex Resources, using
28837 @noindent
28838 To include the resource file in your program just add the
28839 GNAT-compatible object file for the resource(s) to the linker
28840 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28841 option:
28843 @smallexample
28844 $ gnatmake myprog -largs myres.o
28845 @end smallexample
28847 @node Debugging a DLL
28848 @section Debugging a DLL
28849 @cindex DLL debugging
28851 @menu
28852 * Program and DLL Both Built with GCC/GNAT::
28853 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28854 @end menu
28856 @noindent
28857 Debugging a DLL is similar to debugging a standard program. But
28858 we have to deal with two different executable parts: the DLL and the
28859 program that uses it. We have the following four possibilities:
28861 @enumerate 1
28862 @item
28863 The program and the DLL are built with @code{GCC/GNAT}.
28864 @item
28865 The program is built with foreign tools and the DLL is built with
28866 @code{GCC/GNAT}.
28867 @item
28868 The program is built with @code{GCC/GNAT} and the DLL is built with
28869 foreign tools.
28870 @end enumerate
28872 @noindent
28873 In this section we address only cases one and two above.
28874 There is no point in trying to debug
28875 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28876 information in it. To do so you must use a debugger compatible with the
28877 tools suite used to build the DLL.
28879 @node Program and DLL Both Built with GCC/GNAT
28880 @subsection Program and DLL Both Built with GCC/GNAT
28882 @noindent
28883 This is the simplest case. Both the DLL and the program have @code{GDB}
28884 compatible debugging information. It is then possible to break anywhere in
28885 the process. Let's suppose here that the main procedure is named
28886 @code{ada_main} and that in the DLL there is an entry point named
28887 @code{ada_dll}.
28889 @noindent
28890 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28891 program must have been built with the debugging information (see GNAT -g
28892 switch). Here are the step-by-step instructions for debugging it:
28894 @enumerate 1
28895 @item Launch @code{GDB} on the main program.
28897 @smallexample
28898 $ gdb -nw ada_main
28899 @end smallexample
28901 @item Start the program and stop at the beginning of the main procedure
28903 @smallexample
28904 (gdb) start
28905 @end smallexample
28907 @noindent
28908 This step is required to be able to set a breakpoint inside the DLL. As long
28909 as the program is not run, the DLL is not loaded. This has the
28910 consequence that the DLL debugging information is also not loaded, so it is not
28911 possible to set a breakpoint in the DLL.
28913 @item Set a breakpoint inside the DLL
28915 @smallexample
28916 (gdb) break ada_dll
28917 (gdb) cont
28918 @end smallexample
28920 @end enumerate
28922 @noindent
28923 At this stage a breakpoint is set inside the DLL. From there on
28924 you can use the standard approach to debug the whole program
28925 (@pxref{Running and Debugging Ada Programs}).
28927 @ignore
28928 @c This used to work, probably because the DLLs were non-relocatable
28929 @c keep this section around until the problem is sorted out.
28931 To break on the @code{DllMain} routine it is not possible to follow
28932 the procedure above. At the time the program stop on @code{ada_main}
28933 the @code{DllMain} routine as already been called. Either you can use
28934 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28936 @enumerate 1
28937 @item Launch @code{GDB} on the main program.
28939 @smallexample
28940 $ gdb ada_main
28941 @end smallexample
28943 @item Load DLL symbols
28945 @smallexample
28946 (gdb) add-sym api.dll
28947 @end smallexample
28949 @item Set a breakpoint inside the DLL
28951 @smallexample
28952 (gdb) break ada_dll.adb:45
28953 @end smallexample
28955 Note that at this point it is not possible to break using the routine symbol
28956 directly as the program is not yet running. The solution is to break
28957 on the proper line (break in @file{ada_dll.adb} line 45).
28959 @item Start the program
28961 @smallexample
28962 (gdb) run
28963 @end smallexample
28965 @end enumerate
28966 @end ignore
28968 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28969 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28971 @menu
28972 * Debugging the DLL Directly::
28973 * Attaching to a Running Process::
28974 @end menu
28976 @noindent
28977 In this case things are slightly more complex because it is not possible to
28978 start the main program and then break at the beginning to load the DLL and the
28979 associated DLL debugging information. It is not possible to break at the
28980 beginning of the program because there is no @code{GDB} debugging information,
28981 and therefore there is no direct way of getting initial control. This
28982 section addresses this issue by describing some methods that can be used
28983 to break somewhere in the DLL to debug it.
28985 @noindent
28986 First suppose that the main procedure is named @code{main} (this is for
28987 example some C code built with Microsoft Visual C) and that there is a
28988 DLL named @code{test.dll} containing an Ada entry point named
28989 @code{ada_dll}.
28991 @noindent
28992 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28993 been built with debugging information (see GNAT -g option).
28995 @node Debugging the DLL Directly
28996 @subsubsection Debugging the DLL Directly
28998 @enumerate 1
28999 @item
29000 Find out the executable starting address
29002 @smallexample
29003 $ objdump --file-header main.exe
29004 @end smallexample
29006 The starting address is reported on the last line. For example:
29008 @smallexample
29009 main.exe:     file format pei-i386
29010 architecture: i386, flags 0x0000010a:
29011 EXEC_P, HAS_DEBUG, D_PAGED
29012 start address 0x00401010
29013 @end smallexample
29015 @item
29016 Launch the debugger on the executable.
29018 @smallexample
29019 $ gdb main.exe
29020 @end smallexample
29022 @item
29023 Set a breakpoint at the starting address, and launch the program.
29025 @smallexample
29026 $ (gdb) break *0x00401010
29027 $ (gdb) run
29028 @end smallexample
29030 The program will stop at the given address.
29032 @item
29033 Set a breakpoint on a DLL subroutine.
29035 @smallexample
29036 (gdb) break ada_dll.adb:45
29037 @end smallexample
29039 Or if you want to break using a symbol on the DLL, you need first to
29040 select the Ada language (language used by the DLL).
29042 @smallexample
29043 (gdb) set language ada
29044 (gdb) break ada_dll
29045 @end smallexample
29047 @item
29048 Continue the program.
29050 @smallexample
29051 (gdb) cont
29052 @end smallexample
29054 @noindent
29055 This will run the program until it reaches the breakpoint that has been
29056 set. From that point you can use the standard way to debug a program
29057 as described in (@pxref{Running and Debugging Ada Programs}).
29059 @end enumerate
29061 @noindent
29062 It is also possible to debug the DLL by attaching to a running process.
29064 @node Attaching to a Running Process
29065 @subsubsection Attaching to a Running Process
29066 @cindex DLL debugging, attach to process
29068 @noindent
29069 With @code{GDB} it is always possible to debug a running process by
29070 attaching to it. It is possible to debug a DLL this way. The limitation
29071 of this approach is that the DLL must run long enough to perform the
29072 attach operation. It may be useful for instance to insert a time wasting
29073 loop in the code of the DLL to meet this criterion.
29075 @enumerate 1
29077 @item Launch the main program @file{main.exe}.
29079 @smallexample
29080 $ main
29081 @end smallexample
29083 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29084 that the process PID for @file{main.exe} is 208.
29086 @item Launch gdb.
29088 @smallexample
29089 $ gdb
29090 @end smallexample
29092 @item Attach to the running process to be debugged.
29094 @smallexample
29095 (gdb) attach 208
29096 @end smallexample
29098 @item Load the process debugging information.
29100 @smallexample
29101 (gdb) symbol-file main.exe
29102 @end smallexample
29104 @item Break somewhere in the DLL.
29106 @smallexample
29107 (gdb) break ada_dll
29108 @end smallexample
29110 @item Continue process execution.
29112 @smallexample
29113 (gdb) cont
29114 @end smallexample
29116 @end enumerate
29118 @noindent
29119 This last step will resume the process execution, and stop at
29120 the breakpoint we have set. From there you can use the standard
29121 approach to debug a program as described in
29122 (@pxref{Running and Debugging Ada Programs}).
29124 @node Setting Stack Size from gnatlink
29125 @section Setting Stack Size from @command{gnatlink}
29127 @noindent
29128 It is possible to specify the program stack size at link time. On modern
29129 versions of Windows, starting with XP, this is mostly useful to set the size of
29130 the main stack (environment task). The other task stacks are set with pragma
29131 Storage_Size or with the @command{gnatbind -d} command.
29133 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
29134 reserve size of individual tasks, the link-time stack size applies to all
29135 tasks, and pragma Storage_Size has no effect.
29136 In particular, Stack Overflow checks are made against this
29137 link-time specified size.
29139 This setting can be done with
29140 @command{gnatlink} using either:
29142 @itemize @bullet
29144 @item using @option{-Xlinker} linker option
29146 @smallexample
29147 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29148 @end smallexample
29150 This sets the stack reserve size to 0x10000 bytes and the stack commit
29151 size to 0x1000 bytes.
29153 @item using @option{-Wl} linker option
29155 @smallexample
29156 $ gnatlink hello -Wl,--stack=0x1000000
29157 @end smallexample
29159 This sets the stack reserve size to 0x1000000 bytes. Note that with
29160 @option{-Wl} option it is not possible to set the stack commit size
29161 because the coma is a separator for this option.
29163 @end itemize
29165 @node Setting Heap Size from gnatlink
29166 @section Setting Heap Size from @command{gnatlink}
29168 @noindent
29169 Under Windows systems, it is possible to specify the program heap size from
29170 @command{gnatlink} using either:
29172 @itemize @bullet
29174 @item using @option{-Xlinker} linker option
29176 @smallexample
29177 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29178 @end smallexample
29180 This sets the heap reserve size to 0x10000 bytes and the heap commit
29181 size to 0x1000 bytes.
29183 @item using @option{-Wl} linker option
29185 @smallexample
29186 $ gnatlink hello -Wl,--heap=0x1000000
29187 @end smallexample
29189 This sets the heap reserve size to 0x1000000 bytes. Note that with
29190 @option{-Wl} option it is not possible to set the heap commit size
29191 because the coma is a separator for this option.
29193 @end itemize
29195 @node Mac OS Topics
29196 @appendix Mac OS Topics
29197 @cindex OS X
29199 @noindent
29200 This chapter describes topics that are specific to Apple's OS X
29201 platform.
29203 @menu
29204 * Codesigning the Debugger::
29205 @end menu
29207 @node Codesigning the Debugger
29208 @section Codesigning the Debugger
29210 @noindent
29211 The Darwin Kernel requires the debugger to have special permissions
29212 before it is allowed to control other processes. These permissions
29213 are granted by codesigning the GDB executable. Without these
29214 permissions, the debugger will report error messages such as:
29216 @smallexample
29217 Starting program: /x/y/foo
29218 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
29219  (please check gdb is codesigned - see taskgated(8))
29220 @end smallexample
29222 Codesigning requires a certificate.  The following procedure explains
29223 how to create one:
29225 @itemize @bullet
29226 @item Start the Keychain Access application (in
29227 /Applications/Utilities/Keychain Access.app)
29229 @item Select the Keychain Access -> Certificate Assistant ->
29230 Create a Certificate... menu
29232 @item Then:
29234 @itemize @bullet
29235 @item Choose a name for the new certificate (this procedure will use
29236 "gdb-cert" as an example)
29238 @item Set "Identity Type" to "Self Signed Root"
29240 @item Set "Certificate Type" to "Code Signing"
29242 @item Activate the "Let me override defaults" option
29244 @end itemize
29246 @item Click several times on "Continue" until the "Specify a Location
29247 For The Certificate" screen appears, then set "Keychain" to "System"
29249 @item Click on "Continue" until the certificate is created
29251 @item Finally, in the view, double-click on the new certificate,
29252 and set "When using this certificate" to "Always Trust"
29254 @item Exit the Keychain Access application and restart the computer
29255 (this is unfortunately required)
29257 @end itemize
29259 Once a certificate has been created, the debugger can be codesigned
29260 as follow. In a Terminal, run the following command...
29262 @smallexample
29263 codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
29264 @end smallexample
29266 ... where "gdb-cert" should be replaced by the actual certificate
29267 name chosen above, and <gnat_install_prefix> should be replaced by
29268 the location where you installed GNAT.
29270 @c **********************************
29271 @c * GNU Free Documentation License *
29272 @c **********************************
29273 @include fdl.texi
29274 @c GNU Free Documentation License
29276 @node Index
29277 @unnumbered Index
29279 @printindex cp
29281 @contents
29282 @c Put table of contents at end, otherwise it precedes the "title page" in
29283 @c the .txt version
29284 @c Edit the pdf file to move the contents to the beginning, after the title
29285 @c page
29287 @bye