2014-10-20 Gary Dismukes <dismukes@adacore.com>
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob1290bf58e477065d4496bc19c3cdeaf8096935c3
2 \input texinfo   @c -*-texinfo-*-
3 @c %**start of header
5 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c                                                                            o
7 @c                            GNAT DOCUMENTATION                              o
8 @c                                                                            o
9 @c                             G N A T _ U G N                                o
10 @c                                                                            o
11 @c           Copyright (C) 1992-2014, Free Software Foundation, Inc.          o
12 @c                                                                            o
13 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
15 @setfilename gnat_ugn.info
17 @copying
18 Copyright @copyright{} 1995-2014 Free Software Foundation,
19 Inc.
21 Permission is granted to copy, distribute and/or modify this document
22 under the terms of the GNU Free Documentation License, Version 1.3 or
23 any later version published by the Free Software Foundation; with no
24 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
25 Texts.  A copy of the license is included in the section entitled
26 ``GNU Free Documentation License''.
27 @end copying
29 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
31 @c                           GNAT_UGN Style Guide
33 @c  1. Always put a @noindent on the line before the first paragraph
34 @c     after any of these commands:
36 @c          @chapter
37 @c          @section
38 @c          @subsection
39 @c          @subsubsection
40 @c          @subsubsubsection
42 @c          @end smallexample
43 @c          @end itemize
44 @c          @end enumerate
46 @c  2. DO NOT use @example. Use @smallexample instead.
47 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
48 @c        context.  These can interfere with the readability of the texi
49 @c        source file.  Instead, use one of the following annotated
50 @c        @smallexample commands, and preprocess the texi file with the
51 @c        ada2texi tool (which generates appropriate highlighting):
52 @c        @smallexample @c ada
53 @c        @smallexample @c adanocomment
54 @c        @smallexample @c projectfile
55 @c     b) The "@c ada" markup will result in boldface for reserved words
56 @c        and italics for comments
57 @c     c) The "@c adanocomment" markup will result only in boldface for
58 @c        reserved words (comments are left alone)
59 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
60 @c        of reserved words include the new reserved words for project files
62 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
63 @c     command must be preceded by two empty lines
65 @c  4. The @item command should be on a line of its own if it is in an
66 @c     @itemize or @enumerate command.
68 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
69 @c     or "ali".
71 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
72 @c     cause the document build to fail.
74 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
75 @c     This command inhibits page breaks, so long examples in a @cartouche can
76 @c     lead to large, ugly patches of empty space on a page.
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
80 @set NOW January 2007
81 @c This flag is used where the text refers to conditions that exist when the
82 @c text was entered into the document but which may change over time.
83 @c Update the setting for the flag, and (if necessary) the text surrounding,
84 @c the references to the flag, on future doc revisions:
85 @c search for @value{NOW}.
87 @set FSFEDITION
88 @set EDITION GNAT
90 @set PLATFORM
92 @c @ovar(ARG)
93 @c ----------
94 @c The ARG is an optional argument.  To be used for macro arguments in
95 @c their documentation (@defmac).
96 @macro ovar{varname}
97 @r{[}@var{\varname\}@r{]}@c
98 @end macro
99 @c Status as of November 2009:
100 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
101 @c differently, and faulty output is produced by one or the other
102 @c depending on whether the "@c" is present or absent.
103 @c As a result, the @ovar macro is not used, and all invocations
104 @c of the @ovar macro have been expanded inline.
107 @settitle @value{EDITION} User's Guide
108 @dircategory GNU Ada tools
109 @direntry
110 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
111 @end direntry
113 @include gcc-common.texi
115 @setchapternewpage odd
116 @syncodeindex fn cp
117 @c %**end of header
119 @titlepage
120 @title @value{EDITION} User's Guide
122 @sp 2
124 @subtitle GNAT, The GNU Ada Development Environment
125 @versionsubtitle
126 @author AdaCore
128 @page
129 @vskip 0pt plus 1filll
131 @insertcopying
133 @end titlepage
135 @ifnottex
136 @node Top, About This Guide, (dir), (dir)
137 @top @value{EDITION} User's Guide
139 @noindent
140 @value{EDITION} User's Guide @value{PLATFORM}
142 @noindent
143 GNAT, The GNU Ada Development Environment@*
144 GCC version @value{version-GCC}@*
146 @noindent
147 AdaCore@*
149 @menu
150 * About This Guide::
151 * Getting Started with GNAT::
152 * The GNAT Compilation Model::
153 * Compiling with gcc::
154 * Binding with gnatbind::
155 * Linking with gnatlink::
156 * The GNAT Make Program gnatmake::
157 * Improving Performance::
158 * Renaming Files with gnatchop::
159 * Configuration Pragmas::
160 * Handling Arbitrary File Naming Conventions with gnatname::
161 * GNAT Project Manager::
162 * Tools Supporting Project Files::
163 * The Cross-Referencing Tools gnatxref and gnatfind::
164 @ifclear FSFEDITION
165 * The GNAT Pretty-Printer gnatpp::
166 * The Ada-to-XML converter gnat2xml::
167 * The GNAT Metrics Tool gnatmetric::
168 @end ifclear
169 * File Name Krunching with gnatkr::
170 * Preprocessing with gnatprep::
171 * The GNAT Library Browser gnatls::
172 * Cleaning Up with gnatclean::
173 * GNAT and Libraries::
174 * Using the GNU make Utility::
175 * Memory Management Issues::
176 * Stack Related Facilities::
177 @ifclear FSFEDITION
178 * Verifying Properties with gnatcheck::
179 * Creating Sample Bodies with gnatstub::
180 * Creating Unit Tests with gnattest::
181 @end ifclear
182 * Performing Dimensionality Analysis in GNAT::
183 * Generating Ada Bindings for C and C++ headers::
184 * Other Utility Programs::
185 * Code Coverage and Profiling::
186 * Running and Debugging Ada Programs::
187 * Platform-Specific Information for the Run-Time Libraries::
188 * Example of Binder Output File::
189 * Elaboration Order Handling in GNAT::
190 * Overflow Check Handling in GNAT::
191 * Conditional Compilation::
192 * Inline Assembler::
193 * Writing Portable Fixed-Point Declarations::
194 * Compatibility and Porting Guide::
195 * Microsoft Windows Topics::
196 * Mac OS Topics::
197 * GNU Free Documentation License::
198 * Index::
199 @end menu
200 @end ifnottex
202 @node About This Guide
203 @unnumbered About This Guide
205 @noindent
206 This guide describes the use of @value{EDITION},
207 a compiler and software development
208 toolset for the full Ada programming language.
209 It documents the features of the compiler and tools, and explains
210 how to use them to build Ada applications.
212 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
213 invoked in Ada 83 compatibility mode.
214 By default, @value{EDITION} assumes Ada 2012, but you can override with a
215 compiler switch (@pxref{Compiling Different Versions of Ada})
216 to explicitly specify the language version.
217 Throughout this manual, references to ``Ada'' without a year suffix
218 apply to all Ada 95/2005/2012 versions of the language.
220 @ifclear FSFEDITION
221 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
222 ``GNAT'' in the remainder of this document.
223 @end ifclear
226 @menu
227 * What This Guide Contains::
228 * What You Should Know before Reading This Guide::
229 * Related Information::
230 * Conventions::
231 @end menu
233 @node What This Guide Contains
234 @unnumberedsec What This Guide Contains
236 @noindent
237 This guide contains the following chapters:
238 @itemize @bullet
240 @item
241 @ref{Getting Started with GNAT}, describes how to get started compiling
242 and running Ada programs with the GNAT Ada programming environment.
243 @item
244 @ref{The GNAT Compilation Model}, describes the compilation model used
245 by GNAT.
247 @item
248 @ref{Compiling with gcc}, describes how to compile
249 Ada programs with @command{gcc}, the Ada compiler.
251 @item
252 @ref{Binding with gnatbind}, describes how to
253 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
254 utility.
256 @item
257 @ref{Linking with gnatlink},
258 describes @command{gnatlink}, a
259 program that provides for linking using the GNAT run-time library to
260 construct a program. @command{gnatlink} can also incorporate foreign language
261 object units into the executable.
263 @item
264 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
265 utility that automatically determines the set of sources
266 needed by an Ada compilation unit, and executes the necessary compilations
267 binding and link.
269 @item
270 @ref{Improving Performance}, shows various techniques for making your
271 Ada program run faster or take less space and describes the effect of
272 the compiler's optimization switch.
273 It also describes
274 @ifclear FSFEDITION
275 the @command{gnatelim} tool and
276 @end ifclear
277 unused subprogram/data elimination.
279 @item
280 @ref{Renaming Files with gnatchop}, describes
281 @code{gnatchop}, a utility that allows you to preprocess a file that
282 contains Ada source code, and split it into one or more new files, one
283 for each compilation unit.
285 @item
286 @ref{Configuration Pragmas}, describes the configuration pragmas
287 handled by GNAT.
289 @item
290 @ref{Handling Arbitrary File Naming Conventions with gnatname},
291 shows how to override the default GNAT file naming conventions,
292 either for an individual unit or globally.
294 @item
295 @ref{GNAT Project Manager}, describes how to use project files
296 to organize large projects.
298 @item
299 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
300 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
301 way to navigate through sources.
303 @ifclear FSFEDITION
304 @item
305 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
306 version of an Ada source file with control over casing, indentation,
307 comment placement, and other elements of program presentation style.
308 @end ifclear
310 @ifclear FSFEDITION
311 @item
312 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
313 source code into XML.
314 @end ifclear
316 @ifclear FSFEDITION
317 @item
318 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
319 metrics for an Ada source file, such as the number of types and subprograms,
320 and assorted complexity measures.
321 @end ifclear
323 @item
324 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
325 file name krunching utility, used to handle shortened
326 file names on operating systems with a limit on the length of names.
328 @item
329 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
330 preprocessor utility that allows a single source file to be used to
331 generate multiple or parameterized source files by means of macro
332 substitution.
334 @item
335 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
336 utility that displays information about compiled units, including dependences
337 on the corresponding sources files, and consistency of compilations.
339 @item
340 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
341 to delete files that are produced by the compiler, binder and linker.
343 @item
344 @ref{GNAT and Libraries}, describes the process of creating and using
345 Libraries with GNAT. It also describes how to recompile the GNAT run-time
346 library.
348 @item
349 @ref{Using the GNU make Utility}, describes some techniques for using
350 the GNAT toolset in Makefiles.
352 @item
353 @ref{Memory Management Issues}, describes some useful predefined storage pools
354 and in particular the GNAT Debug Pool facility, which helps detect incorrect
355 memory references.
356 @ifclear FSFEDITION
357 It also describes @command{gnatmem}, a utility that monitors dynamic
358 allocation and deallocation and helps detect ``memory leaks''.
359 @end ifclear
361 @item
362 @ref{Stack Related Facilities}, describes some useful tools associated with
363 stack checking and analysis.
365 @ifclear FSFEDITION
366 @item
367 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
368 a utility that checks Ada code against a set of rules.
370 @item
371 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
372 a utility that generates empty but compilable bodies for library units.
373 @end ifclear
375 @ifclear FSFEDITION
376 @item
377 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
378 a utility that generates unit testing templates for library units.
379 @end ifclear
381 @item
382 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
383 facilities used in GNAT to declare dimensioned objects, and to verify that
384 uses of these objects are consistent with their given physical dimensions
385 (so that meters cannot be assigned to kilograms, and so on).
387 @item
388 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
389 generate automatically Ada bindings from C and C++ headers.
391 @item
392 @ref{Other Utility Programs}, discusses several other GNAT utilities,
393 including @code{gnathtml}.
395 @item
396 @ref{Code Coverage and Profiling}, describes how to perform a structural
397 coverage and profile the execution of Ada programs.
399 @item
400 @ref{Running and Debugging Ada Programs}, describes how to run and debug
401 Ada programs.
404 @item
405 @ref{Platform-Specific Information for the Run-Time Libraries},
406 describes the various run-time
407 libraries supported by GNAT on various platforms and explains how to
408 choose a particular library.
410 @item
411 @ref{Example of Binder Output File}, shows the source code for the binder
412 output file for a sample program.
414 @item
415 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
416 you deal with elaboration order issues.
418 @item
419 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
420 you deal with arithmetic overflow issues.
422 @item
423 @ref{Conditional Compilation}, describes how to model conditional compilation,
424 both with Ada in general and with GNAT facilities in particular.
426 @item
427 @ref{Inline Assembler}, shows how to use the inline assembly facility
428 in an Ada program.
430 @item
431 @ref{Writing Portable Fixed-Point Declarations}, gives some guidance on
432 defining portable fixed-point types.
434 @item
435 @ref{Compatibility and Porting Guide}, contains sections on compatibility
436 of GNAT with other Ada development environments (including Ada 83 systems),
437 to assist in porting code from those environments.
439 @item
440 @ref{Microsoft Windows Topics}, presents information relevant to the
441 Microsoft Windows platform.
443 @item
444 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
445 platform.
446 @end itemize
448 @c *************************************************
449 @node What You Should Know before Reading This Guide
450 @c *************************************************
451 @unnumberedsec What You Should Know before Reading This Guide
453 @cindex Ada 95 Language Reference Manual
454 @cindex Ada 2005 Language Reference Manual
455 @noindent
456 This guide assumes a basic familiarity with the Ada 95 language, as
457 described in the International Standard ANSI/ISO/IEC-8652:1995, January
458 1995.
459 It does not require knowledge of the new features introduced by Ada 2005,
460 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
461 and Amendment 1).
462 Both reference manuals are included in the GNAT documentation
463 package.
465 @node Related Information
466 @unnumberedsec Related Information
468 @noindent
469 For further information about related tools, refer to the following
470 documents:
472 @itemize @bullet
473 @item
474 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
475 Reference Manual}, which contains all reference material for the GNAT
476 implementation of Ada.
478 @item
479 @cite{Using the GNAT Programming Studio}, which describes the GPS
480 Integrated Development Environment.
482 @item
483 @cite{GNAT Programming Studio Tutorial}, which introduces the
484 main GPS features through examples.
486 @item
487 @cite{Ada 95 Reference Manual}, which contains reference
488 material for the Ada 95 programming language.
490 @item
491 @cite{Ada 2005 Reference Manual}, which contains reference
492 material for the Ada 2005 programming language.
494 @item
495 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
496 for all details on the use of the GNU source-level debugger.
498 @item
499 @xref{Top,, The extensible self-documenting text editor, emacs,
500 GNU Emacs Manual},
501 for full information on the extensible editor and programming
502 environment Emacs.
504 @end itemize
506 @c **************
507 @node Conventions
508 @unnumberedsec Conventions
509 @cindex Conventions
510 @cindex Typographical conventions
512 @noindent
513 Following are examples of the typographical and graphic conventions used
514 in this guide:
516 @itemize @bullet
517 @item
518 @code{Functions}, @command{utility program names}, @code{standard names},
519 and @code{classes}.
521 @item
522 @option{Option flags}
524 @item
525 @file{File names}, @samp{button names}, and @samp{field names}.
527 @item
528 @code{Variables}, @env{environment variables}, and @var{metasyntactic
529 variables}.
531 @item
532 @emph{Emphasis}.
534 @item
535 @r{[}optional information or parameters@r{]}
537 @item
538 Examples are described by text
539 @smallexample
540 and then shown this way.
541 @end smallexample
542 @end itemize
544 @noindent
545 Commands that are entered by the user are preceded in this manual by the
546 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
547 uses this sequence as a prompt, then the commands will appear exactly as
548 you see them in the manual. If your system uses some other prompt, then
549 the command will appear with the @code{$} replaced by whatever prompt
550 character you are using.
552 Full file names are shown with the ``@code{/}'' character
553 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
554 If you are using GNAT on a Windows platform, please note that
555 the ``@code{\}'' character should be used instead.
557 @c ****************************
558 @node Getting Started with GNAT
559 @chapter Getting Started with GNAT
561 @noindent
562 This chapter describes some simple ways of using GNAT to build
563 executable Ada programs.
564 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
565 show how to use the command line environment.
566 @ref{Introduction to GPS}, provides a brief
567 introduction to the GNAT Programming Studio, a visually-oriented
568 Integrated Development Environment for GNAT.
569 GPS offers a graphical ``look and feel'', support for development in
570 other programming languages, comprehensive browsing features, and
571 many other capabilities.
572 For information on GPS please refer to
573 @cite{Using the GNAT Programming Studio}.
575 @menu
576 * Running GNAT::
577 * Running a Simple Ada Program::
578 * Running a Program with Multiple Units::
579 * Using the gnatmake Utility::
580 * Introduction to GPS::
581 @end menu
583 @node Running GNAT
584 @section Running GNAT
586 @noindent
587 Three steps are needed to create an executable file from an Ada source
588 file:
590 @enumerate
591 @item
592 The source file(s) must be compiled.
593 @item
594 The file(s) must be bound using the GNAT binder.
595 @item
596 All appropriate object files must be linked to produce an executable.
597 @end enumerate
599 @noindent
600 All three steps are most commonly handled by using the @command{gnatmake}
601 utility program that, given the name of the main program, automatically
602 performs the necessary compilation, binding and linking steps.
604 @node Running a Simple Ada Program
605 @section Running a Simple Ada Program
607 @noindent
608 Any text editor may be used to prepare an Ada program.
609 (If @code{Emacs} is
610 used, the optional Ada mode may be helpful in laying out the program.)
612 program text is a normal text file. We will assume in our initial
613 example that you have used your editor to prepare the following
614 standard format text file:
616 @smallexample @c ada
617 @cartouche
618 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
619 @b{procedure} Hello @b{is}
620 @b{begin}
621    Put_Line ("Hello WORLD!");
622 @b{end} Hello;
623 @end cartouche
624 @end smallexample
626 @noindent
627 This file should be named @file{hello.adb}.
628 With the normal default file naming conventions, GNAT requires
629 that each file
630 contain a single compilation unit whose file name is the
631 unit name,
632 with periods replaced by hyphens; the
633 extension is @file{ads} for a
634 spec and @file{adb} for a body.
635 You can override this default file naming convention by use of the
636 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
637 Alternatively, if you want to rename your files according to this default
638 convention, which is probably more convenient if you will be using GNAT
639 for all your compilations, then the @code{gnatchop} utility
640 can be used to generate correctly-named source files
641 (@pxref{Renaming Files with gnatchop}).
643 You can compile the program using the following command (@code{$} is used
644 as the command prompt in the examples in this document):
646 @smallexample
647 $ gcc -c hello.adb
648 @end smallexample
650 @noindent
651 @command{gcc} is the command used to run the compiler. This compiler is
652 capable of compiling programs in several languages, including Ada and
653 C. It assumes that you have given it an Ada program if the file extension is
654 either @file{.ads} or @file{.adb}, and it will then call
655 the GNAT compiler to compile the specified file.
657 The @option{-c} switch is required. It tells @command{gcc} to only do a
658 compilation. (For C programs, @command{gcc} can also do linking, but this
659 capability is not used directly for Ada programs, so the @option{-c}
660 switch must always be present.)
662 This compile command generates a file
663 @file{hello.o}, which is the object
664 file corresponding to your Ada program. It also generates
665 an ``Ada Library Information'' file @file{hello.ali},
666 which contains additional information used to check
667 that an Ada program is consistent.
668 To build an executable file,
669 use @code{gnatbind} to bind the program
670 and @command{gnatlink} to link it. The
671 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
672 @file{ALI} file, but the default extension of @file{.ali} can
673 be omitted. This means that in the most common case, the argument
674 is simply the name of the main program:
676 @smallexample
677 $ gnatbind hello
678 $ gnatlink hello
679 @end smallexample
681 @noindent
682 A simpler method of carrying out these steps is to use
683 @command{gnatmake},
684 a master program that invokes all the required
685 compilation, binding and linking tools in the correct order. In particular,
686 @command{gnatmake} automatically recompiles any sources that have been
687 modified since they were last compiled, or sources that depend
688 on such modified sources, so that ``version skew'' is avoided.
689 @cindex Version skew (avoided by @command{gnatmake})
691 @smallexample
692 $ gnatmake hello.adb
693 @end smallexample
695 @noindent
696 The result is an executable program called @file{hello}, which can be
697 run by entering:
699 @smallexample
700 $ hello
701 @end smallexample
703 @noindent
704 assuming that the current directory is on the search path
705 for executable programs.
707 @noindent
708 and, if all has gone well, you will see
710 @smallexample
711 Hello WORLD!
712 @end smallexample
714 @noindent
715 appear in response to this command.
717 @c ****************************************
718 @node Running a Program with Multiple Units
719 @section Running a Program with Multiple Units
721 @noindent
722 Consider a slightly more complicated example that has three files: a
723 main program, and the spec and body of a package:
725 @smallexample @c ada
726 @cartouche
727 @group
728 @b{package} Greetings @b{is}
729    @b{procedure} Hello;
730    @b{procedure} Goodbye;
731 @b{end} Greetings;
733 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
734 @b{package} @b{body} Greetings @b{is}
735    @b{procedure} Hello @b{is}
736    @b{begin}
737       Put_Line ("Hello WORLD!");
738    @b{end} Hello;
740    @b{procedure} Goodbye @b{is}
741    @b{begin}
742       Put_Line ("Goodbye WORLD!");
743    @b{end} Goodbye;
744 @b{end} Greetings;
745 @end group
747 @group
748 @b{with} Greetings;
749 @b{procedure} Gmain @b{is}
750 @b{begin}
751    Greetings.Hello;
752    Greetings.Goodbye;
753 @b{end} Gmain;
754 @end group
755 @end cartouche
756 @end smallexample
758 @noindent
759 Following the one-unit-per-file rule, place this program in the
760 following three separate files:
762 @table @file
763 @item greetings.ads
764 spec of package @code{Greetings}
766 @item greetings.adb
767 body of package @code{Greetings}
769 @item gmain.adb
770 body of main program
771 @end table
773 @noindent
774 To build an executable version of
775 this program, we could use four separate steps to compile, bind, and link
776 the program, as follows:
778 @smallexample
779 $ gcc -c gmain.adb
780 $ gcc -c greetings.adb
781 $ gnatbind gmain
782 $ gnatlink gmain
783 @end smallexample
785 @noindent
786 Note that there is no required order of compilation when using GNAT.
787 In particular it is perfectly fine to compile the main program first.
788 Also, it is not necessary to compile package specs in the case where
789 there is an accompanying body; you only need to compile the body. If you want
790 to submit these files to the compiler for semantic checking and not code
791 generation, then use the
792 @option{-gnatc} switch:
794 @smallexample
795 $ gcc -c greetings.ads -gnatc
796 @end smallexample
798 @noindent
799 Although the compilation can be done in separate steps as in the
800 above example, in practice it is almost always more convenient
801 to use the @command{gnatmake} tool. All you need to know in this case
802 is the name of the main program's source file. The effect of the above four
803 commands can be achieved with a single one:
805 @smallexample
806 $ gnatmake gmain.adb
807 @end smallexample
809 @noindent
810 In the next section we discuss the advantages of using @command{gnatmake} in
811 more detail.
813 @c *****************************
814 @node Using the gnatmake Utility
815 @section Using the @command{gnatmake} Utility
817 @noindent
818 If you work on a program by compiling single components at a time using
819 @command{gcc}, you typically keep track of the units you modify. In order to
820 build a consistent system, you compile not only these units, but also any
821 units that depend on the units you have modified.
822 For example, in the preceding case,
823 if you edit @file{gmain.adb}, you only need to recompile that file. But if
824 you edit @file{greetings.ads}, you must recompile both
825 @file{greetings.adb} and @file{gmain.adb}, because both files contain
826 units that depend on @file{greetings.ads}.
828 @code{gnatbind} will warn you if you forget one of these compilation
829 steps, so that it is impossible to generate an inconsistent program as a
830 result of forgetting to do a compilation. Nevertheless it is tedious and
831 error-prone to keep track of dependencies among units.
832 One approach to handle the dependency-bookkeeping is to use a
833 makefile. However, makefiles present maintenance problems of their own:
834 if the dependencies change as you change the program, you must make
835 sure that the makefile is kept up-to-date manually, which is also an
836 error-prone process.
838 The @command{gnatmake} utility takes care of these details automatically.
839 Invoke it using either one of the following forms:
841 @smallexample
842 $ gnatmake gmain.adb
843 $ gnatmake gmain
844 @end smallexample
846 @noindent
847 The argument is the name of the file containing the main program;
848 you may omit the extension. @command{gnatmake}
849 examines the environment, automatically recompiles any files that need
850 recompiling, and binds and links the resulting set of object files,
851 generating the executable file, @file{gmain}.
852 In a large program, it
853 can be extremely helpful to use @command{gnatmake}, because working out by hand
854 what needs to be recompiled can be difficult.
856 Note that @command{gnatmake}
857 takes into account all the Ada rules that
858 establish dependencies among units. These include dependencies that result
859 from inlining subprogram bodies, and from
860 generic instantiation. Unlike some other
861 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
862 found by the compiler on a previous compilation, which may possibly
863 be wrong when sources change. @command{gnatmake} determines the exact set of
864 dependencies from scratch each time it is run.
867 @node Introduction to GPS
868 @section Introduction to GPS
869 @cindex GPS (GNAT Programming Studio)
870 @cindex GNAT Programming Studio (GPS)
871 @noindent
872 Although the command line interface (@command{gnatmake}, etc.) alone
873 is sufficient, a graphical Interactive Development
874 Environment can make it easier for you to compose, navigate, and debug
875 programs.  This section describes the main features of GPS
876 (``GNAT Programming Studio''), the GNAT graphical IDE.
877 You will see how to use GPS to build and debug an executable, and
878 you will also learn some of the basics of the GNAT ``project'' facility.
880 GPS enables you to do much more than is presented here;
881 e.g., you can produce a call graph, interface to a third-party
882 Version Control System, and inspect the generated assembly language
883 for a program.
884 Indeed, GPS also supports languages other than Ada.
885 Such additional information, and an explanation of all of the GPS menu
886 items. may be found in the on-line help, which includes
887 a user's guide and a tutorial (these are also accessible from the GNAT
888 startup menu).
890 @menu
891 * Building a New Program with GPS::
892 * Simple Debugging with GPS::
893 @end menu
895 @node Building a New Program with GPS
896 @subsection Building a New Program with GPS
897 @noindent
898 GPS invokes the GNAT compilation tools using information
899 contained in a @emph{project} (also known as a @emph{project file}):
900 a collection of properties such
901 as source directories, identities of main subprograms, tool switches, etc.,
902 and their associated values.
903 See @ref{GNAT Project Manager} for details.
904 In order to run GPS, you will need to either create a new project
905 or else open an existing one.
907 This section will explain how you can use GPS to create a project,
908 to associate Ada source files with a project, and to build and run
909 programs.
911 @enumerate
912 @item @emph{Creating a project}
914 Invoke GPS, either from the command line or the platform's IDE.
915 After it starts, GPS will display a ``Welcome'' screen with three
916 radio buttons:
918 @itemize @bullet
919 @item
920 @code{Start with default project in directory}
922 @item
923 @code{Create new project with wizard}
925 @item
926 @code{Open existing project}
927 @end itemize
929 @noindent
930 Select @code{Create new project with wizard} and press @code{OK}.
931 A new window will appear.  In the text box labeled with
932 @code{Enter the name of the project to create}, type @file{sample}
933 as the project name.
934 In the next box, browse to choose the directory in which you
935 would like to create the project file.
936 After selecting an appropriate directory, press @code{Forward}.
938 A window will appear with the title
939 @code{Version Control System Configuration}.
940 Simply press @code{Forward}.
942 A window will appear with the title
943 @code{Please select the source directories for this project}.
944 The directory that you specified for the project file will be selected
945 by default as the one to use for sources; simply press @code{Forward}.
947 A window will appear with the title
948 @code{Please select the build directory for this project}.
949 The directory that you specified for the project file will be selected
950 by default for object files and executables;
951 simply press @code{Forward}.
953 A window will appear with the title
954 @code{Please select the main units for this project}.
955 You will supply this information later, after creating the source file.
956 Simply press @code{Forward} for now.
958 A window will appear with the title
959 @code{Please select the switches to build the project}.
960 Press @code{Apply}.  This will create a project file named
961 @file{sample.prj} in the directory that you had specified.
963 @item @emph{Creating and saving the source file}
965 After you create the new project, a GPS window will appear, which is
966 partitioned into two main sections:
968 @itemize @bullet
969 @item
970 A @emph{Workspace area}, initially greyed out, which you will use for
971 creating and editing source files
973 @item
974 Directly below, a @emph{Messages area}, which initially displays a
975 ``Welcome'' message.
976 (If the Messages area is not visible, drag its border upward to expand it.)
977 @end itemize
979 @noindent
980 Select @code{File} on the menu bar, and then the @code{New} command.
981 The Workspace area will become white, and you can now
982 enter the source program explicitly.
983 Type the following text
985 @smallexample @c ada
986 @group
987 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
988 @b{procedure} Hello @b{is}
989 @b{begin}
990   Put_Line("Hello from GPS!");
991 @b{end} Hello;
992 @end group
993 @end smallexample
995 @noindent
996 Select @code{File}, then @code{Save As}, and enter the source file name
997 @file{hello.adb}.
998 The file will be saved in the same directory you specified as the
999 location of the default project file.
1001 @item @emph{Updating the project file}
1003 You need to add the new source file to the project.
1004 To do this, select
1005 the @code{Project} menu and then @code{Edit project properties}.
1006 Click the @code{Main files} tab on the left, and then the
1007 @code{Add} button.
1008 Choose @file{hello.adb} from the list, and press @code{Open}.
1009 The project settings window will reflect this action.
1010 Click @code{OK}.
1012 @item @emph{Building and running the program}
1014 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1015 and select @file{hello.adb}.
1016 The Messages window will display the resulting invocations of @command{gcc},
1017 @command{gnatbind}, and @command{gnatlink}
1018 (reflecting the default switch settings from the
1019 project file that you created) and then a ``successful compilation/build''
1020 message.
1022 To run the program, choose the @code{Build} menu, then @code{Run}, and
1023 select @command{hello}.
1024 An @emph{Arguments Selection} window will appear.
1025 There are no command line arguments, so just click @code{OK}.
1027 The Messages window will now display the program's output (the string
1028 @code{Hello from GPS}), and at the bottom of the GPS window a status
1029 update is displayed (@code{Run: hello}).
1030 Close the GPS window (or select @code{File}, then @code{Exit}) to
1031 terminate this GPS session.
1032 @end enumerate
1034 @node Simple Debugging with GPS
1035 @subsection Simple Debugging with GPS
1036 @noindent
1037 This section illustrates basic debugging techniques (setting breakpoints,
1038 examining/modifying variables, single stepping).
1040 @enumerate
1041 @item @emph{Opening a project}
1043 Start GPS and select @code{Open existing project}; browse to
1044 specify the project file @file{sample.prj} that you had created in the
1045 earlier example.
1047 @item @emph{Creating a source file}
1049 Select @code{File}, then @code{New}, and type in the following program:
1051 @smallexample @c ada
1052 @group
1053 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
1054 @b{procedure} Example @b{is}
1055    Line : String (1..80);
1056    N    : Natural;
1057 @b{begin}
1058    Put_Line("Type a line of text at each prompt; an empty line to exit");
1059    @b{loop}
1060       Put(": ");
1061       Get_Line (Line, N);
1062       Put_Line (Line (1..N) );
1063       @b{exit} @b{when} N=0;
1064    @b{end} @b{loop};
1065 @b{end} Example;
1066 @end group
1067 @end smallexample
1069 @noindent
1070 Select @code{File}, then @code{Save as}, and enter the file name
1071 @file{example.adb}.
1073 @item @emph{Updating the project file}
1075 Add @code{Example} as a new main unit for the project:
1076 @enumerate a
1077 @item
1078 Select @code{Project}, then @code{Edit Project Properties}.
1080 @item
1081 Select the @code{Main files} tab, click @code{Add}, then
1082 select the file @file{example.adb} from the list, and
1083 click @code{Open}.
1084 You will see the file name appear in the list of main units
1086 @item
1087 Click @code{OK}
1088 @end enumerate
1090 @item @emph{Building/running the executable}
1092 To build the executable
1093 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1095 Run the program to see its effect (in the Messages area).
1096 Each line that you enter is displayed; an empty line will
1097 cause the loop to exit and the program to terminate.
1099 @item @emph{Debugging the program}
1101 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1102 which are required for debugging, are on by default when you create
1103 a new project.
1104 Thus unless you intentionally remove these settings, you will be able
1105 to debug any program that you develop using GPS.
1107 @enumerate a
1108 @item @emph{Initializing}
1110 Select @code{Debug}, then @code{Initialize}, then @file{example}
1112 @item @emph{Setting a breakpoint}
1114 After performing the initialization step, you will observe a small
1115 icon to the right of each line number.
1116 This serves as a toggle for breakpoints; clicking the icon will
1117 set a breakpoint at the corresponding line (the icon will change to
1118 a red circle with an ``x''), and clicking it again
1119 will remove the breakpoint / reset the icon.
1121 For purposes of this example, set a breakpoint at line 10 (the
1122 statement @code{Put_Line@ (Line@ (1..N));}
1124 @item @emph{Starting program execution}
1126 Select @code{Debug}, then @code{Run}.  When the
1127 @code{Program Arguments} window appears, click @code{OK}.
1128 A console window will appear; enter some line of text,
1129 e.g.@: @code{abcde}, at the prompt.
1130 The program will pause execution when it gets to the
1131 breakpoint, and the corresponding line is highlighted.
1133 @item @emph{Examining a variable}
1135 Move the mouse over one of the occurrences of the variable @code{N}.
1136 You will see the value (5) displayed, in ``tool tip'' fashion.
1137 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1138 You will see information about @code{N} appear in the @code{Debugger Data}
1139 pane, showing the value as 5.
1141 @item @emph{Assigning a new value to a variable}
1143 Right click on the @code{N} in the @code{Debugger Data} pane, and
1144 select @code{Set value of N}.
1145 When the input window appears, enter the value @code{4} and click
1146 @code{OK}.
1147 This value does not automatically appear in the @code{Debugger Data}
1148 pane; to see it, right click again on the @code{N} in the
1149 @code{Debugger Data} pane and select @code{Update value}.
1150 The new value, 4, will appear in red.
1152 @item @emph{Single stepping}
1154 Select @code{Debug}, then @code{Next}.
1155 This will cause the next statement to be executed, in this case the
1156 call of @code{Put_Line} with the string slice.
1157 Notice in the console window that the displayed string is simply
1158 @code{abcd} and not @code{abcde} which you had entered.
1159 This is because the upper bound of the slice is now 4 rather than 5.
1161 @item @emph{Removing a breakpoint}
1163 Toggle the breakpoint icon at line 10.
1165 @item @emph{Resuming execution from a breakpoint}
1167 Select @code{Debug}, then @code{Continue}.
1168 The program will reach the next iteration of the loop, and
1169 wait for input after displaying the prompt.
1170 This time, just hit the @kbd{Enter} key.
1171 The value of @code{N} will be 0, and the program will terminate.
1172 The console window will disappear.
1173 @end enumerate
1174 @end enumerate
1176 @node The GNAT Compilation Model
1177 @chapter The GNAT Compilation Model
1178 @cindex GNAT compilation model
1179 @cindex Compilation model
1181 @menu
1182 * Source Representation::
1183 * Foreign Language Representation::
1184 * File Naming Rules::
1185 * Using Other File Names::
1186 * Alternative File Naming Schemes::
1187 * Generating Object Files::
1188 * Source Dependencies::
1189 * The Ada Library Information Files::
1190 * Binding an Ada Program::
1191 * Mixed Language Programming::
1192 * Building Mixed Ada & C++ Programs::
1193 * Comparison between GNAT and C/C++ Compilation Models::
1194 * Comparison between GNAT and Conventional Ada Library Models::
1195 @end menu
1197 @noindent
1198 This chapter describes the compilation model used by GNAT. Although
1199 similar to that used by other languages, such as C and C++, this model
1200 is substantially different from the traditional Ada compilation models,
1201 which are based on a library. The model is initially described without
1202 reference to the library-based model. If you have not previously used an
1203 Ada compiler, you need only read the first part of this chapter. The
1204 last section describes and discusses the differences between the GNAT
1205 model and the traditional Ada compiler models. If you have used other
1206 Ada compilers, this section will help you to understand those
1207 differences, and the advantages of the GNAT model.
1209 @node Source Representation
1210 @section Source Representation
1211 @cindex Latin-1
1213 @noindent
1214 Ada source programs are represented in standard text files, using
1215 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1216 7-bit ASCII set, plus additional characters used for
1217 representing foreign languages (@pxref{Foreign Language Representation}
1218 for support of non-USA character sets). The format effector characters
1219 are represented using their standard ASCII encodings, as follows:
1221 @table @code
1222 @item VT
1223 @findex VT
1224 Vertical tab, @code{16#0B#}
1226 @item HT
1227 @findex HT
1228 Horizontal tab, @code{16#09#}
1230 @item CR
1231 @findex CR
1232 Carriage return, @code{16#0D#}
1234 @item LF
1235 @findex LF
1236 Line feed, @code{16#0A#}
1238 @item FF
1239 @findex FF
1240 Form feed, @code{16#0C#}
1241 @end table
1243 @noindent
1244 Source files are in standard text file format. In addition, GNAT will
1245 recognize a wide variety of stream formats, in which the end of
1246 physical lines is marked by any of the following sequences:
1247 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1248 in accommodating files that are imported from other operating systems.
1250 @cindex End of source file
1251 @cindex Source file, end
1252 @findex SUB
1253 The end of a source file is normally represented by the physical end of
1254 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1255 recognized as signalling the end of the source file. Again, this is
1256 provided for compatibility with other operating systems where this
1257 code is used to represent the end of file.
1259 Each file contains a single Ada compilation unit, including any pragmas
1260 associated with the unit. For example, this means you must place a
1261 package declaration (a package @dfn{spec}) and the corresponding body in
1262 separate files. An Ada @dfn{compilation} (which is a sequence of
1263 compilation units) is represented using a sequence of files. Similarly,
1264 you will place each subunit or child unit in a separate file.
1266 @node Foreign Language Representation
1267 @section Foreign Language Representation
1269 @noindent
1270 GNAT supports the standard character sets defined in Ada as well as
1271 several other non-standard character sets for use in localized versions
1272 of the compiler (@pxref{Character Set Control}).
1273 @menu
1274 * Latin-1::
1275 * Other 8-Bit Codes::
1276 * Wide_Character Encodings::
1277 * Wide_Wide_Character Encodings::
1278 @end menu
1280 @node Latin-1
1281 @subsection Latin-1
1282 @cindex Latin-1
1284 @noindent
1285 The basic character set is Latin-1. This character set is defined by ISO
1286 standard 8859, part 1. The lower half (character codes @code{16#00#}
1287 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1288 half is used to represent additional characters. These include extended letters
1289 used by European languages, such as French accents, the vowels with umlauts
1290 used in German, and the extra letter A-ring used in Swedish.
1292 @findex Ada.Characters.Latin_1
1293 For a complete list of Latin-1 codes and their encodings, see the source
1294 file of library unit @code{Ada.Characters.Latin_1} in file
1295 @file{a-chlat1.ads}.
1296 You may use any of these extended characters freely in character or
1297 string literals. In addition, the extended characters that represent
1298 letters can be used in identifiers.
1300 @node Other 8-Bit Codes
1301 @subsection Other 8-Bit Codes
1303 @noindent
1304 GNAT also supports several other 8-bit coding schemes:
1306 @table @asis
1307 @item ISO 8859-2 (Latin-2)
1308 @cindex Latin-2
1309 @cindex ISO 8859-2
1310 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1311 equivalence.
1313 @item ISO 8859-3 (Latin-3)
1314 @cindex Latin-3
1315 @cindex ISO 8859-3
1316 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1317 equivalence.
1319 @item ISO 8859-4 (Latin-4)
1320 @cindex Latin-4
1321 @cindex ISO 8859-4
1322 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1323 equivalence.
1325 @item ISO 8859-5 (Cyrillic)
1326 @cindex ISO 8859-5
1327 @cindex Cyrillic
1328 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1329 lowercase equivalence.
1331 @item ISO 8859-15 (Latin-9)
1332 @cindex ISO 8859-15
1333 @cindex Latin-9
1334 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1335 lowercase equivalence
1337 @item IBM PC (code page 437)
1338 @cindex code page 437
1339 This code page is the normal default for PCs in the U.S. It corresponds
1340 to the original IBM PC character set. This set has some, but not all, of
1341 the extended Latin-1 letters, but these letters do not have the same
1342 encoding as Latin-1. In this mode, these letters are allowed in
1343 identifiers with uppercase and lowercase equivalence.
1345 @item IBM PC (code page 850)
1346 @cindex code page 850
1347 This code page is a modification of 437 extended to include all the
1348 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1349 mode, all these letters are allowed in identifiers with uppercase and
1350 lowercase equivalence.
1352 @item Full Upper 8-bit
1353 Any character in the range 80-FF allowed in identifiers, and all are
1354 considered distinct. In other words, there are no uppercase and lowercase
1355 equivalences in this range. This is useful in conjunction with
1356 certain encoding schemes used for some foreign character sets (e.g.,
1357 the typical method of representing Chinese characters on the PC).
1359 @item No Upper-Half
1360 No upper-half characters in the range 80-FF are allowed in identifiers.
1361 This gives Ada 83 compatibility for identifier names.
1362 @end table
1364 @noindent
1365 For precise data on the encodings permitted, and the uppercase and lowercase
1366 equivalences that are recognized, see the file @file{csets.adb} in
1367 the GNAT compiler sources. You will need to obtain a full source release
1368 of GNAT to obtain this file.
1370 @node Wide_Character Encodings
1371 @subsection Wide_Character Encodings
1373 @noindent
1374 GNAT allows wide character codes to appear in character and string
1375 literals, and also optionally in identifiers, by means of the following
1376 possible encoding schemes:
1378 @table @asis
1380 @item Hex Coding
1381 In this encoding, a wide character is represented by the following five
1382 character sequence:
1384 @smallexample
1385 ESC a b c d
1386 @end smallexample
1388 @noindent
1389 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1390 characters (using uppercase letters) of the wide character code. For
1391 example, ESC A345 is used to represent the wide character with code
1392 @code{16#A345#}.
1393 This scheme is compatible with use of the full Wide_Character set.
1395 @item Upper-Half Coding
1396 @cindex Upper-Half Coding
1397 The wide character with encoding @code{16#abcd#} where the upper bit is on
1398 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1399 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1400 character, but is not required to be in the upper half. This method can
1401 be also used for shift-JIS or EUC, where the internal coding matches the
1402 external coding.
1404 @item Shift JIS Coding
1405 @cindex Shift JIS Coding
1406 A wide character is represented by a two-character sequence,
1407 @code{16#ab#} and
1408 @code{16#cd#}, with the restrictions described for upper-half encoding as
1409 described above. The internal character code is the corresponding JIS
1410 character according to the standard algorithm for Shift-JIS
1411 conversion. Only characters defined in the JIS code set table can be
1412 used with this encoding method.
1414 @item EUC Coding
1415 @cindex EUC Coding
1416 A wide character is represented by a two-character sequence
1417 @code{16#ab#} and
1418 @code{16#cd#}, with both characters being in the upper half. The internal
1419 character code is the corresponding JIS character according to the EUC
1420 encoding algorithm. Only characters defined in the JIS code set table
1421 can be used with this encoding method.
1423 @item UTF-8 Coding
1424 A wide character is represented using
1425 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1426 10646-1/Am.2. Depending on the character value, the representation
1427 is a one, two, or three byte sequence:
1428 @smallexample
1429 @iftex
1430 @leftskip=.7cm
1431 @end iftex
1432 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1433 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1434 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1436 @end smallexample
1438 @noindent
1439 where the @var{xxx} bits correspond to the left-padded bits of the
1440 16-bit character value. Note that all lower half ASCII characters
1441 are represented as ASCII bytes and all upper half characters and
1442 other wide characters are represented as sequences of upper-half
1443 (The full UTF-8 scheme allows for encoding 31-bit characters as
1444 6-byte sequences, and in the following section on wide wide
1445 characters, the use of these sequences is documented).
1447 @item Brackets Coding
1448 In this encoding, a wide character is represented by the following eight
1449 character sequence:
1451 @smallexample
1452 [ " a b c d " ]
1453 @end smallexample
1455 @noindent
1456 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1457 characters (using uppercase letters) of the wide character code. For
1458 example, [``A345''] is used to represent the wide character with code
1459 @code{16#A345#}. It is also possible (though not required) to use the
1460 Brackets coding for upper half characters. For example, the code
1461 @code{16#A3#} can be represented as @code{[``A3'']}.
1463 This scheme is compatible with use of the full Wide_Character set,
1464 and is also the method used for wide character encoding in some standard
1465 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1467 @end table
1469 @noindent
1470 Note: Some of these coding schemes do not permit the full use of the
1471 Ada character set. For example, neither Shift JIS, nor EUC allow the
1472 use of the upper half of the Latin-1 set.
1474 @node Wide_Wide_Character Encodings
1475 @subsection Wide_Wide_Character Encodings
1477 @noindent
1478 GNAT allows wide wide character codes to appear in character and string
1479 literals, and also optionally in identifiers, by means of the following
1480 possible encoding schemes:
1482 @table @asis
1484 @item UTF-8 Coding
1485 A wide character is represented using
1486 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1487 10646-1/Am.2. Depending on the character value, the representation
1488 of character codes with values greater than 16#FFFF# is a
1489 is a four, five, or six byte sequence:
1491 @smallexample
1492 @iftex
1493 @leftskip=.7cm
1494 @end iftex
1495 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1496                              10xxxxxx
1497 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1498                              10xxxxxx 10xxxxxx
1499 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1500                              10xxxxxx 10xxxxxx 10xxxxxx
1501 @end smallexample
1503 @noindent
1504 where the @var{xxx} bits correspond to the left-padded bits of the
1505 32-bit character value.
1507 @item Brackets Coding
1508 In this encoding, a wide wide character is represented by the following ten or
1509 twelve byte character sequence:
1511 @smallexample
1512 [ " a b c d e f " ]
1513 [ " a b c d e f g h " ]
1514 @end smallexample
1516 @noindent
1517 Where @code{a-h} are the six or eight hexadecimal
1518 characters (using uppercase letters) of the wide wide character code. For
1519 example, ["1F4567"] is used to represent the wide wide character with code
1520 @code{16#001F_4567#}.
1522 This scheme is compatible with use of the full Wide_Wide_Character set,
1523 and is also the method used for wide wide character encoding in some standard
1524 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1526 @end table
1528 @node File Naming Rules
1529 @section File Naming Rules
1531 @noindent
1532 The default file name is determined by the name of the unit that the
1533 file contains. The name is formed by taking the full expanded name of
1534 the unit and replacing the separating dots with hyphens and using
1535 lowercase for all letters.
1537 An exception arises if the file name generated by the above rules starts
1538 with one of the characters
1539 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1540 and the second character is a
1541 minus. In this case, the character tilde is used in place
1542 of the minus. The reason for this special rule is to avoid clashes with
1543 the standard names for child units of the packages System, Ada,
1544 Interfaces, and GNAT, which use the prefixes
1545 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1546 respectively.
1548 The file extension is @file{.ads} for a spec and
1549 @file{.adb} for a body. The following list shows some
1550 examples of these rules.
1552 @table @file
1553 @item main.ads
1554 Main (spec)
1555 @item main.adb
1556 Main (body)
1557 @item arith_functions.ads
1558 Arith_Functions (package spec)
1559 @item arith_functions.adb
1560 Arith_Functions (package body)
1561 @item func-spec.ads
1562 Func.Spec (child package spec)
1563 @item func-spec.adb
1564 Func.Spec (child package body)
1565 @item main-sub.adb
1566 Sub (subunit of Main)
1567 @item a~bad.adb
1568 A.Bad (child package body)
1569 @end table
1571 @noindent
1572 Following these rules can result in excessively long
1573 file names if corresponding
1574 unit names are long (for example, if child units or subunits are
1575 heavily nested). An option is available to shorten such long file names
1576 (called file name ``krunching''). This may be particularly useful when
1577 programs being developed with GNAT are to be used on operating systems
1578 with limited file name lengths. @xref{Using gnatkr}.
1580 Of course, no file shortening algorithm can guarantee uniqueness over
1581 all possible unit names; if file name krunching is used, it is your
1582 responsibility to ensure no name clashes occur. Alternatively you
1583 can specify the exact file names that you want used, as described
1584 in the next section. Finally, if your Ada programs are migrating from a
1585 compiler with a different naming convention, you can use the gnatchop
1586 utility to produce source files that follow the GNAT naming conventions.
1587 (For details @pxref{Renaming Files with gnatchop}.)
1589 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1590 systems, case is not significant. So for example on @code{Windows XP}
1591 if the canonical name is @code{main-sub.adb}, you can use the file name
1592 @code{Main-Sub.adb} instead. However, case is significant for other
1593 operating systems, so for example, if you want to use other than
1594 canonically cased file names on a Unix system, you need to follow
1595 the procedures described in the next section.
1597 @node Using Other File Names
1598 @section Using Other File Names
1599 @cindex File names
1601 @noindent
1602 In the previous section, we have described the default rules used by
1603 GNAT to determine the file name in which a given unit resides. It is
1604 often convenient to follow these default rules, and if you follow them,
1605 the compiler knows without being explicitly told where to find all
1606 the files it needs.
1608 However, in some cases, particularly when a program is imported from
1609 another Ada compiler environment, it may be more convenient for the
1610 programmer to specify which file names contain which units. GNAT allows
1611 arbitrary file names to be used by means of the Source_File_Name pragma.
1612 The form of this pragma is as shown in the following examples:
1613 @cindex Source_File_Name pragma
1615 @smallexample @c ada
1616 @cartouche
1617 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1618   Spec_File_Name => "myutilst_a.ada");
1619 @b{pragma} Source_File_name (My_Utilities.Stacks,
1620   Body_File_Name => "myutilst.ada");
1621 @end cartouche
1622 @end smallexample
1624 @noindent
1625 As shown in this example, the first argument for the pragma is the unit
1626 name (in this example a child unit). The second argument has the form
1627 of a named association. The identifier
1628 indicates whether the file name is for a spec or a body;
1629 the file name itself is given by a string literal.
1631 The source file name pragma is a configuration pragma, which means that
1632 normally it will be placed in the @file{gnat.adc}
1633 file used to hold configuration
1634 pragmas that apply to a complete compilation environment.
1635 For more details on how the @file{gnat.adc} file is created and used
1636 see @ref{Handling of Configuration Pragmas}.
1637 @cindex @file{gnat.adc}
1639 GNAT allows completely arbitrary file names to be specified using the
1640 source file name pragma. However, if the file name specified has an
1641 extension other than @file{.ads} or @file{.adb} it is necessary to use
1642 a special syntax when compiling the file. The name in this case must be
1643 preceded by the special sequence @option{-x} followed by a space and the name
1644 of the language, here @code{ada}, as in:
1646 @smallexample
1647 $ gcc -c -x ada peculiar_file_name.sim
1648 @end smallexample
1650 @noindent
1651 @command{gnatmake} handles non-standard file names in the usual manner (the
1652 non-standard file name for the main program is simply used as the
1653 argument to gnatmake). Note that if the extension is also non-standard,
1654 then it must be included in the @command{gnatmake} command, it may not
1655 be omitted.
1657 @node Alternative File Naming Schemes
1658 @section Alternative File Naming Schemes
1659 @cindex File naming schemes, alternative
1660 @cindex File names
1662 In the previous section, we described the use of the @code{Source_File_Name}
1663 pragma to allow arbitrary names to be assigned to individual source files.
1664 However, this approach requires one pragma for each file, and especially in
1665 large systems can result in very long @file{gnat.adc} files, and also create
1666 a maintenance problem.
1668 GNAT also provides a facility for specifying systematic file naming schemes
1669 other than the standard default naming scheme previously described. An
1670 alternative scheme for naming is specified by the use of
1671 @code{Source_File_Name} pragmas having the following format:
1672 @cindex Source_File_Name pragma
1674 @smallexample @c ada
1675 @b{pragma} Source_File_Name (
1676    Spec_File_Name  => FILE_NAME_PATTERN
1677  @r{[},Casing          => CASING_SPEC@r{]}
1678  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1680 @b{pragma} Source_File_Name (
1681    Body_File_Name  => FILE_NAME_PATTERN
1682  @r{[},Casing          => CASING_SPEC@r{]}
1683  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1685 @b{pragma} Source_File_Name (
1686    Subunit_File_Name  => FILE_NAME_PATTERN
1687  @r{[},Casing             => CASING_SPEC@r{]}
1688  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
1690 FILE_NAME_PATTERN ::= STRING_LITERAL
1691 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1692 @end smallexample
1694 @noindent
1695 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1696 It contains a single asterisk character, and the unit name is substituted
1697 systematically for this asterisk. The optional parameter
1698 @code{Casing} indicates
1699 whether the unit name is to be all upper-case letters, all lower-case letters,
1700 or mixed-case. If no
1701 @code{Casing} parameter is used, then the default is all
1702 lower-case.
1704 The optional @code{Dot_Replacement} string is used to replace any periods
1705 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1706 argument is used then separating dots appear unchanged in the resulting
1707 file name.
1708 Although the above syntax indicates that the
1709 @code{Casing} argument must appear
1710 before the @code{Dot_Replacement} argument, but it
1711 is also permissible to write these arguments in the opposite order.
1713 As indicated, it is possible to specify different naming schemes for
1714 bodies, specs, and subunits. Quite often the rule for subunits is the
1715 same as the rule for bodies, in which case, there is no need to give
1716 a separate @code{Subunit_File_Name} rule, and in this case the
1717 @code{Body_File_name} rule is used for subunits as well.
1719 The separate rule for subunits can also be used to implement the rather
1720 unusual case of a compilation environment (e.g.@: a single directory) which
1721 contains a subunit and a child unit with the same unit name. Although
1722 both units cannot appear in the same partition, the Ada Reference Manual
1723 allows (but does not require) the possibility of the two units coexisting
1724 in the same environment.
1726 The file name translation works in the following steps:
1728 @itemize @bullet
1730 @item
1731 If there is a specific @code{Source_File_Name} pragma for the given unit,
1732 then this is always used, and any general pattern rules are ignored.
1734 @item
1735 If there is a pattern type @code{Source_File_Name} pragma that applies to
1736 the unit, then the resulting file name will be used if the file exists. If
1737 more than one pattern matches, the latest one will be tried first, and the
1738 first attempt resulting in a reference to a file that exists will be used.
1740 @item
1741 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1742 for which the corresponding file exists, then the standard GNAT default
1743 naming rules are used.
1745 @end itemize
1747 @noindent
1748 As an example of the use of this mechanism, consider a commonly used scheme
1749 in which file names are all lower case, with separating periods copied
1750 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1751 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1752 two pragmas appear:
1754 @smallexample @c ada
1755 @b{pragma} Source_File_Name
1756   (Spec_File_Name => "*.1.ada");
1757 @b{pragma} Source_File_Name
1758   (Body_File_Name => "*.2.ada");
1759 @end smallexample
1761 @noindent
1762 The default GNAT scheme is actually implemented by providing the following
1763 default pragmas internally:
1765 @smallexample @c ada
1766 @b{pragma} Source_File_Name
1767   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1768 @b{pragma} Source_File_Name
1769   (Body_File_Name => "*.adb", Dot_Replacement => "-");
1770 @end smallexample
1772 @noindent
1773 Our final example implements a scheme typically used with one of the
1774 Ada 83 compilers, where the separator character for subunits was ``__''
1775 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1776 by adding @file{.ADA}, and subunits by
1777 adding @file{.SEP}. All file names were
1778 upper case. Child units were not present of course since this was an
1779 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1780 the same double underscore separator for child units.
1782 @smallexample @c ada
1783 @b{pragma} Source_File_Name
1784   (Spec_File_Name => "*_.ADA",
1785    Dot_Replacement => "__",
1786    Casing = Uppercase);
1787 @b{pragma} Source_File_Name
1788   (Body_File_Name => "*.ADA",
1789    Dot_Replacement => "__",
1790    Casing = Uppercase);
1791 @b{pragma} Source_File_Name
1792   (Subunit_File_Name => "*.SEP",
1793    Dot_Replacement => "__",
1794    Casing = Uppercase);
1795 @end smallexample
1797 @node Generating Object Files
1798 @section Generating Object Files
1800 @noindent
1801 An Ada program consists of a set of source files, and the first step in
1802 compiling the program is to generate the corresponding object files.
1803 These are generated by compiling a subset of these source files.
1804 The files you need to compile are the following:
1806 @itemize @bullet
1807 @item
1808 If a package spec has no body, compile the package spec to produce the
1809 object file for the package.
1811 @item
1812 If a package has both a spec and a body, compile the body to produce the
1813 object file for the package. The source file for the package spec need
1814 not be compiled in this case because there is only one object file, which
1815 contains the code for both the spec and body of the package.
1817 @item
1818 For a subprogram, compile the subprogram body to produce the object file
1819 for the subprogram. The spec, if one is present, is as usual in a
1820 separate file, and need not be compiled.
1822 @item
1823 @cindex Subunits
1824 In the case of subunits, only compile the parent unit. A single object
1825 file is generated for the entire subunit tree, which includes all the
1826 subunits.
1828 @item
1829 Compile child units independently of their parent units
1830 (though, of course, the spec of all the ancestor unit must be present in order
1831 to compile a child unit).
1833 @item
1834 @cindex Generics
1835 Compile generic units in the same manner as any other units. The object
1836 files in this case are small dummy files that contain at most the
1837 flag used for elaboration checking. This is because GNAT always handles generic
1838 instantiation by means of macro expansion. However, it is still necessary to
1839 compile generic units, for dependency checking and elaboration purposes.
1840 @end itemize
1842 @noindent
1843 The preceding rules describe the set of files that must be compiled to
1844 generate the object files for a program. Each object file has the same
1845 name as the corresponding source file, except that the extension is
1846 @file{.o} as usual.
1848 You may wish to compile other files for the purpose of checking their
1849 syntactic and semantic correctness. For example, in the case where a
1850 package has a separate spec and body, you would not normally compile the
1851 spec. However, it is convenient in practice to compile the spec to make
1852 sure it is error-free before compiling clients of this spec, because such
1853 compilations will fail if there is an error in the spec.
1855 GNAT provides an option for compiling such files purely for the
1856 purposes of checking correctness; such compilations are not required as
1857 part of the process of building a program. To compile a file in this
1858 checking mode, use the @option{-gnatc} switch.
1860 @node Source Dependencies
1861 @section Source Dependencies
1863 @noindent
1864 A given object file clearly depends on the source file which is compiled
1865 to produce it. Here we are using @dfn{depends} in the sense of a typical
1866 @code{make} utility; in other words, an object file depends on a source
1867 file if changes to the source file require the object file to be
1868 recompiled.
1869 In addition to this basic dependency, a given object may depend on
1870 additional source files as follows:
1872 @itemize @bullet
1873 @item
1874 If a file being compiled @code{with}'s a unit @var{X}, the object file
1875 depends on the file containing the spec of unit @var{X}. This includes
1876 files that are @code{with}'ed implicitly either because they are parents
1877 of @code{with}'ed child units or they are run-time units required by the
1878 language constructs used in a particular unit.
1880 @item
1881 If a file being compiled instantiates a library level generic unit, the
1882 object file depends on both the spec and body files for this generic
1883 unit.
1885 @item
1886 If a file being compiled instantiates a generic unit defined within a
1887 package, the object file depends on the body file for the package as
1888 well as the spec file.
1890 @item
1891 @findex Inline
1892 @cindex @option{-gnatn} switch
1893 If a file being compiled contains a call to a subprogram for which
1894 pragma @code{Inline} applies and inlining is activated with the
1895 @option{-gnatn} switch, the object file depends on the file containing the
1896 body of this subprogram as well as on the file containing the spec. Note
1897 that for inlining to actually occur as a result of the use of this switch,
1898 it is necessary to compile in optimizing mode.
1900 @cindex @option{-gnatN} switch
1901 The use of @option{-gnatN} activates  inlining optimization
1902 that is performed by the front end of the compiler. This inlining does
1903 not require that the code generation be optimized. Like @option{-gnatn},
1904 the use of this switch generates additional dependencies.
1906 When using a gcc-based back end (in practice this means using any version
1907 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1908 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1909 Historically front end inlining was more extensive than the gcc back end
1910 inlining, but that is no longer the case.
1912 @item
1913 If an object file @file{O} depends on the proper body of a subunit through
1914 inlining or instantiation, it depends on the parent unit of the subunit.
1915 This means that any modification of the parent unit or one of its subunits
1916 affects the compilation of @file{O}.
1918 @item
1919 The object file for a parent unit depends on all its subunit body files.
1921 @item
1922 The previous two rules meant that for purposes of computing dependencies and
1923 recompilation, a body and all its subunits are treated as an indivisible whole.
1925 @noindent
1926 These rules are applied transitively: if unit @code{A} @code{with}'s
1927 unit @code{B}, whose elaboration calls an inlined procedure in package
1928 @code{C}, the object file for unit @code{A} will depend on the body of
1929 @code{C}, in file @file{c.adb}.
1931 The set of dependent files described by these rules includes all the
1932 files on which the unit is semantically dependent, as dictated by the
1933 Ada language standard. However, it is a superset of what the
1934 standard describes, because it includes generic, inline, and subunit
1935 dependencies.
1937 An object file must be recreated by recompiling the corresponding source
1938 file if any of the source files on which it depends are modified. For
1939 example, if the @code{make} utility is used to control compilation,
1940 the rule for an Ada object file must mention all the source files on
1941 which the object file depends, according to the above definition.
1942 The determination of the necessary
1943 recompilations is done automatically when one uses @command{gnatmake}.
1944 @end itemize
1946 @node The Ada Library Information Files
1947 @section The Ada Library Information Files
1948 @cindex Ada Library Information files
1949 @cindex @file{ALI} files
1951 @noindent
1952 Each compilation actually generates two output files. The first of these
1953 is the normal object file that has a @file{.o} extension. The second is a
1954 text file containing full dependency information. It has the same
1955 name as the source file, but an @file{.ali} extension.
1956 This file is known as the Ada Library Information (@file{ALI}) file.
1957 The following information is contained in the @file{ALI} file.
1959 @itemize @bullet
1960 @item
1961 Version information (indicates which version of GNAT was used to compile
1962 the unit(s) in question)
1964 @item
1965 Main program information (including priority and time slice settings,
1966 as well as the wide character encoding used during compilation).
1968 @item
1969 List of arguments used in the @command{gcc} command for the compilation
1971 @item
1972 Attributes of the unit, including configuration pragmas used, an indication
1973 of whether the compilation was successful, exception model used etc.
1975 @item
1976 A list of relevant restrictions applying to the unit (used for consistency)
1977 checking.
1979 @item
1980 Categorization information (e.g.@: use of pragma @code{Pure}).
1982 @item
1983 Information on all @code{with}'ed units, including presence of
1984 @code{Elaborate} or @code{Elaborate_All} pragmas.
1986 @item
1987 Information from any @code{Linker_Options} pragmas used in the unit
1989 @item
1990 Information on the use of @code{Body_Version} or @code{Version}
1991 attributes in the unit.
1993 @item
1994 Dependency information. This is a list of files, together with
1995 time stamp and checksum information. These are files on which
1996 the unit depends in the sense that recompilation is required
1997 if any of these units are modified.
1999 @item
2000 Cross-reference data. Contains information on all entities referenced
2001 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2002 provide cross-reference information.
2004 @end itemize
2006 @noindent
2007 For a full detailed description of the format of the @file{ALI} file,
2008 see the source of the body of unit @code{Lib.Writ}, contained in file
2009 @file{lib-writ.adb} in the GNAT compiler sources.
2011 @node Binding an Ada Program
2012 @section Binding an Ada Program
2014 @noindent
2015 When using languages such as C and C++, once the source files have been
2016 compiled the only remaining step in building an executable program
2017 is linking the object modules together. This means that it is possible to
2018 link an inconsistent version of a program, in which two units have
2019 included different versions of the same header.
2021 The rules of Ada do not permit such an inconsistent program to be built.
2022 For example, if two clients have different versions of the same package,
2023 it is illegal to build a program containing these two clients.
2024 These rules are enforced by the GNAT binder, which also determines an
2025 elaboration order consistent with the Ada rules.
2027 The GNAT binder is run after all the object files for a program have
2028 been created. It is given the name of the main program unit, and from
2029 this it determines the set of units required by the program, by reading the
2030 corresponding ALI files. It generates error messages if the program is
2031 inconsistent or if no valid order of elaboration exists.
2033 If no errors are detected, the binder produces a main program, in Ada by
2034 default, that contains calls to the elaboration procedures of those
2035 compilation unit that require them, followed by
2036 a call to the main program. This Ada program is compiled to generate the
2037 object file for the main program. The name of
2038 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2039 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2040 main program unit.
2042 Finally, the linker is used to build the resulting executable program,
2043 using the object from the main program from the bind step as well as the
2044 object files for the Ada units of the program.
2046 @node Mixed Language Programming
2047 @section Mixed Language Programming
2048 @cindex Mixed Language Programming
2050 @noindent
2051 This section describes how to develop a mixed-language program,
2052 specifically one that comprises units in both Ada and C.
2054 @menu
2055 * Interfacing to C::
2056 * Calling Conventions::
2057 @end menu
2059 @node Interfacing to C
2060 @subsection Interfacing to C
2061 @noindent
2062 Interfacing Ada with a foreign language such as C involves using
2063 compiler directives to import and/or export entity definitions in each
2064 language---using @code{extern} statements in C, for instance, and the
2065 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2066 A full treatment of these topics is provided in Appendix B, section 1
2067 of the Ada Reference Manual.
2069 There are two ways to build a program using GNAT that contains some Ada
2070 sources and some foreign language sources, depending on whether or not
2071 the main subprogram is written in Ada.  Here is a source example with
2072 the main subprogram in Ada:
2074 @smallexample
2075 /* file1.c */
2076 #include <stdio.h>
2078 void print_num (int num)
2080   printf ("num is %d.\n", num);
2081   return;
2084 /* file2.c */
2086 /* num_from_Ada is declared in my_main.adb */
2087 extern int num_from_Ada;
2089 int get_num (void)
2091   return num_from_Ada;
2093 @end smallexample
2095 @smallexample @c ada
2096 --  my_main.adb
2097 procedure My_Main is
2099    --  Declare then export an Integer entity called num_from_Ada
2100    My_Num : Integer := 10;
2101    pragma Export (C, My_Num, "num_from_Ada");
2103    --  Declare an Ada function spec for Get_Num, then use
2104    --  C function get_num for the implementation.
2105    function Get_Num return Integer;
2106    pragma Import (C, Get_Num, "get_num");
2108    --  Declare an Ada procedure spec for Print_Num, then use
2109    --  C function print_num for the implementation.
2110    procedure Print_Num (Num : Integer);
2111    pragma Import (C, Print_Num, "print_num";
2113 begin
2114    Print_Num (Get_Num);
2115 end My_Main;
2116 @end smallexample
2118 @enumerate
2119 @item
2120 To build this example, first compile the foreign language files to
2121 generate object files:
2122 @smallexample
2123 gcc -c file1.c
2124 gcc -c file2.c
2125 @end smallexample
2127 @item
2128 Then, compile the Ada units to produce a set of object files and ALI
2129 files:
2130 @smallexample
2131 gnatmake -c my_main.adb
2132 @end smallexample
2134 @item
2135 Run the Ada binder on the Ada main program:
2136 @smallexample
2137 gnatbind my_main.ali
2138 @end smallexample
2140 @item
2141 Link the Ada main program, the Ada objects and the other language
2142 objects:
2143 @smallexample
2144 gnatlink my_main.ali file1.o file2.o
2145 @end smallexample
2146 @end enumerate
2148 The last three steps can be grouped in a single command:
2149 @smallexample
2150 gnatmake my_main.adb -largs file1.o file2.o
2151 @end smallexample
2153 @cindex Binder output file
2154 @noindent
2155 If the main program is in a language other than Ada, then you may have
2156 more than one entry point into the Ada subsystem. You must use a special
2157 binder option to generate callable routines that initialize and
2158 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2159 Calls to the initialization and finalization routines must be inserted
2160 in the main program, or some other appropriate point in the code. The
2161 call to initialize the Ada units must occur before the first Ada
2162 subprogram is called, and the call to finalize the Ada units must occur
2163 after the last Ada subprogram returns. The binder will place the
2164 initialization and finalization subprograms into the
2165 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2166 sources.  To illustrate, we have the following example:
2168 @smallexample
2169 /* main.c */
2170 extern void adainit (void);
2171 extern void adafinal (void);
2172 extern int add (int, int);
2173 extern int sub (int, int);
2175 int main (int argc, char *argv[])
2177   int a = 21, b = 7;
2179   adainit();
2181   /* Should print "21 + 7 = 28" */
2182   printf ("%d + %d = %d\n", a, b, add (a, b));
2183   /* Should print "21 - 7 = 14" */
2184   printf ("%d - %d = %d\n", a, b, sub (a, b));
2186   adafinal();
2188 @end smallexample
2190 @smallexample @c ada
2191 --  unit1.ads
2192 package Unit1 is
2193    function Add (A, B : Integer) return Integer;
2194    pragma Export (C, Add, "add");
2195 end Unit1;
2197 --  unit1.adb
2198 package body Unit1 is
2199    function Add (A, B : Integer) return Integer is
2200    begin
2201       return A + B;
2202    end Add;
2203 end Unit1;
2205 --  unit2.ads
2206 package Unit2 is
2207    function Sub (A, B : Integer) return Integer;
2208    pragma Export (C, Sub, "sub");
2209 end Unit2;
2211 --  unit2.adb
2212 package body Unit2 is
2213    function Sub (A, B : Integer) return Integer is
2214    begin
2215       return A - B;
2216    end Sub;
2217 end Unit2;
2218 @end smallexample
2220 @enumerate
2221 @item
2222 The build procedure for this application is similar to the last
2223 example's.  First, compile the foreign language files to generate object
2224 files:
2225 @smallexample
2226 gcc -c main.c
2227 @end smallexample
2229 @item
2230 Next, compile the Ada units to produce a set of object files and ALI
2231 files:
2232 @smallexample
2233 gnatmake -c unit1.adb
2234 gnatmake -c unit2.adb
2235 @end smallexample
2237 @item
2238 Run the Ada binder on every generated ALI file.  Make sure to use the
2239 @option{-n} option to specify a foreign main program:
2240 @smallexample
2241 gnatbind -n unit1.ali unit2.ali
2242 @end smallexample
2244 @item
2245 Link the Ada main program, the Ada objects and the foreign language
2246 objects. You need only list the last ALI file here:
2247 @smallexample
2248 gnatlink unit2.ali main.o -o exec_file
2249 @end smallexample
2251 This procedure yields a binary executable called @file{exec_file}.
2252 @end enumerate
2254 @noindent
2255 Depending on the circumstances (for example when your non-Ada main object
2256 does not provide symbol @code{main}), you may also need to instruct the
2257 GNAT linker not to include the standard startup objects by passing the
2258 @option{-nostartfiles} switch to @command{gnatlink}.
2260 @node Calling Conventions
2261 @subsection Calling Conventions
2262 @cindex Foreign Languages
2263 @cindex Calling Conventions
2264 GNAT follows standard calling sequence conventions and will thus interface
2265 to any other language that also follows these conventions. The following
2266 Convention identifiers are recognized by GNAT:
2268 @table @code
2269 @cindex Interfacing to Ada
2270 @cindex Other Ada compilers
2271 @cindex Convention Ada
2272 @item Ada
2273 This indicates that the standard Ada calling sequence will be
2274 used and all Ada data items may be passed without any limitations in the
2275 case where GNAT is used to generate both the caller and callee. It is also
2276 possible to mix GNAT generated code and code generated by another Ada
2277 compiler. In this case, the data types should be restricted to simple
2278 cases, including primitive types. Whether complex data types can be passed
2279 depends on the situation. Probably it is safe to pass simple arrays, such
2280 as arrays of integers or floats. Records may or may not work, depending
2281 on whether both compilers lay them out identically. Complex structures
2282 involving variant records, access parameters, tasks, or protected types,
2283 are unlikely to be able to be passed.
2285 Note that in the case of GNAT running
2286 on a platform that supports HP Ada 83, a higher degree of compatibility
2287 can be guaranteed, and in particular records are laid out in an identical
2288 manner in the two compilers. Note also that if output from two different
2289 compilers is mixed, the program is responsible for dealing with elaboration
2290 issues. Probably the safest approach is to write the main program in the
2291 version of Ada other than GNAT, so that it takes care of its own elaboration
2292 requirements, and then call the GNAT-generated adainit procedure to ensure
2293 elaboration of the GNAT components. Consult the documentation of the other
2294 Ada compiler for further details on elaboration.
2296 However, it is not possible to mix the tasking run time of GNAT and
2297 HP Ada 83, All the tasking operations must either be entirely within
2298 GNAT compiled sections of the program, or entirely within HP Ada 83
2299 compiled sections of the program.
2301 @cindex Interfacing to Assembly
2302 @cindex Convention Assembler
2303 @item Assembler
2304 Specifies assembler as the convention. In practice this has the
2305 same effect as convention Ada (but is not equivalent in the sense of being
2306 considered the same convention).
2308 @cindex Convention Asm
2309 @findex Asm
2310 @item Asm
2311 Equivalent to Assembler.
2313 @cindex Interfacing to COBOL
2314 @cindex Convention COBOL
2315 @findex COBOL
2316 @item COBOL
2317 Data will be passed according to the conventions described
2318 in section B.4 of the Ada Reference Manual.
2320 @findex C
2321 @cindex Interfacing to C
2322 @cindex Convention C
2323 @item C
2324 Data will be passed according to the conventions described
2325 in section B.3 of the Ada Reference Manual.
2327 A note on interfacing to a C ``varargs'' function:
2328 @findex C varargs function
2329 @cindex Interfacing to C varargs function
2330 @cindex varargs function interfaces
2332 @itemize @bullet
2333 @item
2334 In C, @code{varargs} allows a function to take a variable number of
2335 arguments. There is no direct equivalent in this to Ada. One
2336 approach that can be used is to create a C wrapper for each
2337 different profile and then interface to this C wrapper. For
2338 example, to print an @code{int} value using @code{printf},
2339 create a C function @code{printfi} that takes two arguments, a
2340 pointer to a string and an int, and calls @code{printf}.
2341 Then in the Ada program, use pragma @code{Import} to
2342 interface to @code{printfi}.
2344 @item
2345 It may work on some platforms to directly interface to
2346 a @code{varargs} function by providing a specific Ada profile
2347 for a particular call. However, this does not work on
2348 all platforms, since there is no guarantee that the
2349 calling sequence for a two argument normal C function
2350 is the same as for calling a @code{varargs} C function with
2351 the same two arguments.
2352 @end itemize
2354 @cindex Convention Default
2355 @findex Default
2356 @item Default
2357 Equivalent to C.
2359 @cindex Convention External
2360 @findex External
2361 @item External
2362 Equivalent to C.
2364 @findex C++
2365 @cindex Interfacing to C++
2366 @cindex Convention C++
2367 @item C_Plus_Plus (or CPP)
2368 This stands for C++. For most purposes this is identical to C.
2369 See the separate description of the specialized GNAT pragmas relating to
2370 C++ interfacing for further details.
2372 @findex Fortran
2373 @cindex Interfacing to Fortran
2374 @cindex Convention Fortran
2375 @item Fortran
2376 Data will be passed according to the conventions described
2377 in section B.5 of the Ada Reference Manual.
2379 @item Intrinsic
2380 This applies to an intrinsic operation, as defined in the Ada
2381 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2382 this means that the body of the subprogram is provided by the compiler itself,
2383 usually by means of an efficient code sequence, and that the user does not
2384 supply an explicit body for it. In an application program, the pragma may
2385 be applied to the following sets of names:
2387 @itemize @bullet
2388 @item
2389 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2390 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2391 two formal parameters. The
2392 first one must be a signed integer type or a modular type with a binary
2393 modulus, and the second parameter must be of type Natural.
2394 The return type must be the same as the type of the first argument. The size
2395 of this type can only be 8, 16, 32, or 64.
2397 @item
2398 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2399 The corresponding operator declaration must have parameters and result type
2400 that have the same root numeric type (for example, all three are long_float
2401 types). This simplifies the definition of operations that use type checking
2402 to perform dimensional checks:
2404 @smallexample @c ada
2405 @b{type} Distance @b{is} @b{new} Long_Float;
2406 @b{type} Time     @b{is} @b{new} Long_Float;
2407 @b{type} Velocity @b{is} @b{new} Long_Float;
2408 @b{function} "/" (D : Distance; T : Time)
2409   @b{return} Velocity;
2410 @b{pragma} Import (Intrinsic, "/");
2411 @end smallexample
2413 @noindent
2414 This common idiom is often programmed with a generic definition and an
2415 explicit body. The pragma makes it simpler to introduce such declarations.
2416 It incurs no overhead in compilation time or code size, because it is
2417 implemented as a single machine instruction.
2419 @item
2420 General subprogram entities, to bind an Ada subprogram declaration to
2421 a compiler builtin by name with back-ends where such interfaces are
2422 available. A typical example is the set of ``__builtin'' functions
2423 exposed by the GCC back-end, as in the following example:
2425 @smallexample @c ada
2426    @b{function} builtin_sqrt (F : Float) @b{return} Float;
2427    @b{pragma} Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2428 @end smallexample
2430 Most of the GCC builtins are accessible this way, and as for other
2431 import conventions (e.g. C), it is the user's responsibility to ensure
2432 that the Ada subprogram profile matches the underlying builtin
2433 expectations.
2434 @end itemize
2436 @noindent
2438 @findex Stdcall
2439 @cindex Convention Stdcall
2440 @item Stdcall
2441 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2442 and specifies that the @code{Stdcall} calling sequence will be used,
2443 as defined by the NT API. Nevertheless, to ease building
2444 cross-platform bindings this convention will be handled as a @code{C} calling
2445 convention on non-Windows platforms.
2447 @findex DLL
2448 @cindex Convention DLL
2449 @item DLL
2450 This is equivalent to @code{Stdcall}.
2452 @findex Win32
2453 @cindex Convention Win32
2454 @item Win32
2455 This is equivalent to @code{Stdcall}.
2457 @findex Stubbed
2458 @cindex Convention Stubbed
2459 @item Stubbed
2460 This is a special convention that indicates that the compiler
2461 should provide a stub body that raises @code{Program_Error}.
2462 @end table
2464 @noindent
2465 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2466 that can be used to parameterize conventions and allow additional synonyms
2467 to be specified. For example if you have legacy code in which the convention
2468 identifier Fortran77 was used for Fortran, you can use the configuration
2469 pragma:
2471 @smallexample @c ada
2472 @b{pragma} Convention_Identifier (Fortran77, Fortran);
2473 @end smallexample
2475 @noindent
2476 And from now on the identifier Fortran77 may be used as a convention
2477 identifier (for example in an @code{Import} pragma) with the same
2478 meaning as Fortran.
2480 @node Building Mixed Ada & C++ Programs
2481 @section Building Mixed Ada and C++ Programs
2483 @noindent
2484 A programmer inexperienced with mixed-language development may find that
2485 building an application containing both Ada and C++ code can be a
2486 challenge.  This section gives a few
2487 hints that should make this task easier. The first section addresses
2488 the differences between interfacing with C and interfacing with C++.
2489 The second section
2490 looks into the delicate problem of linking the complete application from
2491 its Ada and C++ parts. The last section gives some hints on how the GNAT
2492 run-time library can be adapted in order to allow inter-language dispatching
2493 with a new C++ compiler.
2495 @menu
2496 * Interfacing to C++::
2497 * Linking a Mixed C++ & Ada Program::
2498 * A Simple Example::
2499 * Interfacing with C++ constructors::
2500 * Interfacing with C++ at the Class Level::
2501 @end menu
2503 @node Interfacing to C++
2504 @subsection Interfacing to C++
2506 @noindent
2507 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2508 generating code that is compatible with the G++ Application Binary
2509 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2511 @noindent
2512 Interfacing can be done at 3 levels: simple data, subprograms, and
2513 classes. In the first two cases, GNAT offers a specific @code{Convention
2514 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2515 Usually, C++ mangles the names of subprograms. To generate proper mangled
2516 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2517 This problem can also be addressed manually in two ways:
2519 @itemize @bullet
2520 @item
2521 by modifying the C++ code in order to force a C convention using
2522 the @code{extern "C"} syntax.
2524 @item
2525 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2526 Link_Name argument of the pragma import.
2527 @end itemize
2529 @noindent
2530 Interfacing at the class level can be achieved by using the GNAT specific
2531 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
2532 gnat_rm, GNAT Reference Manual}, for additional information.
2534 @node Linking a Mixed C++ & Ada Program
2535 @subsection Linking a Mixed C++ & Ada Program
2537 @noindent
2538 Usually the linker of the C++ development system must be used to link
2539 mixed applications because most C++ systems will resolve elaboration
2540 issues (such as calling constructors on global class instances)
2541 transparently during the link phase. GNAT has been adapted to ease the
2542 use of a foreign linker for the last phase. Three cases can be
2543 considered:
2544 @enumerate
2546 @item
2547 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2548 The C++ linker can simply be called by using the C++ specific driver
2549 called @code{g++}.
2551 Note that if the C++ code uses inline functions, you will need to
2552 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2553 order to provide an existing function implementation that the Ada code can
2554 link with.
2556 @smallexample
2557 $ g++ -c -fkeep-inline-functions file1.C
2558 $ g++ -c -fkeep-inline-functions file2.C
2559 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2560 @end smallexample
2562 @item
2563 Using GNAT and G++ from two different GCC installations: If both
2564 compilers are on the @env{PATH}, the previous method may be used. It is
2565 important to note that environment variables such as
2566 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2567 @env{GCC_ROOT} will affect both compilers
2568 at the same time and may make one of the two compilers operate
2569 improperly if set during invocation of the wrong compiler.  It is also
2570 very important that the linker uses the proper @file{libgcc.a} GCC
2571 library -- that is, the one from the C++ compiler installation. The
2572 implicit link command as suggested in the @command{gnatmake} command
2573 from the former example can be replaced by an explicit link command with
2574 the full-verbosity option in order to verify which library is used:
2575 @smallexample
2576 $ gnatbind ada_unit
2577 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2578 @end smallexample
2579 If there is a problem due to interfering environment variables, it can
2580 be worked around by using an intermediate script. The following example
2581 shows the proper script to use when GNAT has not been installed at its
2582 default location and g++ has been installed at its default location:
2584 @smallexample
2585 $ cat ./my_script
2586 #!/bin/sh
2587 unset BINUTILS_ROOT
2588 unset GCC_ROOT
2589 c++ $*
2590 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2591 @end smallexample
2593 @item
2594 Using a non-GNU C++ compiler: The commands previously described can be
2595 used to insure that the C++ linker is used. Nonetheless, you need to add
2596 a few more parameters to the link command line, depending on the exception
2597 mechanism used.
2599 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2600 to the libgcc libraries are required:
2602 @smallexample
2603 $ cat ./my_script
2604 #!/bin/sh
2605 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2606 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2607 @end smallexample
2609 Where CC is the name of the non-GNU C++ compiler.
2611 If the @code{zero cost} exception mechanism is used, and the platform
2612 supports automatic registration of exception tables (e.g.@: Solaris),
2613 paths to more objects are required:
2615 @smallexample
2616 $ cat ./my_script
2617 #!/bin/sh
2618 CC `gcc -print-file-name=crtbegin.o` $* \
2619 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2620 `gcc -print-file-name=crtend.o`
2621 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2622 @end smallexample
2624 If the @code{zero cost} exception mechanism is used, and the platform
2625 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2626 or AIX), the simple approach described above will not work and
2627 a pre-linking phase using GNAT will be necessary.
2629 @end enumerate
2631 Another alternative is to use the @command{gprbuild} multi-language builder
2632 which has a large knowledge base and knows how to link Ada and C++ code
2633 together automatically in most cases.
2635 @node A Simple Example
2636 @subsection  A Simple Example
2637 @noindent
2638 The following example, provided as part of the GNAT examples, shows how
2639 to achieve procedural interfacing between Ada and C++ in both
2640 directions. The C++ class A has two methods. The first method is exported
2641 to Ada by the means of an extern C wrapper function. The second method
2642 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2643 a limited record with a layout comparable to the C++ class. The Ada
2644 subprogram, in turn, calls the C++ method. So, starting from the C++
2645 main program, the process passes back and forth between the two
2646 languages.
2648 @noindent
2649 Here are the compilation commands:
2650 @smallexample
2651 $ gnatmake -c simple_cpp_interface
2652 $ g++ -c cpp_main.C
2653 $ g++ -c ex7.C
2654 $ gnatbind -n simple_cpp_interface
2655 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2656       -lstdc++ ex7.o cpp_main.o
2657 @end smallexample
2659 @noindent
2660 Here are the corresponding sources:
2661 @smallexample
2663 //cpp_main.C
2665 #include "ex7.h"
2667 extern "C" @{
2668   void adainit (void);
2669   void adafinal (void);
2670   void method1 (A *t);
2673 void method1 (A *t)
2675   t->method1 ();
2678 int main ()
2680   A obj;
2681   adainit ();
2682   obj.method2 (3030);
2683   adafinal ();
2686 //ex7.h
2688 class Origin @{
2689  public:
2690   int o_value;
2692 class A : public Origin @{
2693  public:
2694   void method1 (void);
2695   void method2 (int v);
2696   A();
2697   int   a_value;
2700 //ex7.C
2702 #include "ex7.h"
2703 #include <stdio.h>
2705 extern "C" @{ void ada_method2 (A *t, int v);@}
2707 void A::method1 (void)
2709   a_value = 2020;
2710   printf ("in A::method1, a_value = %d \n",a_value);
2714 void A::method2 (int v)
2716    ada_method2 (this, v);
2717    printf ("in A::method2, a_value = %d \n",a_value);
2721 A::A(void)
2723    a_value = 1010;
2724   printf ("in A::A, a_value = %d \n",a_value);
2726 @end smallexample
2728 @smallexample @c ada
2729 --@i{ Ada sources}
2730 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2732    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2733    @b{begin}
2734       Method1 (This);
2735       This.A_Value := V;
2736    @b{end} Ada_Method2;
2738 @b{end} Simple_Cpp_Interface;
2740 @b{with} System;
2741 @b{package} Simple_Cpp_Interface @b{is}
2742    @b{type} A @b{is} @b{limited}
2743       @b{record}
2744          Vptr    : System.Address;
2745          O_Value : Integer;
2746          A_Value : Integer;
2747       @b{end} @b{record};
2748    @b{pragma} Convention (C, A);
2750    @b{procedure} Method1 (This : @b{in} @b{out} A);
2751    @b{pragma} Import (C, Method1);
2753    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2754    @b{pragma} Export (C, Ada_Method2);
2756 @b{end} Simple_Cpp_Interface;
2757 @end smallexample
2759 @node Interfacing with C++ constructors
2760 @subsection Interfacing with C++ constructors
2761 @noindent
2763 In order to interface with C++ constructors GNAT provides the
2764 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2765 gnat_rm, GNAT Reference Manual}, for additional information).
2766 In this section we present some common uses of C++ constructors
2767 in mixed-languages programs in GNAT.
2769 Let us assume that we need to interface with the following
2770 C++ class:
2772 @smallexample
2773 @b{class} Root @{
2774 @b{public}:
2775   int  a_value;
2776   int  b_value;
2777   @b{virtual} int Get_Value ();
2778   Root();              // Default constructor
2779   Root(int v);         // 1st non-default constructor
2780   Root(int v, int w);  // 2nd non-default constructor
2782 @end smallexample
2784 For this purpose we can write the following package spec (further
2785 information on how to build this spec is available in
2786 @ref{Interfacing with C++ at the Class Level} and
2787 @ref{Generating Ada Bindings for C and C++ headers}).
2789 @smallexample @c ada
2790 @b{with} Interfaces.C; @b{use} Interfaces.C;
2791 @b{package} Pkg_Root @b{is}
2792   @b{type} Root @b{is} @b{tagged} @b{limited} @b{record}
2793      A_Value : int;
2794      B_Value : int;
2795   @b{end} @b{record};
2796   @b{pragma} Import (CPP, Root);
2798   @b{function} Get_Value (Obj : Root) @b{return} int;
2799   @b{pragma} Import (CPP, Get_Value);
2801   @b{function} Constructor @b{return} Root;
2802   @b{pragma} Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2804   @b{function} Constructor (v : Integer) @b{return} Root;
2805   @b{pragma} Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2807   @b{function} Constructor (v, w : Integer) @b{return} Root;
2808   @b{pragma} Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2809 @b{end} Pkg_Root;
2810 @end smallexample
2812 On the Ada side the constructor is represented by a function (whose
2813 name is arbitrary) that returns the classwide type corresponding to
2814 the imported C++ class. Although the constructor is described as a
2815 function, it is typically a procedure with an extra implicit argument
2816 (the object being initialized) at the implementation level. GNAT
2817 issues the appropriate call, whatever it is, to get the object
2818 properly initialized.
2820 Constructors can only appear in the following contexts:
2822 @itemize @bullet
2823 @item
2824 On the right side of an initialization of an object of type @var{T}.
2825 @item
2826 On the right side of an initialization of a record component of type @var{T}.
2827 @item
2828 In an Ada 2005 limited aggregate.
2829 @item
2830 In an Ada 2005 nested limited aggregate.
2831 @item
2832 In an Ada 2005 limited aggregate that initializes an object built in
2833 place by an extended return statement.
2834 @end itemize
2836 @noindent
2837 In a declaration of an object whose type is a class imported from C++,
2838 either the default C++ constructor is implicitly called by GNAT, or
2839 else the required C++ constructor must be explicitly called in the
2840 expression that initializes the object. For example:
2842 @smallexample @c ada
2843   Obj1 : Root;
2844   Obj2 : Root := Constructor;
2845   Obj3 : Root := Constructor (v => 10);
2846   Obj4 : Root := Constructor (30, 40);
2847 @end smallexample
2849 The first two declarations are equivalent: in both cases the default C++
2850 constructor is invoked (in the former case the call to the constructor is
2851 implicit, and in the latter case the call is explicit in the object
2852 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2853 that takes an integer argument, and @code{Obj4} is initialized by the
2854 non-default C++ constructor that takes two integers.
2856 Let us derive the imported C++ class in the Ada side. For example:
2858 @smallexample @c ada
2859   @b{type} DT @b{is} @b{new} Root @b{with} @b{record}
2860      C_Value : Natural := 2009;
2861   @b{end} @b{record};
2862 @end smallexample
2864 In this case the components DT inherited from the C++ side must be
2865 initialized by a C++ constructor, and the additional Ada components
2866 of type DT are initialized by GNAT. The initialization of such an
2867 object is done either by default, or by means of a function returning
2868 an aggregate of type DT, or by means of an extension aggregate.
2870 @smallexample @c ada
2871   Obj5 : DT;
2872   Obj6 : DT := Function_Returning_DT (50);
2873   Obj7 : DT := (Constructor (30,40) @b{with} C_Value => 50);
2874 @end smallexample
2876 The declaration of @code{Obj5} invokes the default constructors: the
2877 C++ default constructor of the parent type takes care of the initialization
2878 of the components inherited from Root, and GNAT takes care of the default
2879 initialization of the additional Ada components of type DT (that is,
2880 @code{C_Value} is initialized to value 2009). The order of invocation of
2881 the constructors is consistent with the order of elaboration required by
2882 Ada and C++. That is, the constructor of the parent type is always called
2883 before the constructor of the derived type.
2885 Let us now consider a record that has components whose type is imported
2886 from C++. For example:
2888 @smallexample @c ada
2889   @b{type} Rec1 @b{is} @b{limited} @b{record}
2890      Data1 : Root := Constructor (10);
2891      Value : Natural := 1000;
2892   @b{end} @b{record};
2894   @b{type} Rec2 (D : Integer := 20) @b{is} @b{limited} @b{record}
2895      Rec   : Rec1;
2896      Data2 : Root := Constructor (D, 30);
2897   @b{end} @b{record};
2898 @end smallexample
2900 The initialization of an object of type @code{Rec2} will call the
2901 non-default C++ constructors specified for the imported components.
2902 For example:
2904 @smallexample @c ada
2905   Obj8 : Rec2 (40);
2906 @end smallexample
2908 Using Ada 2005 we can use limited aggregates to initialize an object
2909 invoking C++ constructors that differ from those specified in the type
2910 declarations. For example:
2912 @smallexample @c ada
2913   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2914                           @b{others} => <>),
2915                   @b{others} => <>);
2916 @end smallexample
2918 The above declaration uses an Ada 2005 limited aggregate to
2919 initialize @code{Obj9}, and the C++ constructor that has two integer
2920 arguments is invoked to initialize the @code{Data1} component instead
2921 of the constructor specified in the declaration of type @code{Rec1}. In
2922 Ada 2005 the box in the aggregate indicates that unspecified components
2923 are initialized using the expression (if any) available in the component
2924 declaration. That is, in this case discriminant @code{D} is initialized
2925 to value @code{20}, @code{Value} is initialized to value 1000, and the
2926 non-default C++ constructor that handles two integers takes care of
2927 initializing component @code{Data2} with values @code{20,30}.
2929 In Ada 2005 we can use the extended return statement to build the Ada
2930 equivalent to C++ non-default constructors. For example:
2932 @smallexample @c ada
2933   @b{function} Constructor (V : Integer) @b{return} Rec2 @b{is}
2934   @b{begin}
2935      @b{return} Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
2936                                    @b{others} => <>),
2937                            @b{others} => <>) @b{do}
2938         --@i{  Further actions required for construction of}
2939         --@i{  objects of type Rec2}
2940         ...
2941      @b{end} @b{record};
2942   @b{end} Constructor;
2943 @end smallexample
2945 In this example the extended return statement construct is used to
2946 build in place the returned object whose components are initialized
2947 by means of a limited aggregate. Any further action associated with
2948 the constructor can be placed inside the construct.
2950 @node Interfacing with C++ at the Class Level
2951 @subsection Interfacing with C++ at the Class Level
2952 @noindent
2953 In this section we demonstrate the GNAT features for interfacing with
2954 C++ by means of an example making use of Ada 2005 abstract interface
2955 types. This example consists of a classification of animals; classes
2956 have been used to model our main classification of animals, and
2957 interfaces provide support for the management of secondary
2958 classifications. We first demonstrate a case in which the types and
2959 constructors are defined on the C++ side and imported from the Ada
2960 side, and latter the reverse case.
2962 The root of our derivation will be the @code{Animal} class, with a
2963 single private attribute (the @code{Age} of the animal), a constructor,
2964 and two public primitives to set and get the value of this attribute.
2966 @smallexample
2967 @b{class} Animal @{
2968  @b{public}:
2969    @b{virtual} void Set_Age (int New_Age);
2970    @b{virtual} int Age ();
2971    Animal() @{Age_Count = 0;@};
2972  @b{private}:
2973    int Age_Count;
2975 @end smallexample
2977 Abstract interface types are defined in C++ by means of classes with pure
2978 virtual functions and no data members. In our example we will use two
2979 interfaces that provide support for the common management of @code{Carnivore}
2980 and @code{Domestic} animals:
2982 @smallexample
2983 @b{class} Carnivore @{
2984 @b{public}:
2985    @b{virtual} int Number_Of_Teeth () = 0;
2988 @b{class} Domestic @{
2989 @b{public}:
2990    @b{virtual void} Set_Owner (char* Name) = 0;
2992 @end smallexample
2994 Using these declarations, we can now say that a @code{Dog} is an animal that is
2995 both Carnivore and Domestic, that is:
2997 @smallexample
2998 @b{class} Dog : Animal, Carnivore, Domestic @{
2999  @b{public}:
3000    @b{virtual} int  Number_Of_Teeth ();
3001    @b{virtual} void Set_Owner (char* Name);
3003    Dog(); // Constructor
3004  @b{private}:
3005    int  Tooth_Count;
3006    char *Owner;
3008 @end smallexample
3010 In the following examples we will assume that the previous declarations are
3011 located in a file named @code{animals.h}. The following package demonstrates
3012 how to import these C++ declarations from the Ada side:
3014 @smallexample @c ada
3015 @b{with} Interfaces.C.Strings; @b{use} Interfaces.C.Strings;
3016 @b{package} Animals @b{is}
3017   @b{type} Carnivore @b{is} @b{limited} interface;
3018   @b{pragma} Convention (C_Plus_Plus, Carnivore);
3019   @b{function} Number_Of_Teeth (X : Carnivore)
3020      @b{return} Natural @b{is} @b{abstract};
3022   @b{type} Domestic @b{is} @b{limited} interface;
3023   @b{pragma} Convention (C_Plus_Plus, Domestic);
3024   @b{procedure} Set_Owner
3025     (X    : @b{in} @b{out} Domestic;
3026      Name : Chars_Ptr) @b{is} @b{abstract};
3028   @b{type} Animal @b{is} @b{tagged} @b{limited} @b{record}
3029     Age : Natural;
3030   @b{end} @b{record};
3031   @b{pragma} Import (C_Plus_Plus, Animal);
3033   @b{procedure} Set_Age (X : @b{in} @b{out} Animal; Age : Integer);
3034   @b{pragma} Import (C_Plus_Plus, Set_Age);
3036   @b{function} Age (X : Animal) @b{return} Integer;
3037   @b{pragma} Import (C_Plus_Plus, Age);
3039   @b{function} New_Animal @b{return} Animal;
3040   @b{pragma} CPP_Constructor (New_Animal);
3041   @b{pragma} Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
3043   @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
3044     Tooth_Count : Natural;
3045     Owner       : String (1 .. 30);
3046   @b{end} @b{record};
3047   @b{pragma} Import (C_Plus_Plus, Dog);
3049   @b{function} Number_Of_Teeth (A : Dog) @b{return} Natural;
3050   @b{pragma} Import (C_Plus_Plus, Number_Of_Teeth);
3052   @b{procedure} Set_Owner (A : @b{in} @b{out} Dog; Name : Chars_Ptr);
3053   @b{pragma} Import (C_Plus_Plus, Set_Owner);
3055   @b{function} New_Dog @b{return} Dog;
3056   @b{pragma} CPP_Constructor (New_Dog);
3057   @b{pragma} Import (CPP, New_Dog, "_ZN3DogC2Ev");
3058 @b{end} Animals;
3059 @end smallexample
3061 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3062 interfacing with these C++ classes is easy. The only requirement is that all
3063 the primitives and components must be declared exactly in the same order in
3064 the two languages.
3066 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3067 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3068 the arguments to the called primitives will be the same as for C++. For the
3069 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3070 to indicate that they have been defined on the C++ side; this is required
3071 because the dispatch table associated with these tagged types will be built
3072 in the C++ side and therefore will not contain the predefined Ada primitives
3073 which Ada would otherwise expect.
3075 As the reader can see there is no need to indicate the C++ mangled names
3076 associated with each subprogram because it is assumed that all the calls to
3077 these primitives will be dispatching calls. The only exception is the
3078 constructor, which must be registered with the compiler by means of
3079 @code{pragma CPP_Constructor} and needs to provide its associated C++
3080 mangled name because the Ada compiler generates direct calls to it.
3082 With the above packages we can now declare objects of type Dog on the Ada side
3083 and dispatch calls to the corresponding subprograms on the C++ side. We can
3084 also extend the tagged type Dog with further fields and primitives, and
3085 override some of its C++ primitives on the Ada side. For example, here we have
3086 a type derivation defined on the Ada side that inherits all the dispatching
3087 primitives of the ancestor from the C++ side.
3089 @smallexample
3090 @b{with} Animals; @b{use} Animals;
3091 @b{package} Vaccinated_Animals @b{is}
3092   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3093   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3094 @b{end} Vaccinated_Animals;
3095 @end smallexample
3097 It is important to note that, because of the ABI compatibility, the programmer
3098 does not need to add any further information to indicate either the object
3099 layout or the dispatch table entry associated with each dispatching operation.
3101 Now let us define all the types and constructors on the Ada side and export
3102 them to C++, using the same hierarchy of our previous example:
3104 @smallexample @c ada
3105 @b{with} Interfaces.C.Strings;
3106 @b{use} Interfaces.C.Strings;
3107 @b{package} Animals @b{is}
3108   @b{type} Carnivore @b{is} @b{limited} interface;
3109   @b{pragma} Convention (C_Plus_Plus, Carnivore);
3110   @b{function} Number_Of_Teeth (X : Carnivore)
3111      @b{return} Natural @b{is} @b{abstract};
3113   @b{type} Domestic @b{is} @b{limited} interface;
3114   @b{pragma} Convention (C_Plus_Plus, Domestic);
3115   @b{procedure} Set_Owner
3116     (X    : @b{in} @b{out} Domestic;
3117      Name : Chars_Ptr) @b{is} @b{abstract};
3119   @b{type} Animal @b{is} @b{tagged} @b{record}
3120     Age : Natural;
3121   @b{end} @b{record};
3122   @b{pragma} Convention (C_Plus_Plus, Animal);
3124   @b{procedure} Set_Age (X : @b{in} @b{out} Animal; Age : Integer);
3125   @b{pragma} Export (C_Plus_Plus, Set_Age);
3127   @b{function} Age (X : Animal) @b{return} Integer;
3128   @b{pragma} Export (C_Plus_Plus, Age);
3130   @b{function} New_Animal @b{return} Animal'Class;
3131   @b{pragma} Export (C_Plus_Plus, New_Animal);
3133   @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
3134     Tooth_Count : Natural;
3135     Owner       : String (1 .. 30);
3136   @b{end} @b{record};
3137   @b{pragma} Convention (C_Plus_Plus, Dog);
3139   @b{function} Number_Of_Teeth (A : Dog) @b{return} Natural;
3140   @b{pragma} Export (C_Plus_Plus, Number_Of_Teeth);
3142   @b{procedure} Set_Owner (A : @b{in} @b{out} Dog; Name : Chars_Ptr);
3143   @b{pragma} Export (C_Plus_Plus, Set_Owner);
3145   @b{function} New_Dog @b{return} Dog'Class;
3146   @b{pragma} Export (C_Plus_Plus, New_Dog);
3147 @b{end} Animals;
3148 @end smallexample
3150 Compared with our previous example the only differences are the use of
3151 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
3152 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3153 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3154 nothing else to be done; as explained above, the only requirement is that all
3155 the primitives and components are declared in exactly the same order.
3157 For completeness, let us see a brief C++ main program that uses the
3158 declarations available in @code{animals.h} (presented in our first example) to
3159 import and use the declarations from the Ada side, properly initializing and
3160 finalizing the Ada run-time system along the way:
3162 @smallexample
3163 @b{#include} "animals.h"
3164 @b{#include} <iostream>
3165 @b{using namespace} std;
3167 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3168 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3169 void Check_Animal (Animal *obj)       @{@dots{}@}
3170 void Check_Dog (Dog *obj)             @{@dots{}@}
3172 @b{extern} "C" @{
3173   void adainit (void);
3174   void adafinal (void);
3175   Dog* new_dog ();
3178 void test ()
3180   Dog *obj = new_dog();  // Ada constructor
3181   Check_Carnivore (obj); // Check secondary DT
3182   Check_Domestic (obj);  // Check secondary DT
3183   Check_Animal (obj);    // Check primary DT
3184   Check_Dog (obj);       // Check primary DT
3187 int main ()
3189   adainit ();  test();  adafinal ();
3190   return 0;
3192 @end smallexample
3194 @node Comparison between GNAT and C/C++ Compilation Models
3195 @section Comparison between GNAT and C/C++ Compilation Models
3197 @noindent
3198 The GNAT model of compilation is close to the C and C++ models. You can
3199 think of Ada specs as corresponding to header files in C. As in C, you
3200 don't need to compile specs; they are compiled when they are used. The
3201 Ada @code{with} is similar in effect to the @code{#include} of a C
3202 header.
3204 One notable difference is that, in Ada, you may compile specs separately
3205 to check them for semantic and syntactic accuracy. This is not always
3206 possible with C headers because they are fragments of programs that have
3207 less specific syntactic or semantic rules.
3209 The other major difference is the requirement for running the binder,
3210 which performs two important functions. First, it checks for
3211 consistency. In C or C++, the only defense against assembling
3212 inconsistent programs lies outside the compiler, in a makefile, for
3213 example. The binder satisfies the Ada requirement that it be impossible
3214 to construct an inconsistent program when the compiler is used in normal
3215 mode.
3217 @cindex Elaboration order control
3218 The other important function of the binder is to deal with elaboration
3219 issues. There are also elaboration issues in C++ that are handled
3220 automatically. This automatic handling has the advantage of being
3221 simpler to use, but the C++ programmer has no control over elaboration.
3222 Where @code{gnatbind} might complain there was no valid order of
3223 elaboration, a C++ compiler would simply construct a program that
3224 malfunctioned at run time.
3226 @node Comparison between GNAT and Conventional Ada Library Models
3227 @section Comparison between GNAT and Conventional Ada Library Models
3229 @noindent
3230 This section is intended for Ada programmers who have
3231 used an Ada compiler implementing the traditional Ada library
3232 model, as described in the Ada Reference Manual.
3234 @cindex GNAT library
3235 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3236 source files themselves acts as the library. Compiling Ada programs does
3237 not generate any centralized information, but rather an object file and
3238 a ALI file, which are of interest only to the binder and linker.
3239 In a traditional system, the compiler reads information not only from
3240 the source file being compiled, but also from the centralized library.
3241 This means that the effect of a compilation depends on what has been
3242 previously compiled. In particular:
3244 @itemize @bullet
3245 @item
3246 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3247 to the version of the unit most recently compiled into the library.
3249 @item
3250 Inlining is effective only if the necessary body has already been
3251 compiled into the library.
3253 @item
3254 Compiling a unit may obsolete other units in the library.
3255 @end itemize
3257 @noindent
3258 In GNAT, compiling one unit never affects the compilation of any other
3259 units because the compiler reads only source files. Only changes to source
3260 files can affect the results of a compilation. In particular:
3262 @itemize @bullet
3263 @item
3264 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3265 to the source version of the unit that is currently accessible to the
3266 compiler.
3268 @item
3269 @cindex Inlining
3270 Inlining requires the appropriate source files for the package or
3271 subprogram bodies to be available to the compiler. Inlining is always
3272 effective, independent of the order in which units are complied.
3274 @item
3275 Compiling a unit never affects any other compilations. The editing of
3276 sources may cause previous compilations to be out of date if they
3277 depended on the source file being modified.
3278 @end itemize
3280 @noindent
3281 The most important result of these differences is that order of compilation
3282 is never significant in GNAT. There is no situation in which one is
3283 required to do one compilation before another. What shows up as order of
3284 compilation requirements in the traditional Ada library becomes, in
3285 GNAT, simple source dependencies; in other words, there is only a set
3286 of rules saying what source files must be present when a file is
3287 compiled.
3290 @c *************************
3291 @node Compiling with gcc
3292 @chapter Compiling with @command{gcc}
3294 @noindent
3295 This chapter discusses how to compile Ada programs using the @command{gcc}
3296 command. It also describes the set of switches
3297 that can be used to control the behavior of the compiler.
3298 @menu
3299 * Compiling Programs::
3300 * Switches for gcc::
3301 * Search Paths and the Run-Time Library (RTL)::
3302 * Order of Compilation Issues::
3303 * Examples::
3304 @end menu
3306 @node Compiling Programs
3307 @section Compiling Programs
3309 @noindent
3310 The first step in creating an executable program is to compile the units
3311 of the program using the @command{gcc} command. You must compile the
3312 following files:
3314 @itemize @bullet
3315 @item
3316 the body file (@file{.adb}) for a library level subprogram or generic
3317 subprogram
3319 @item
3320 the spec file (@file{.ads}) for a library level package or generic
3321 package that has no body
3323 @item
3324 the body file (@file{.adb}) for a library level package
3325 or generic package that has a body
3327 @end itemize
3329 @noindent
3330 You need @emph{not} compile the following files
3332 @itemize @bullet
3334 @item
3335 the spec of a library unit which has a body
3337 @item
3338 subunits
3339 @end itemize
3341 @noindent
3342 because they are compiled as part of compiling related units. GNAT
3343 package specs
3344 when the corresponding body is compiled, and subunits when the parent is
3345 compiled.
3347 @cindex cannot generate code
3348 If you attempt to compile any of these files, you will get one of the
3349 following error messages (where @var{fff} is the name of the file you
3350 compiled):
3352 @smallexample
3353 cannot generate code for file @var{fff} (package spec)
3354 to check package spec, use -gnatc
3356 cannot generate code for file @var{fff} (missing subunits)
3357 to check parent unit, use -gnatc
3359 cannot generate code for file @var{fff} (subprogram spec)
3360 to check subprogram spec, use -gnatc
3362 cannot generate code for file @var{fff} (subunit)
3363 to check subunit, use -gnatc
3364 @end smallexample
3366 @noindent
3367 As indicated by the above error messages, if you want to submit
3368 one of these files to the compiler to check for correct semantics
3369 without generating code, then use the @option{-gnatc} switch.
3371 The basic command for compiling a file containing an Ada unit is
3373 @smallexample
3374 @c $ gcc -c @ovar{switches} @file{file name}
3375 @c Expanding @ovar macro inline (explanation in macro def comments)
3376 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3377 @end smallexample
3379 @noindent
3380 where @var{file name} is the name of the Ada file (usually
3381 having an extension
3382 @file{.ads} for a spec or @file{.adb} for a body).
3383 You specify the
3384 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3385 The result of a successful compilation is an object file, which has the
3386 same name as the source file but an extension of @file{.o} and an Ada
3387 Library Information (ALI) file, which also has the same name as the
3388 source file, but with @file{.ali} as the extension. GNAT creates these
3389 two output files in the current directory, but you may specify a source
3390 file in any directory using an absolute or relative path specification
3391 containing the directory information.
3393 @findex gnat1
3394 @command{gcc} is actually a driver program that looks at the extensions of
3395 the file arguments and loads the appropriate compiler. For example, the
3396 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3397 These programs are in directories known to the driver program (in some
3398 configurations via environment variables you set), but need not be in
3399 your path. The @command{gcc} driver also calls the assembler and any other
3400 utilities needed to complete the generation of the required object
3401 files.
3403 It is possible to supply several file names on the same @command{gcc}
3404 command. This causes @command{gcc} to call the appropriate compiler for
3405 each file. For example, the following command lists two separate
3406 files to be compiled:
3408 @smallexample
3409 $ gcc -c x.adb y.adb
3410 @end smallexample
3412 @noindent
3413 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3414 @file{y.adb}.
3415 The compiler generates two object files @file{x.o} and @file{y.o}
3416 and the two ALI files @file{x.ali} and @file{y.ali}.
3417 Any switches apply to all the files listed,
3419 @node Switches for gcc
3420 @section Switches for @command{gcc}
3422 @noindent
3423 The @command{gcc} command accepts switches that control the
3424 compilation process. These switches are fully described in this section.
3425 First we briefly list all the switches, in alphabetical order, then we
3426 describe the switches in more detail in functionally grouped sections.
3428 More switches exist for GCC than those documented here, especially
3429 for specific targets. However, their use is not recommended as
3430 they may change code generation in ways that are incompatible with
3431 the Ada run-time library, or can cause inconsistencies between
3432 compilation units.
3434 @menu
3435 * Output and Error Message Control::
3436 * Warning Message Control::
3437 * Debugging and Assertion Control::
3438 * Validity Checking::
3439 * Style Checking::
3440 * Run-Time Checks::
3441 * Using gcc for Syntax Checking::
3442 * Using gcc for Semantic Checking::
3443 * Compiling Different Versions of Ada::
3444 * Character Set Control::
3445 * File Naming Control::
3446 * Subprogram Inlining Control::
3447 * Auxiliary Output Control::
3448 * Debugging Control::
3449 * Exception Handling Control::
3450 * Units to Sources Mapping Files::
3451 * Integrated Preprocessing::
3452 * Code Generation Control::
3453 @end menu
3455 @table @option
3456 @c !sort!
3457 @cindex @option{-b} (@command{gcc})
3458 @item -b @var{target}
3459 Compile your program to run on @var{target}, which is the name of a
3460 system configuration. You must have a GNAT cross-compiler built if
3461 @var{target} is not the same as your host system.
3463 @item -B@var{dir}
3464 @cindex @option{-B} (@command{gcc})
3465 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3466 from @var{dir} instead of the default location. Only use this switch
3467 when multiple versions of the GNAT compiler are available.
3468 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3469 GNU Compiler Collection (GCC)}, for further details. You would normally
3470 use the @option{-b} or @option{-V} switch instead.
3472 @item -c
3473 @cindex @option{-c} (@command{gcc})
3474 Compile. Always use this switch when compiling Ada programs.
3476 Note: for some other languages when using @command{gcc}, notably in
3477 the case of C and C++, it is possible to use
3478 use @command{gcc} without a @option{-c} switch to
3479 compile and link in one step. In the case of GNAT, you
3480 cannot use this approach, because the binder must be run
3481 and @command{gcc} cannot be used to run the GNAT binder.
3483 @item -fcallgraph-info@r{[}=su,da@r{]}
3484 @cindex @option{-fcallgraph-info} (@command{gcc})
3485 Makes the compiler output callgraph information for the program, on a
3486 per-file basis. The information is generated in the VCG format.  It can
3487 be decorated with additional, per-node and/or per-edge information, if a
3488 list of comma-separated markers is additionally specified. When the
3489 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3490 marker is specified, the callgraph is decorated with information about
3491 dynamically allocated objects.
3493 @item -fdump-scos
3494 @cindex @option{-fdump-scos} (@command{gcc})
3495 Generates SCO (Source Coverage Obligation) information in the ALI file.
3496 This information is used by advanced coverage tools. See unit @file{SCOs}
3497 in the compiler sources for details in files @file{scos.ads} and
3498 @file{scos.adb}.
3500 @item -fdump-xref
3501 @cindex @option{-fdump-xref} (@command{gcc})
3502 Generates cross reference information in GLI files for C and C++ sources.
3503 The GLI files have the same syntax as the ALI files for Ada, and can be used
3504 for source navigation in IDEs and on the command line using e.g. gnatxref
3505 and the @option{--ext=gli} switch.
3507 @item -flto@r{[}=n@r{]}
3508 @cindex @option{-flto} (@command{gcc})
3509 Enables Link Time Optimization. This switch must be used in conjunction
3510 with the traditional @option{-Ox} switches and instructs the compiler to
3511 defer most optimizations until the link stage. The advantage of this
3512 approach is that the compiler can do a whole-program analysis and choose
3513 the best interprocedural optimization strategy based on a complete view
3514 of the program, instead of a fragmentary view with the usual approach.
3515 This can also speed up the compilation of huge programs and reduce the
3516 size of the final executable, compared with a per-unit compilation with
3517 full inlining across modules enabled with the @option{-gnatn2} switch.
3518 The drawback of this approach is that it may require much more memory.
3519 The switch, as well as the accompanying @option{-Ox} switches, must be
3520 specified both for the compilation and the link phases.
3521 If the @var{n} parameter is specified, the optimization and final code
3522 generation at link time are executed using @var{n} parallel jobs by
3523 means of an installed @command{make} program.
3525 @item -fno-inline
3526 @cindex @option{-fno-inline} (@command{gcc})
3527 Suppresses all inlining, even if other optimization or inlining
3528 switches are set.  This includes suppression of inlining that
3529 results from the use of the pragma @code{Inline_Always}.
3530 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3531 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3532 effects if this switch is present.  Note that inlining can also
3533 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3535 @item -fno-inline-functions
3536 @cindex @option{-fno-inline-functions} (@command{gcc})
3537 Suppresses automatic inlining of subprograms, which is enabled
3538 if @option{-O3} is used.
3540 @item -fno-inline-small-functions
3541 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3542 Suppresses automatic inlining of small subprograms, which is enabled
3543 if @option{-O2} is used.
3545 @item -fno-inline-functions-called-once
3546 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3547 Suppresses inlining of subprograms local to the unit and called once
3548 from within it, which is enabled if @option{-O1} is used.
3550 @item -fno-ivopts
3551 @cindex @option{-fno-ivopts} (@command{gcc})
3552 Suppresses high-level loop induction variable optimizations, which are
3553 enabled if @option{-O1} is used. These optimizations are generally
3554 profitable but, for some specific cases of loops with numerous uses
3555 of the iteration variable that follow a common pattern, they may end
3556 up destroying the regularity that could be exploited at a lower level
3557 and thus producing inferior code.
3559 @item -fno-strict-aliasing
3560 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3561 Causes the compiler to avoid assumptions regarding non-aliasing
3562 of objects of different types. See
3563 @ref{Optimization and Strict Aliasing} for details.
3565 @item -fstack-check
3566 @cindex @option{-fstack-check} (@command{gcc})
3567 Activates stack checking.
3568 See @ref{Stack Overflow Checking} for details.
3570 @item -fstack-usage
3571 @cindex @option{-fstack-usage} (@command{gcc})
3572 Makes the compiler output stack usage information for the program, on a
3573 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3575 @item -g
3576 @cindex @option{-g} (@command{gcc})
3577 Generate debugging information. This information is stored in the object
3578 file and copied from there to the final executable file by the linker,
3579 where it can be read by the debugger. You must use the
3580 @option{-g} switch if you plan on using the debugger.
3582 @item -gnat83
3583 @cindex @option{-gnat83} (@command{gcc})
3584 Enforce Ada 83 restrictions.
3586 @item -gnat95
3587 @cindex @option{-gnat95} (@command{gcc})
3588 Enforce Ada 95 restrictions.
3590 @item -gnat05
3591 @cindex @option{-gnat05} (@command{gcc})
3592 Allow full Ada 2005 features.
3594 @item -gnat2005
3595 @cindex @option{-gnat2005} (@command{gcc})
3596 Allow full Ada 2005 features (same as @option{-gnat05})
3598 @item -gnat12
3599 @cindex @option{-gnat12} (@command{gcc})
3601 @item -gnat2012
3602 @cindex @option{-gnat2012} (@command{gcc})
3603 Allow full Ada 2012 features (same as @option{-gnat12})
3605 @item -gnata
3606 @cindex @option{-gnata} (@command{gcc})
3607 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3608 activated. Note that these pragmas can also be controlled using the
3609 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3610 It also activates pragmas @code{Check}, @code{Precondition}, and
3611 @code{Postcondition}. Note that these pragmas can also be controlled
3612 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3613 also activates all assertions defined in the RM as aspects: preconditions,
3614 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3615 corresponding pragmas for type invariants and (sub)type predicates are
3616 also activated. The default is that all these assertions are disabled,
3617 and have no effect, other than being checked for syntactic validity, and
3618 in the case of subtype predicates, constructions such as membership tests
3619 still test predicates even if assertions are turned off.
3621 @item -gnatA
3622 @cindex @option{-gnatA} (@command{gcc})
3623 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3624 it will be ignored.
3626 @item -gnatb
3627 @cindex @option{-gnatb} (@command{gcc})
3628 Generate brief messages to @file{stderr} even if verbose mode set.
3630 @item -gnatB
3631 @cindex @option{-gnatB} (@command{gcc})
3632 Assume no invalid (bad) values except for 'Valid attribute use
3633 (@pxref{Validity Checking}).
3635 @item -gnatc
3636 @cindex @option{-gnatc} (@command{gcc})
3637 Check syntax and semantics only (no code generation attempted). When the
3638 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3639 only given to the compiler (after @option{-cargs} or in package Compiler of
3640 the project file, @command{gnatmake} will fail because it will not find the
3641 object file after compilation. If @command{gnatmake} is called with
3642 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3643 Builder of the project file) then @command{gnatmake} will not fail because
3644 it will not look for the object files after compilation, and it will not try
3645 to build and link. This switch may not be given if a previous @code{-gnatR}
3646 switch has been given, since @code{-gnatR} requires that the code generator
3647 be called to complete determination of representation information.
3649 @item -gnatC
3650 @cindex @option{-gnatC} (@command{gcc})
3651 Generate CodePeer intermediate format (no code generation attempted).
3652 This switch will generate an intermediate representation suitable for
3653 use by CodePeer (@file{.scil} files). This switch is not compatible with
3654 code generation (it will, among other things, disable some switches such
3655 as -gnatn, and enable others such as -gnata).
3657 @item -gnatd
3658 @cindex @option{-gnatd} (@command{gcc})
3659 Specify debug options for the compiler. The string of characters after
3660 the @option{-gnatd} specify the specific debug options. The possible
3661 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3662 compiler source file @file{debug.adb} for details of the implemented
3663 debug options. Certain debug options are relevant to applications
3664 programmers, and these are documented at appropriate points in this
3665 users guide.
3667 @item -gnatD
3668 @cindex @option{-gnatD[nn]} (@command{gcc})
3669 Create expanded source files for source level debugging. This switch
3670 also suppress generation of cross-reference information
3671 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3672 -gnatR switch has been given, since these two switches are not compatible.
3674 @item -gnateA
3675 @cindex @option{-gnateA} (@command{gcc})
3676 Check that the actual parameters of a subprogram call are not aliases of one
3677 another. To qualify as aliasing, the actuals must denote objects of a composite
3678 type, their memory locations must be identical or overlapping, and at least one
3679 of the corresponding formal parameters must be of mode OUT or IN OUT.
3681 @smallexample
3682 type Rec_Typ is record
3683    Data : Integer := 0;
3684 end record;
3686 function Self (Val : Rec_Typ) return Rec_Typ is
3687 begin
3688    return Val;
3689 end Self;
3691 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
3692 begin
3693    null;
3694 end Detect_Aliasing;
3696 Obj : Rec_Typ;
3698 Detect_Aliasing (Obj, Obj);
3699 Detect_Aliasing (Obj, Self (Obj));
3700 @end smallexample
3702 In the example above, the first call to @code{Detect_Aliasing} fails with a
3703 @code{Program_Error} at runtime because the actuals for @code{Val_1} and
3704 @code{Val_2} denote the same object. The second call executes without raising
3705 an exception because @code{Self(Obj)} produces an anonymous object which does
3706 not share the memory location of @code{Obj}.
3708 @item -gnatec=@var{path}
3709 @cindex @option{-gnatec} (@command{gcc})
3710 Specify a configuration pragma file
3711 (the equal sign is optional)
3712 (@pxref{The Configuration Pragmas Files}).
3714 @item -gnateC
3715 @cindex @option{-gnateC} (@command{gcc})
3716 Generate CodePeer messages in a compiler-like format. This switch is only
3717 effective if @option{-gnatcC} is also specified and requires an installation
3718 of CodePeer.
3720 @item -gnated
3721 @cindex @option{-gnated} (@command{gcc})
3722 Disable atomic synchronization
3724 @item -gnateDsymbol@r{[}=@var{value}@r{]}
3725 @cindex @option{-gnateD} (@command{gcc})
3726 Defines a symbol, associated with @var{value}, for preprocessing.
3727 (@pxref{Integrated Preprocessing}).
3729 @item -gnateE
3730 @cindex @option{-gnateE} (@command{gcc})
3731 Generate extra information in exception messages. In particular, display
3732 extra column information and the value and range associated with index and
3733 range check failures, and extra column information for access checks.
3734 In cases where the compiler is able to determine at compile time that
3735 a check will fail, it gives a warning, and the extra information is not
3736 produced at run time.
3738 @item -gnatef
3739 @cindex @option{-gnatef} (@command{gcc})
3740 Display full source path name in brief error messages.
3742 @item -gnateF
3743 @cindex @option{-gnateF} (@command{gcc})
3744 Check for overflow on all floating-point operations, including those
3745 for unconstrained predefined types. See description of pragma
3746 @code{Check_Float_Overflow} in GNAT RM.
3748 @item -gnateG
3749 @cindex @option{-gnateG} (@command{gcc})
3750 Save result of preprocessing in a text file.
3752 @item -gnatei@var{nnn}
3753 @cindex @option{-gnatei} (@command{gcc})
3754 Set maximum number of instantiations during compilation of a single unit to
3755 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3756 the rare case when a single unit legitimately exceeds this limit.
3758 @item -gnateI@var{nnn}
3759 @cindex @option{-gnateI} (@command{gcc})
3760 Indicates that the source is a multi-unit source and that the index of the
3761 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3762 to be a valid index in the multi-unit source.
3764 @item -gnatel
3765 @cindex @option{-gnatel} (@command{gcc})
3766 This switch can be used with the static elaboration model to issue info
3767 messages showing
3768 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
3769 are generated. This is useful in diagnosing elaboration circularities
3770 caused by these implicit pragmas when using the static elaboration
3771 model. See See the section in this guide on elaboration checking for
3772 further details. These messages are not generated by default, and are
3773 intended only for temporary use when debugging circularity problems.
3775 @item -gnateL
3776 @cindex @option{-gnatel} (@command{gcc})
3777 This switch turns off the info messages about implicit elaboration pragmas.
3779 @item -gnatem=@var{path}
3780 @cindex @option{-gnatem} (@command{gcc})
3781 Specify a mapping file
3782 (the equal sign is optional)
3783 (@pxref{Units to Sources Mapping Files}).
3785 @item -gnatep=@var{file}
3786 @cindex @option{-gnatep} (@command{gcc})
3787 Specify a preprocessing data file
3788 (the equal sign is optional)
3789 (@pxref{Integrated Preprocessing}).
3791 @item -gnateP
3792 @cindex @option{-gnateP} (@command{gcc})
3793 Turn categorization dependency errors into warnings.
3794 Ada requires that units that WITH one another have compatible categories, for
3795 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3796 these errors become warnings (which can be ignored, or suppressed in the usual
3797 manner). This can be useful in some specialized circumstances such as the
3798 temporary use of special test software.
3800 @item -gnateS
3801 @cindex @option{-gnateS} (@command{gcc})
3802 Synonym of @option{-fdump-scos}, kept for backwards compatibility.
3804 @item -gnatet=@var{path}
3805 @cindex @option{-gnatet=file} (@command{gcc})
3806 Generate target dependent information. The format of the output file is
3807 described in the section about switch @option{-gnateT}.
3809 @item -gnateT=@var{path}
3810 @cindex @option{-gnateT} (@command{gcc})
3811 Read target dependent information, such as endianness or sizes and alignments
3812 of base type. If this switch is passed, the default target dependent
3813 information of the compiler is replaced by the one read from the input file.
3814 This is used by tools other than the compiler, e.g. to do
3815 semantic analysis of programs that will run on some other target than
3816 the machine on which the tool is run.
3818 The following target dependent values should be defined,
3819 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3820 positive integer value, and fields marked with a question mark are
3821 boolean fields, where a value of 0 is False, and a value of 1 is True:
3823 @smallexample
3824 Bits_BE                    : Nat; -- Bits stored big-endian?
3825 Bits_Per_Unit              : Pos; -- Bits in a storage unit
3826 Bits_Per_Word              : Pos; -- Bits in a word
3827 Bytes_BE                   : Nat; -- Bytes stored big-endian?
3828 Char_Size                  : Pos; -- Standard.Character'Size
3829 Double_Float_Alignment     : Nat; -- Alignment of double float
3830 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
3831 Double_Size                : Pos; -- Standard.Long_Float'Size
3832 Float_Size                 : Pos; -- Standard.Float'Size
3833 Float_Words_BE             : Nat; -- Float words stored big-endian?
3834 Int_Size                   : Pos; -- Standard.Integer'Size
3835 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
3836 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
3837 Long_Size                  : Pos; -- Standard.Long_Integer'Size
3838 Maximum_Alignment          : Pos; -- Maximum permitted alignment
3839 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
3840 Pointer_Size               : Pos; -- System.Address'Size
3841 Short_Enums                : Nat; -- Short foreign convention enums?
3842 Short_Size                 : Pos; -- Standard.Short_Integer'Size
3843 Strict_Alignment           : Nat; -- Strict alignment?
3844 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3845 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
3846 Words_BE                   : Nat; -- Words stored big-endian?
3847 @end smallexample
3849 The format of the input file is as follows. First come the values of
3850 the variables defined above, with one line per value:
3852 @smallexample
3853 name  value
3854 @end smallexample
3856 where @code{name} is the name of the parameter, spelled out in full,
3857 and cased as in the above list, and @code{value} is an unsigned decimal
3858 integer. Two or more blanks separates the name from the value.
3860 All the variables must be present, in alphabetical order (i.e. the
3861 same order as the list above).
3863 Then there is a blank line to separate the two parts of the file. Then
3864 come the lines showing the floating-point types to be registered, with
3865 one line per registered mode:
3867 @smallexample
3868 name  digs float_rep size alignment
3869 @end smallexample
3871 where @code{name} is the string name of the type (which can have
3872 single spaces embedded in the name (e.g. long double), @code{digs} is
3873 the number of digits for the floating-point type, @code{float_rep} is
3874 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3875 AAMP), @code{size} is the size in bits, @code{alignment} is the
3876 alignment in bits. The name is followed by at least two blanks, fields
3877 are separated by at least one blank, and a LF character immediately
3878 follows the alignment field.
3880 Here is an example of a target parameterization file:
3882 @smallexample
3883 Bits_BE                       0
3884 Bits_Per_Unit                 8
3885 Bits_Per_Word                64
3886 Bytes_BE                      0
3887 Char_Size                     8
3888 Double_Float_Alignment        0
3889 Double_Scalar_Alignment       0
3890 Double_Size                  64
3891 Float_Size                   32
3892 Float_Words_BE                0
3893 Int_Size                     64
3894 Long_Double_Size            128
3895 Long_Long_Size               64
3896 Long_Size                    64
3897 Maximum_Alignment            16
3898 Max_Unaligned_Field          64
3899 Pointer_Size                 64
3900 Short_Size                   16
3901 Strict_Alignment              0
3902 System_Allocator_Alignment   16
3903 Wchar_T_Size                 32
3904 Words_BE                      0
3906 float         15  I  64  64
3907 double        15  I  64  64
3908 long double   18  I  80 128
3909 TF            33  I 128 128
3910 @end smallexample
3912 @item -gnateu
3913 @cindex @option{-gnateu} (@command{gcc})
3914 Ignore unrecognized validity, warning, and style switches that
3915 appear after this switch is given. This may be useful when
3916 compiling sources developed on a later version of the compiler
3917 with an earlier version. Of course the earlier version must
3918 support this switch.
3920 @item -gnateV
3921 @cindex @option{-gnateV} (@command{gcc})
3922 Check that all actual parameters of a subprogram call are valid according to
3923 the rules of validity checking (@pxref{Validity Checking}).
3925 @item -gnateY
3926 @cindex @option{-gnateY} (@command{gcc})
3927 Ignore all STYLE_CHECKS pragmas. Full legality checks
3928 are still carried out, but the pragmas have no effect
3929 on what style checks are active. This allows all style
3930 checking options to be controlled from the command line.
3932 @item -gnatE
3933 @cindex @option{-gnatE} (@command{gcc})
3934 Full dynamic elaboration checks.
3936 @item -gnatf
3937 @cindex @option{-gnatf} (@command{gcc})
3938 Full errors. Multiple errors per line, all undefined references, do not
3939 attempt to suppress cascaded errors.
3941 @item -gnatF
3942 @cindex @option{-gnatF} (@command{gcc})
3943 Externals names are folded to all uppercase.
3945 @item -gnatg
3946 @cindex @option{-gnatg} (@command{gcc})
3947 Internal GNAT implementation mode. This should not be used for
3948 applications programs, it is intended only for use by the compiler
3949 and its run-time library. For documentation, see the GNAT sources.
3950 Note that @option{-gnatg} implies
3951 @option{-gnatw.ge} and
3952 @option{-gnatyg}
3953 so that all standard warnings and all standard style options are turned on.
3954 All warnings and style messages are treated as errors.
3956 @item -gnatG=nn
3957 @cindex @option{-gnatG[nn]} (@command{gcc})
3958 List generated expanded code in source form.
3960 @item -gnath
3961 @cindex @option{-gnath} (@command{gcc})
3962 Output usage information. The output is written to @file{stdout}.
3964 @item -gnati@var{c}
3965 @cindex @option{-gnati} (@command{gcc})
3966 Identifier character set
3967 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3968 For details of the possible selections for @var{c},
3969 see @ref{Character Set Control}.
3971 @item -gnatI
3972 @cindex @option{-gnatI} (@command{gcc})
3973 Ignore representation clauses. When this switch is used,
3974 representation clauses are treated as comments. This is useful
3975 when initially porting code where you want to ignore rep clause
3976 problems, and also for compiling foreign code (particularly
3977 for use with ASIS). The representation clauses that are ignored
3978 are: enumeration_representation_clause, record_representation_clause,
3979 and attribute_definition_clause for the following attributes:
3980 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
3981 Object_Size, Size, Small, Stream_Size, and Value_Size.
3982 Note that this option should be used only for compiling -- the
3983 code is likely to malfunction at run time.
3985 Note that when @code{-gnatct} is used to generate trees for input
3986 into @code{ASIS} tools, these representation clauses are removed
3987 from the tree and ignored. This means that the tool will not see them.
3989 @item -gnatjnn
3990 @cindex @option{-gnatjnn} (@command{gcc})
3991 Reformat error messages to fit on nn character lines
3993 @item -gnatk=@var{n}
3994 @cindex @option{-gnatk} (@command{gcc})
3995 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
3997 @item -gnatl
3998 @cindex @option{-gnatl} (@command{gcc})
3999 Output full source listing with embedded error messages.
4001 @item -gnatL
4002 @cindex @option{-gnatL} (@command{gcc})
4003 Used in conjunction with -gnatG or -gnatD to intersperse original
4004 source lines (as comment lines with line numbers) in the expanded
4005 source output.
4007 @item -gnatm=@var{n}
4008 @cindex @option{-gnatm} (@command{gcc})
4009 Limit number of detected error or warning messages to @var{n}
4010 where @var{n} is in the range 1..999999. The default setting if
4011 no switch is given is 9999. If the number of warnings reaches this
4012 limit, then a message is output and further warnings are suppressed,
4013 but the compilation is continued. If the number of error messages
4014 reaches this limit, then a message is output and the compilation
4015 is abandoned. The equal sign here is optional. A value of zero
4016 means that no limit applies.
4018 @item -gnatn[12]
4019 @cindex @option{-gnatn} (@command{gcc})
4020 Activate inlining for subprograms for which pragma @code{Inline} is
4021 specified. This inlining is performed by the GCC back-end. An optional
4022 digit sets the inlining level: 1 for moderate inlining across modules
4023 or 2 for full inlining across modules. If no inlining level is specified,
4024 the compiler will pick it based on the optimization level.
4026 @item -gnatN
4027 @cindex @option{-gnatN} (@command{gcc})
4028 Activate front end inlining for subprograms for which
4029 pragma @code{Inline} is specified. This inlining is performed
4030 by the front end and will be visible in the
4031 @option{-gnatG} output.
4033 When using a gcc-based back end (in practice this means using any version
4034 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4035 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4036 Historically front end inlining was more extensive than the gcc back end
4037 inlining, but that is no longer the case.
4039 @item -gnato0
4040 @cindex @option{-gnato0} (@command{gcc})
4041 Suppresses overflow checking. This causes the behavior of the compiler to
4042 match the default for older versions where overflow checking was suppressed
4043 by default. This is equivalent to having
4044 @code{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
4046 @item -gnato??
4047 @cindex @option{-gnato??} (@command{gcc})
4048 Set default mode for handling generation of code to avoid intermediate
4049 arithmetic overflow. Here `@code{??}' is two digits, a
4050 single digit, or nothing. Each digit is one of the digits `@code{1}'
4051 through `@code{3}':
4053 @itemize @bullet
4054 @item   @code{1}:
4055 all intermediate overflows checked against base type (@code{STRICT})
4056 @item   @code{2}:
4057 minimize intermediate overflows (@code{MINIMIZED})
4058 @item   @code{3}:
4059 eliminate intermediate overflows (@code{ELIMINATED})
4060 @end itemize
4062 If only one digit appears then it applies to all
4063 cases; if two digits are given, then the first applies outside
4064 assertions, and the second within assertions.
4066 If no digits follow the @option{-gnato}, then it is equivalent to
4067 @option{-gnato11},
4068 causing all intermediate overflows to be handled in strict mode.
4070 This switch also causes arithmetic overflow checking to be performed
4071 (as though @code{pragma Unsuppress (Overflow_Mode)} had been specified.
4073 The default if no option @option{-gnato} is given is that overflow handling
4074 is in @code{STRICT} mode (computations done using the base type), and that
4075 overflow checking is enabled.
4077 Note that division by zero is a separate check that is not
4078 controlled by this switch (division by zero checking is on by default).
4080 See also @ref{Specifying the Desired Mode}.
4082 @item -gnatp
4083 @cindex @option{-gnatp} (@command{gcc})
4084 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4085 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4087 @item -gnat-p
4088 @cindex @option{-gnat-p} (@command{gcc})
4089 Cancel effect of previous @option{-gnatp} switch.
4091 @item -gnatP
4092 @cindex @option{-gnatP} (@command{gcc})
4093 Enable polling. This is required on some systems (notably Windows NT) to
4094 obtain asynchronous abort and asynchronous transfer of control capability.
4095 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4096 details.
4098 @item -gnatq
4099 @cindex @option{-gnatq} (@command{gcc})
4100 Don't quit. Try semantics, even if parse errors.
4102 @item -gnatQ
4103 @cindex @option{-gnatQ} (@command{gcc})
4104 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4105 Note that code generation is still suppressed in the presence of any
4106 errors, so even with @option{-gnatQ} no object file is generated.
4108 @item -gnatr
4109 @cindex @option{-gnatr} (@command{gcc})
4110 Treat pragma Restrictions as Restriction_Warnings.
4112 @item -gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}
4113 @cindex @option{-gnatR} (@command{gcc})
4114 Output representation information for declared types and objects.
4115 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4116 been given, since these two switches are not compatible.
4118 @item -gnatRm[s]
4119 Output convention and parameter passing mechanisms for all subprograms.
4121 @item -gnats
4122 @cindex @option{-gnats} (@command{gcc})
4123 Syntax check only.
4125 @item -gnatS
4126 @cindex @option{-gnatS} (@command{gcc})
4127 Print package Standard.
4129 @item -gnatt
4130 @cindex @option{-gnatt} (@command{gcc})
4131 Generate tree output file.
4133 @item -gnatT@var{nnn}
4134 @cindex @option{-gnatT} (@command{gcc})
4135 All compiler tables start at @var{nnn} times usual starting size.
4137 @item -gnatu
4138 @cindex @option{-gnatu} (@command{gcc})
4139 List units for this compilation.
4141 @item -gnatU
4142 @cindex @option{-gnatU} (@command{gcc})
4143 Tag all error messages with the unique string ``error:''
4145 @item -gnatv
4146 @cindex @option{-gnatv} (@command{gcc})
4147 Verbose mode. Full error output with source lines to @file{stdout}.
4149 @item -gnatV
4150 @cindex @option{-gnatV} (@command{gcc})
4151 Control level of validity checking (@pxref{Validity Checking}).
4153 @item -gnatw@var{xxx}
4154 @cindex @option{-gnatw} (@command{gcc})
4155 Warning mode where
4156 @var{xxx} is a string of option letters that denotes
4157 the exact warnings that
4158 are enabled or disabled (@pxref{Warning Message Control}).
4160 @item -gnatW@var{e}
4161 @cindex @option{-gnatW} (@command{gcc})
4162 Wide character encoding method
4163 (@var{e}=n/h/u/s/e/8).
4165 @item -gnatx
4166 @cindex @option{-gnatx} (@command{gcc})
4167 Suppress generation of cross-reference information.
4169 @item -gnatX
4170 @cindex @option{-gnatX} (@command{gcc})
4171 Enable GNAT implementation extensions and latest Ada version.
4173 @item -gnaty
4174 @cindex @option{-gnaty} (@command{gcc})
4175 Enable built-in style checks (@pxref{Style Checking}).
4177 @item -gnatz@var{m}
4178 @cindex @option{-gnatz} (@command{gcc})
4179 Distribution stub generation and compilation
4180 (@var{m}=r/c for receiver/caller stubs).
4182 @item -I@var{dir}
4183 @cindex @option{-I} (@command{gcc})
4184 @cindex RTL
4185 Direct GNAT to search the @var{dir} directory for source files needed by
4186 the current compilation
4187 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4189 @item -I-
4190 @cindex @option{-I-} (@command{gcc})
4191 @cindex RTL
4192 Except for the source file named in the command line, do not look for source
4193 files in the directory containing the source file named in the command line
4194 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4196 @item -mbig-switch
4197 @cindex @option{-mbig-switch} (@command{gcc})
4198 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4199 This standard gcc switch causes the compiler to use larger offsets in its
4200 jump table representation for @code{case} statements.
4201 This may result in less efficient code, but is sometimes necessary
4202 (for example on HP-UX targets)
4203 @cindex HP-UX and @option{-mbig-switch} option
4204 in order to compile large and/or nested @code{case} statements.
4206 @item -o @var{file}
4207 @cindex @option{-o} (@command{gcc})
4208 This switch is used in @command{gcc} to redirect the generated object file
4209 and its associated ALI file. Beware of this switch with GNAT, because it may
4210 cause the object file and ALI file to have different names which in turn
4211 may confuse the binder and the linker.
4213 @item -nostdinc
4214 @cindex @option{-nostdinc} (@command{gcc})
4215 Inhibit the search of the default location for the GNAT Run Time
4216 Library (RTL) source files.
4218 @item -nostdlib
4219 @cindex @option{-nostdlib} (@command{gcc})
4220 Inhibit the search of the default location for the GNAT Run Time
4221 Library (RTL) ALI files.
4223 @c @item -O@ovar{n}
4224 @c Expanding @ovar macro inline (explanation in macro def comments)
4225 @item -O@r{[}@var{n}@r{]}
4226 @cindex @option{-O} (@command{gcc})
4227 @var{n} controls the optimization level.
4229 @table @asis
4230 @item n = 0
4231 No optimization, the default setting if no @option{-O} appears
4233 @item n = 1
4234 Normal optimization, the default if you specify @option{-O} without
4235 an operand. A good compromise between code quality and compilation
4236 time.
4238 @item n = 2
4239 Extensive optimization, may improve execution time, possibly at the cost of
4240 substantially increased compilation time.
4242 @item n = 3
4243 Same as @option{-O2}, and also includes inline expansion for small subprograms
4244 in the same unit.
4246 @item n = s
4247 Optimize space usage
4248 @end table
4250 @noindent
4251 See also @ref{Optimization Levels}.
4254 @item -pass-exit-codes
4255 @cindex @option{-pass-exit-codes} (@command{gcc})
4256 Catch exit codes from the compiler and use the most meaningful as
4257 exit status.
4259 @item --RTS=@var{rts-path}
4260 @cindex @option{--RTS} (@command{gcc})
4261 Specifies the default location of the runtime library. Same meaning as the
4262 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4264 @item -S
4265 @cindex @option{-S} (@command{gcc})
4266 Used in place of @option{-c} to
4267 cause the assembler source file to be
4268 generated, using @file{.s} as the extension,
4269 instead of the object file.
4270 This may be useful if you need to examine the generated assembly code.
4272 @item -fverbose-asm
4273 @cindex @option{-fverbose-asm} (@command{gcc})
4274 Used in conjunction with @option{-S}
4275 to cause the generated assembly code file to be annotated with variable
4276 names, making it significantly easier to follow.
4278 @item -v
4279 @cindex @option{-v} (@command{gcc})
4280 Show commands generated by the @command{gcc} driver. Normally used only for
4281 debugging purposes or if you need to be sure what version of the
4282 compiler you are executing.
4284 @item -V @var{ver}
4285 @cindex @option{-V} (@command{gcc})
4286 Execute @var{ver} version of the compiler. This is the @command{gcc}
4287 version, not the GNAT version.
4289 @item -w
4290 @cindex @option{-w} (@command{gcc})
4291 Turn off warnings generated by the back end of the compiler. Use of
4292 this switch also causes the default for front end warnings to be set
4293 to suppress (as though @option{-gnatws} had appeared at the start of
4294 the options).
4296 @end table
4298 @c Combining qualifiers does not work on VMS
4299 You may combine a sequence of GNAT switches into a single switch. For
4300 example, the combined switch
4302 @cindex Combining GNAT switches
4303 @smallexample
4304 -gnatofi3
4305 @end smallexample
4307 @noindent
4308 is equivalent to specifying the following sequence of switches:
4310 @smallexample
4311 -gnato -gnatf -gnati3
4312 @end smallexample
4314 @noindent
4315 The following restrictions apply to the combination of switches
4316 in this manner:
4318 @itemize @bullet
4319 @item
4320 The switch @option{-gnatc} if combined with other switches must come
4321 first in the string.
4323 @item
4324 The switch @option{-gnats} if combined with other switches must come
4325 first in the string.
4327 @item
4328 The switches
4330 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4331 switches, and only one of them may appear in the command line.
4333 @item
4334 The switch @option{-gnat-p} may not be combined with any other switch.
4336 @item
4337 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4338 switch), then all further characters in the switch are interpreted
4339 as style modifiers (see description of @option{-gnaty}).
4341 @item
4342 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4343 switch), then all further characters in the switch are interpreted
4344 as debug flags (see description of @option{-gnatd}).
4346 @item
4347 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4348 switch), then all further characters in the switch are interpreted
4349 as warning mode modifiers (see description of @option{-gnatw}).
4351 @item
4352 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4353 switch), then all further characters in the switch are interpreted
4354 as validity checking options (@pxref{Validity Checking}).
4356 @item
4357 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4358 a combined list of options.
4359 @end itemize
4361 @node Output and Error Message Control
4362 @subsection Output and Error Message Control
4363 @findex stderr
4365 @noindent
4366 The standard default format for error messages is called ``brief format''.
4367 Brief format messages are written to @file{stderr} (the standard error
4368 file) and have the following form:
4370 @smallexample
4371 e.adb:3:04: Incorrect spelling of keyword "function"
4372 e.adb:4:20: ";" should be "is"
4373 @end smallexample
4375 @noindent
4376 The first integer after the file name is the line number in the file,
4377 and the second integer is the column number within the line.
4378 @code{GPS} can parse the error messages
4379 and point to the referenced character.
4380 The following switches provide control over the error message
4381 format:
4383 @table @option
4384 @c !sort!
4385 @item -gnatv
4386 @cindex @option{-gnatv} (@command{gcc})
4387 @findex stdout
4388 The v stands for verbose.
4389 The effect of this setting is to write long-format error
4390 messages to @file{stdout} (the standard output file.
4391 The same program compiled with the
4392 @option{-gnatv} switch would generate:
4394 @smallexample
4395 @cartouche
4396 3. funcion X (Q : Integer)
4397    |
4398 >>> Incorrect spelling of keyword "function"
4399 4. return Integer;
4400                  |
4401 >>> ";" should be "is"
4402 @end cartouche
4403 @end smallexample
4405 @noindent
4406 The vertical bar indicates the location of the error, and the @samp{>>>}
4407 prefix can be used to search for error messages. When this switch is
4408 used the only source lines output are those with errors.
4410 @item -gnatl
4411 @cindex @option{-gnatl} (@command{gcc})
4412 The @code{l} stands for list.
4413 This switch causes a full listing of
4414 the file to be generated. In the case where a body is
4415 compiled, the corresponding spec is also listed, along
4416 with any subunits. Typical output from compiling a package
4417 body @file{p.adb} might look like:
4419 @smallexample @c ada
4420 @cartouche
4421  Compiling: p.adb
4423      1. @b{package} @b{body} p @b{is}
4424      2.    @b{procedure} a;
4425      3.    @b{procedure} a @b{is} @b{separate};
4426      4. @b{begin}
4427      5.    @b{null}
4428                |
4429         >>> missing ";"
4431      6. @b{end};
4433 Compiling: p.ads
4435      1. @b{package} p @b{is}
4436      2.    @b{pragma} Elaborate_Body
4437                                 |
4438         >>> missing ";"
4440      3. @b{end} p;
4442 Compiling: p-a.adb
4444      1. @b{separate} p
4445                 |
4446         >>> missing "("
4448      2. @b{procedure} a @b{is}
4449      3. @b{begin}
4450      4.    @b{null}
4451                |
4452         >>> missing ";"
4454      5. @b{end};
4455 @end cartouche
4456 @end smallexample
4458 @noindent
4459 @findex stderr
4460 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4461 standard output is redirected, a brief summary is written to
4462 @file{stderr} (standard error) giving the number of error messages and
4463 warning messages generated.
4465 @item -gnatl=file
4466 @cindex @option{-gnatl=fname} (@command{gcc})
4467 This has the same effect as @option{-gnatl} except that the output is
4468 written to a file instead of to standard output. If the given name
4469 @file{fname} does not start with a period, then it is the full name
4470 of the file to be written. If @file{fname} is an extension, it is
4471 appended to the name of the file being compiled. For example, if
4472 file @file{xyz.adb} is compiled with @option{-gnatl=.lst},
4473 then the output is written to file xyz.adb.lst.
4475 @item -gnatU
4476 @cindex @option{-gnatU} (@command{gcc})
4477 This switch forces all error messages to be preceded by the unique
4478 string ``error:''. This means that error messages take a few more
4479 characters in space, but allows easy searching for and identification
4480 of error messages.
4482 @item -gnatb
4483 @cindex @option{-gnatb} (@command{gcc})
4484 The @code{b} stands for brief.
4485 This switch causes GNAT to generate the
4486 brief format error messages to @file{stderr} (the standard error
4487 file) as well as the verbose
4488 format message or full listing (which as usual is written to
4489 @file{stdout} (the standard output file).
4491 @item -gnatm=@var{n}
4492 @cindex @option{-gnatm} (@command{gcc})
4493 The @code{m} stands for maximum.
4494 @var{n} is a decimal integer in the
4495 range of 1 to 999999 and limits the number of error or warning
4496 messages to be generated. For example, using
4497 @option{-gnatm2} might yield
4499 @smallexample
4500 e.adb:3:04: Incorrect spelling of keyword "function"
4501 e.adb:5:35: missing ".."
4502 fatal error: maximum number of errors detected
4503 compilation abandoned
4504 @end smallexample
4506 @noindent
4507 The default setting if
4508 no switch is given is 9999. If the number of warnings reaches this
4509 limit, then a message is output and further warnings are suppressed,
4510 but the compilation is continued. If the number of error messages
4511 reaches this limit, then a message is output and the compilation
4512 is abandoned. A value of zero means that no limit applies.
4514 @noindent
4515 Note that the equal sign is optional, so the switches
4516 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4518 @item -gnatf
4519 @cindex @option{-gnatf} (@command{gcc})
4520 @cindex Error messages, suppressing
4521 The @code{f} stands for full.
4522 Normally, the compiler suppresses error messages that are likely to be
4523 redundant. This switch causes all error
4524 messages to be generated. In particular, in the case of
4525 references to undefined variables. If a given variable is referenced
4526 several times, the normal format of messages is
4527 @smallexample
4528 e.adb:7:07: "V" is undefined (more references follow)
4529 @end smallexample
4531 @noindent
4532 where the parenthetical comment warns that there are additional
4533 references to the variable @code{V}. Compiling the same program with the
4534 @option{-gnatf} switch yields
4536 @smallexample
4537 e.adb:7:07: "V" is undefined
4538 e.adb:8:07: "V" is undefined
4539 e.adb:8:12: "V" is undefined
4540 e.adb:8:16: "V" is undefined
4541 e.adb:9:07: "V" is undefined
4542 e.adb:9:12: "V" is undefined
4543 @end smallexample
4545 @noindent
4546 The @option{-gnatf} switch also generates additional information for
4547 some error messages.  Some examples are:
4549 @itemize @bullet
4550 @item
4551 Details on possibly non-portable unchecked conversion
4552 @item
4553 List possible interpretations for ambiguous calls
4554 @item
4555 Additional details on incorrect parameters
4556 @end itemize
4558 @item -gnatjnn
4559 @cindex @option{-gnatjnn} (@command{gcc})
4560 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4561 with continuation lines are treated as though the continuation lines were
4562 separate messages (and so a warning with two continuation lines counts as
4563 three warnings, and is listed as three separate messages).
4565 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4566 messages are output in a different manner. A message and all its continuation
4567 lines are treated as a unit, and count as only one warning or message in the
4568 statistics totals. Furthermore, the message is reformatted so that no line
4569 is longer than nn characters.
4571 @item -gnatq
4572 @cindex @option{-gnatq} (@command{gcc})
4573 The @code{q} stands for quit (really ``don't quit'').
4574 In normal operation mode, the compiler first parses the program and
4575 determines if there are any syntax errors. If there are, appropriate
4576 error messages are generated and compilation is immediately terminated.
4577 This switch tells
4578 GNAT to continue with semantic analysis even if syntax errors have been
4579 found. This may enable the detection of more errors in a single run. On
4580 the other hand, the semantic analyzer is more likely to encounter some
4581 internal fatal error when given a syntactically invalid tree.
4583 @item -gnatQ
4584 @cindex @option{-gnatQ} (@command{gcc})
4585 In normal operation mode, the @file{ALI} file is not generated if any
4586 illegalities are detected in the program. The use of @option{-gnatQ} forces
4587 generation of the @file{ALI} file. This file is marked as being in
4588 error, so it cannot be used for binding purposes, but it does contain
4589 reasonably complete cross-reference information, and thus may be useful
4590 for use by tools (e.g., semantic browsing tools or integrated development
4591 environments) that are driven from the @file{ALI} file. This switch
4592 implies @option{-gnatq}, since the semantic phase must be run to get a
4593 meaningful ALI file.
4595 In addition, if @option{-gnatt} is also specified, then the tree file is
4596 generated even if there are illegalities. It may be useful in this case
4597 to also specify @option{-gnatq} to ensure that full semantic processing
4598 occurs. The resulting tree file can be processed by ASIS, for the purpose
4599 of providing partial information about illegal units, but if the error
4600 causes the tree to be badly malformed, then ASIS may crash during the
4601 analysis.
4603 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4604 being in error, @command{gnatmake} will attempt to recompile the source when it
4605 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4607 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4608 since ALI files are never generated if @option{-gnats} is set.
4610 @end table
4612 @node Warning Message Control
4613 @subsection Warning Message Control
4614 @cindex Warning messages
4615 @noindent
4616 In addition to error messages, which correspond to illegalities as defined
4617 in the Ada Reference Manual, the compiler detects two kinds of warning
4618 situations.
4620 First, the compiler considers some constructs suspicious and generates a
4621 warning message to alert you to a possible error. Second, if the
4622 compiler detects a situation that is sure to raise an exception at
4623 run time, it generates a warning message. The following shows an example
4624 of warning messages:
4625 @smallexample
4626 e.adb:4:24: warning: creation of object may raise Storage_Error
4627 e.adb:10:17: warning: static value out of range
4628 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4629 @end smallexample
4631 @noindent
4632 GNAT considers a large number of situations as appropriate
4633 for the generation of warning messages. As always, warnings are not
4634 definite indications of errors. For example, if you do an out-of-range
4635 assignment with the deliberate intention of raising a
4636 @code{Constraint_Error} exception, then the warning that may be
4637 issued does not indicate an error. Some of the situations for which GNAT
4638 issues warnings (at least some of the time) are given in the following
4639 list. This list is not complete, and new warnings are often added to
4640 subsequent versions of GNAT. The list is intended to give a general idea
4641 of the kinds of warnings that are generated.
4643 @itemize @bullet
4644 @item
4645 Possible infinitely recursive calls
4647 @item
4648 Out-of-range values being assigned
4650 @item
4651 Possible order of elaboration problems
4653 @item
4654 Size not a multiple of alignment for a record type
4656 @item
4657 Assertions (pragma Assert) that are sure to fail
4659 @item
4660 Unreachable code
4662 @item
4663 Address clauses with possibly unaligned values, or where an attempt is
4664 made to overlay a smaller variable with a larger one.
4666 @item
4667 Fixed-point type declarations with a null range
4669 @item
4670 Direct_IO or Sequential_IO instantiated with a type that has access values
4672 @item
4673 Variables that are never assigned a value
4675 @item
4676 Variables that are referenced before being initialized
4678 @item
4679 Task entries with no corresponding @code{accept} statement
4681 @item
4682 Duplicate accepts for the same task entry in a @code{select}
4684 @item
4685 Objects that take too much storage
4687 @item
4688 Unchecked conversion between types of differing sizes
4690 @item
4691 Missing @code{return} statement along some execution path in a function
4693 @item
4694 Incorrect (unrecognized) pragmas
4696 @item
4697 Incorrect external names
4699 @item
4700 Allocation from empty storage pool
4702 @item
4703 Potentially blocking operation in protected type
4705 @item
4706 Suspicious parenthesization of expressions
4708 @item
4709 Mismatching bounds in an aggregate
4711 @item
4712 Attempt to return local value by reference
4714 @item
4715 Premature instantiation of a generic body
4717 @item
4718 Attempt to pack aliased components
4720 @item
4721 Out of bounds array subscripts
4723 @item
4724 Wrong length on string assignment
4726 @item
4727 Violations of style rules if style checking is enabled
4729 @item
4730 Unused @code{with} clauses
4732 @item
4733 @code{Bit_Order} usage that does not have any effect
4735 @item
4736 @code{Standard.Duration} used to resolve universal fixed expression
4738 @item
4739 Dereference of possibly null value
4741 @item
4742 Declaration that is likely to cause storage error
4744 @item
4745 Internal GNAT unit @code{with}'ed by application unit
4747 @item
4748 Values known to be out of range at compile time
4750 @item
4751 Unreferenced or unmodified variables. Note that a special
4752 exemption applies to variables which contain any of the substrings
4753 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
4754 are considered likely to be intentionally used in a situation where
4755 otherwise a warning would be given, so warnings of this kind are
4756 always suppressed for such variables.
4758 @item
4759 Address overlays that could clobber memory
4761 @item
4762 Unexpected initialization when address clause present
4764 @item
4765 Bad alignment for address clause
4767 @item
4768 Useless type conversions
4770 @item
4771 Redundant assignment statements and other redundant constructs
4773 @item
4774 Useless exception handlers
4776 @item
4777 Accidental hiding of name by child unit
4779 @item
4780 Access before elaboration detected at compile time
4782 @item
4783 A range in a @code{for} loop that is known to be null or might be null
4785 @end itemize
4787 @noindent
4788 The following section lists compiler switches that are available
4789 to control the handling of warning messages. It is also possible
4790 to exercise much finer control over what warnings are issued and
4791 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4792 gnat_rm, GNAT Reference manual}.
4794 @table @option
4795 @c !sort!
4796 @item -gnatwa
4797 @emph{Activate most optional warnings.}
4798 @cindex @option{-gnatwa} (@command{gcc})
4799 This switch activates most optional warning messages.  See the remaining list
4800 in this section for details on optional warning messages that can be
4801 individually controlled.  The warnings that are not turned on by this
4802 switch are:
4804 @itemize
4805 @option{-gnatwd} (implicit dereferencing)
4806 @option{-gnatw.d} (tag warnings with -gnatw switch)
4807 @option{-gnatwh} (hiding)
4808 @option{-gnatw.h} (holes in record layouts)
4809 @option{-gnatw.k} (redefinition of names in standard)
4810 @option{-gnatwl} (elaboration warnings)
4811 @option{-gnatw.l} (inherited aspects)
4812 @option{-gnatw.n} (atomic synchronization)
4813 @option{-gnatwo} (address clause overlay)
4814 @option{-gnatw.o} (values set by out parameters ignored)
4815 @option{-gnatw.s} (overridden size clause)
4816 @option{-gnatwt} (tracking of deleted conditional code)
4817 @option{-gnatw.u} (unordered enumeration)
4818 @option{-gnatw.w} (use of Warnings Off)
4819 @option{-gnatw.y} (reasons for package needing body)
4820 @end itemize
4822 All other optional warnings are turned on.
4824 @item -gnatwA
4825 @emph{Suppress all optional errors.}
4826 @cindex @option{-gnatwA} (@command{gcc})
4827 This switch suppresses all optional warning messages, see remaining list
4828 in this section for details on optional warning messages that can be
4829 individually controlled. Note that unlike switch @option{-gnatws}, the
4830 use of switch @option{-gnatwA} does not suppress warnings that are
4831 normally given unconditionally and cannot be individually controlled
4832 (for example, the warning about a missing exit path in a function).
4833 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4834 the use of switch @option{-gnatwA} can be individually turned back
4835 on. For example the use of switch @option{-gnatwA} followed by
4836 switch @option{-gnatwd} will suppress all optional warnings except
4837 the warnings for implicit dereferencing.
4839 @item -gnatw.a
4840 @emph{Activate warnings on failing assertions.}
4841 @cindex @option{-gnatw.a} (@command{gcc})
4842 @cindex Assert failures
4843 This switch activates warnings for assertions where the compiler can tell at
4844 compile time that the assertion will fail. Note that this warning is given
4845 even if assertions are disabled. The default is that such warnings are
4846 generated.
4848 @item -gnatw.A
4849 @emph{Suppress warnings on failing assertions.}
4850 @cindex @option{-gnatw.A} (@command{gcc})
4851 @cindex Assert failures
4852 This switch suppresses warnings for assertions where the compiler can tell at
4853 compile time that the assertion will fail.
4855 @item -gnatwb
4856 @emph{Activate warnings on bad fixed values.}
4857 @cindex @option{-gnatwb} (@command{gcc})
4858 @cindex Bad fixed values
4859 @cindex Fixed-point Small value
4860 @cindex Small value
4861 This switch activates warnings for static fixed-point expressions whose
4862 value is not an exact multiple of Small. Such values are implementation
4863 dependent, since an implementation is free to choose either of the multiples
4864 that surround the value. GNAT always chooses the closer one, but this is not
4865 required behavior, and it is better to specify a value that is an exact
4866 multiple, ensuring predictable execution. The default is that such warnings
4867 are not generated.
4869 @item -gnatwB
4870 @emph{Suppress warnings on bad fixed values.}
4871 @cindex @option{-gnatwB} (@command{gcc})
4872 This switch suppresses warnings for static fixed-point expressions whose
4873 value is not an exact multiple of Small.
4875 @item -gnatw.b
4876 @emph{Activate warnings on biased representation.}
4877 @cindex @option{-gnatw.b} (@command{gcc})
4878 @cindex Biased representation
4879 This switch activates warnings when a size clause, value size clause, component
4880 clause, or component size clause forces the use of biased representation for an
4881 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4882 to represent 10/11). The default is that such warnings are generated.
4884 @item -gnatw.B
4885 @emph{Suppress warnings on biased representation.}
4886 @cindex @option{-gnatwB} (@command{gcc})
4887 This switch suppresses warnings for representation clauses that force the use
4888 of biased representation.
4890 @item -gnatwc
4891 @emph{Activate warnings on conditionals.}
4892 @cindex @option{-gnatwc} (@command{gcc})
4893 @cindex Conditionals, constant
4894 This switch activates warnings for conditional expressions used in
4895 tests that are known to be True or False at compile time. The default
4896 is that such warnings are not generated.
4897 Note that this warning does
4898 not get issued for the use of boolean variables or constants whose
4899 values are known at compile time, since this is a standard technique
4900 for conditional compilation in Ada, and this would generate too many
4901 false positive warnings.
4903 This warning option also activates a special test for comparisons using
4904 the operators ``>='' and`` <=''.
4905 If the compiler can tell that only the equality condition is possible,
4906 then it will warn that the ``>'' or ``<'' part of the test
4907 is useless and that the operator could be replaced by ``=''.
4908 An example would be comparing a @code{Natural} variable <= 0.
4910 This warning option also generates warnings if
4911 one or both tests is optimized away in a membership test for integer
4912 values if the result can be determined at compile time. Range tests on
4913 enumeration types are not included, since it is common for such tests
4914 to include an end point.
4916 This warning can also be turned on using @option{-gnatwa}.
4918 @item -gnatwC
4919 @emph{Suppress warnings on conditionals.}
4920 @cindex @option{-gnatwC} (@command{gcc})
4921 This switch suppresses warnings for conditional expressions used in
4922 tests that are known to be True or False at compile time.
4924 @item -gnatw.c
4925 @emph{Activate warnings on missing component clauses.}
4926 @cindex @option{-gnatw.c} (@command{gcc})
4927 @cindex Component clause, missing
4928 This switch activates warnings for record components where a record
4929 representation clause is present and has component clauses for the
4930 majority, but not all, of the components. A warning is given for each
4931 component for which no component clause is present.
4933 @item -gnatw.C
4934 @emph{Suppress warnings on missing component clauses.}
4935 @cindex @option{-gnatwC} (@command{gcc})
4936 This switch suppresses warnings for record components that are
4937 missing a component clause in the situation described above.
4939 @item -gnatwd
4940 @emph{Activate warnings on implicit dereferencing.}
4941 @cindex @option{-gnatwd} (@command{gcc})
4942 If this switch is set, then the use of a prefix of an access type
4943 in an indexed component, slice, or selected component without an
4944 explicit @code{.all} will generate a warning. With this warning
4945 enabled, access checks occur only at points where an explicit
4946 @code{.all} appears in the source code (assuming no warnings are
4947 generated as a result of this switch). The default is that such
4948 warnings are not generated.
4950 @item -gnatwD
4951 @emph{Suppress warnings on implicit dereferencing.}
4952 @cindex @option{-gnatwD} (@command{gcc})
4953 @cindex Implicit dereferencing
4954 @cindex Dereferencing, implicit
4955 This switch suppresses warnings for implicit dereferences in
4956 indexed components, slices, and selected components.
4958 @item -gnatw.d
4959 @emph{Activate tagging of warning and info messages.}
4960 @cindex @option{-gnatw.d} (@command{gcc})
4961 If this switch is set, then warning messages are tagged, with one of the
4962 following strings:
4964 @table @option
4966 @item [-gnatw?]
4967 Used to tag warnings controlled by the switch @option{-gnatwx} where x
4968 is a letter a-z.
4970 @item [-gnatw.?]
4971 Used to tag warnings controlled by the switch @option{-gnatw.x} where x
4972 is a letter a-z.
4974 @item [-gnatel]
4975 Used to tag elaboration information (info) messages generated when the
4976 static model of elaboration is used and the @option{-gnatel} switch is set.
4978 @item [restriction warning]
4979 Used to tag warning messages for restriction violations, activated by use
4980 of the pragma @option{Restriction_Warnings}.
4982 @item [warning-as-error]
4983 Used to tag warning messages that have been converted to error messages by
4984 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
4985 the string "error: " rather than "warning: ".
4987 @item [enabled by default]
4988 Used to tag all other warnings that are always given by default, unless
4989 warnings are completely suppressed using pragma @option{Warnings(Off)} or
4990 the switch @option{-gnatws}.
4992 @end table
4994 @item -gnatw.D
4995 @emph{Deactivate tagging of warning and info messages messages.}
4996 @cindex @option{-gnatw.d} (@command{gcc})
4997 If this switch is set, then warning messages return to the default
4998 mode in which warnings and info messages are not tagged as described above for
4999 @code{-gnatw.d}.
5001 @item -gnatwe
5002 @emph{Treat warnings and style checks as errors.}
5003 @cindex @option{-gnatwe} (@command{gcc})
5004 @cindex Warnings, treat as error
5005 This switch causes warning messages and style check messages to be
5006 treated as errors.
5007 The warning string still appears, but the warning messages are counted
5008 as errors, and prevent the generation of an object file. Note that this
5009 is the only -gnatw switch that affects the handling of style check messages.
5010 Note also that this switch has no effect on info (information) messages, which
5011 are not treated as errors if this switch is present.
5013 @item -gnatw.e
5014 @emph{Activate every optional warning}
5015 @cindex @option{-gnatw.e} (@command{gcc})
5016 @cindex Warnings, activate every optional warning
5017 This switch activates all optional warnings, including those which
5018 are not activated by @code{-gnatwa}. The use of this switch is not
5019 recommended for normal use. If you turn this switch on, it is almost
5020 certain that you will get large numbers of useless warnings. The
5021 warnings that are excluded from @code{-gnatwa} are typically highly
5022 specialized warnings that are suitable for use only in code that has
5023 been specifically designed according to specialized coding rules.
5025 @item -gnatwf
5026 @emph{Activate warnings on unreferenced formals.}
5027 @cindex @option{-gnatwf} (@command{gcc})
5028 @cindex Formals, unreferenced
5029 This switch causes a warning to be generated if a formal parameter
5030 is not referenced in the body of the subprogram. This warning can
5031 also be turned on using @option{-gnatwu}. The
5032 default is that these warnings are not generated.
5034 @item -gnatwF
5035 @emph{Suppress warnings on unreferenced formals.}
5036 @cindex @option{-gnatwF} (@command{gcc})
5037 This switch suppresses warnings for unreferenced formal
5038 parameters. Note that the
5039 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5040 effect of warning on unreferenced entities other than subprogram
5041 formals.
5043 @item -gnatwg
5044 @emph{Activate warnings on unrecognized pragmas.}
5045 @cindex @option{-gnatwg} (@command{gcc})
5046 @cindex Pragmas, unrecognized
5047 This switch causes a warning to be generated if an unrecognized
5048 pragma is encountered. Apart from issuing this warning, the
5049 pragma is ignored and has no effect. The default
5050 is that such warnings are issued (satisfying the Ada Reference
5051 Manual requirement that such warnings appear).
5053 @item -gnatwG
5054 @emph{Suppress warnings on unrecognized pragmas.}
5055 @cindex @option{-gnatwG} (@command{gcc})
5056 This switch suppresses warnings for unrecognized pragmas.
5058 @item -gnatw.g
5059 @emph{Warnings used for GNAT sources}
5060 @cindex @option{-gnatw.g} (@command{gcc})
5061 This switch sets the warning categories that are used by the standard
5062 GNAT style. Currently this is equivalent to
5063 @option{-gnatwAao.sI.C.V.X}
5064 but more warnings may be added in the future without advanced notice.
5066 @item -gnatwh
5067 @emph{Activate warnings on hiding.}
5068 @cindex @option{-gnatwh} (@command{gcc})
5069 @cindex Hiding of Declarations
5070 This switch activates warnings on hiding declarations.
5071 A declaration is considered hiding
5072 if it is for a non-overloadable entity, and it declares an entity with the
5073 same name as some other entity that is directly or use-visible. The default
5074 is that such warnings are not generated.
5076 @item -gnatwH
5077 @emph{Suppress warnings on hiding.}
5078 @cindex @option{-gnatwH} (@command{gcc})
5079 This switch suppresses warnings on hiding declarations.
5081 @item -gnatw.h
5082 @emph{Activate warnings on holes/gaps in records.}
5083 @cindex @option{-gnatw.h} (@command{gcc})
5084 @cindex Record Representation (gaps)
5085 This switch activates warnings on component clauses in record
5086 representation clauses that leave holes (gaps) in the record layout.
5087 If this warning option is active, then record representation clauses
5088 should specify a contiguous layout, adding unused fill fields if needed.
5090 @item -gnatw.H
5091 @emph{Suppress warnings on holes/gaps in records.}
5092 @cindex @option{-gnatw.H} (@command{gcc})
5093 This switch suppresses warnings on component clauses in record
5094 representation clauses that leave holes (haps) in the record layout.
5096 @item -gnatwi
5097 @emph{Activate warnings on implementation units.}
5098 @cindex @option{-gnatwi} (@command{gcc})
5099 This switch activates warnings for a @code{with} of an internal GNAT
5100 implementation unit, defined as any unit from the @code{Ada},
5101 @code{Interfaces}, @code{GNAT},
5102  or @code{System}
5103 hierarchies that is not
5104 documented in either the Ada Reference Manual or the GNAT
5105 Programmer's Reference Manual. Such units are intended only
5106 for internal implementation purposes and should not be @code{with}'ed
5107 by user programs. The default is that such warnings are generated
5109 @item -gnatwI
5110 @emph{Disable warnings on implementation units.}
5111 @cindex @option{-gnatwI} (@command{gcc})
5112 This switch disables warnings for a @code{with} of an internal GNAT
5113 implementation unit.
5115 @item -gnatw.i
5116 @emph{Activate warnings on overlapping actuals.}
5117 @cindex @option{-gnatw.i} (@command{gcc})
5118 This switch enables a warning on statically detectable overlapping actuals in
5119 a subprogram call, when one of the actuals is an in-out parameter, and the
5120 types of the actuals are not by-copy types. This warning is off by default.
5122 @item -gnatw.I
5123 @emph{Disable warnings on overlapping actuals.}
5124 @cindex @option{-gnatw.I} (@command{gcc})
5125 This switch disables warnings on overlapping actuals in a call..
5127 @item -gnatwj
5128 @emph{Activate warnings on obsolescent features (Annex J).}
5129 @cindex @option{-gnatwj} (@command{gcc})
5130 @cindex Features, obsolescent
5131 @cindex Obsolescent features
5132 If this warning option is activated, then warnings are generated for
5133 calls to subprograms marked with @code{pragma Obsolescent} and
5134 for use of features in Annex J of the Ada Reference Manual. In the
5135 case of Annex J, not all features are flagged. In particular use
5136 of the renamed packages (like @code{Text_IO}) and use of package
5137 @code{ASCII} are not flagged, since these are very common and
5138 would generate many annoying positive warnings. The default is that
5139 such warnings are not generated.
5141 In addition to the above cases, warnings are also generated for
5142 GNAT features that have been provided in past versions but which
5143 have been superseded (typically by features in the new Ada standard).
5144 For example, @code{pragma Ravenscar} will be flagged since its
5145 function is replaced by @code{pragma Profile(Ravenscar)}, and
5146 @code{pragma Interface_Name} will be flagged since its function
5147 is replaced by @code{pragma Import}.
5149 Note that this warning option functions differently from the
5150 restriction @code{No_Obsolescent_Features} in two respects.
5151 First, the restriction applies only to annex J features.
5152 Second, the restriction does flag uses of package @code{ASCII}.
5154 @item -gnatwJ
5155 @emph{Suppress warnings on obsolescent features (Annex J).}
5156 @cindex @option{-gnatwJ} (@command{gcc})
5157 This switch disables warnings on use of obsolescent features.
5159 @item -gnatwk
5160 @emph{Activate warnings on variables that could be constants.}
5161 @cindex @option{-gnatwk} (@command{gcc})
5162 This switch activates warnings for variables that are initialized but
5163 never modified, and then could be declared constants. The default is that
5164 such warnings are not given.
5166 @item -gnatwK
5167 @emph{Suppress warnings on variables that could be constants.}
5168 @cindex @option{-gnatwK} (@command{gcc})
5169 This switch disables warnings on variables that could be declared constants.
5171 @item -gnatw.k
5172 @emph{Activate warnings on redefinition of names in standard.}
5173 @cindex @option{-gnatw.k} (@command{gcc})
5174 This switch activates warnings for declarations that declare a name that
5175 is defined in package Standard. Such declarations can be confusing,
5176 especially since the names in package Standard continue to be directly
5177 visible, meaning that use visibiliy on such redeclared names does not
5178 work as expected. Names of discriminants and components in records are
5179 not included in this check.
5181 @item -gnatw.K
5182 @emph{Suppress warnings on redefinition of names in standard.}
5183 @cindex @option{-gnatwK} (@command{gcc})
5184 This switch activates warnings for declarations that declare a name that
5185 is defined in package Standard.
5187 @item -gnatwl
5188 @emph{Activate warnings for elaboration pragmas.}
5189 @cindex @option{-gnatwl} (@command{gcc})
5190 @cindex Elaboration, warnings
5191 This switch activates warnings for possible elaboration problems,
5192 including suspicious use
5193 of @code{Elaborate} pragmas, when using the static elaboration model, and
5194 possible situations that may raise @code{Program_Error} when using the
5195 dynamic elaboration model.
5196 See the section in this guide on elaboration checking for further details.
5197 The default is that such warnings
5198 are not generated.
5200 @item -gnatwL
5201 @emph{Suppress warnings for elaboration pragmas.}
5202 @cindex @option{-gnatwL} (@command{gcc})
5203 This switch suppresses warnings for possible elaboration problems.
5205 @item -gnatw.l
5206 @emph{List inherited aspects.}
5207 @cindex @option{-gnatw.l} (@command{gcc})
5208 This switch causes the compiler to list inherited invariants,
5209 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5210 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5212 @item -gnatw.L
5213 @emph{Suppress listing of inherited aspects.}
5214 @cindex @option{-gnatw.L} (@command{gcc})
5215 This switch suppresses listing of inherited aspects.
5217 @item -gnatwm
5218 @emph{Activate warnings on modified but unreferenced variables.}
5219 @cindex @option{-gnatwm} (@command{gcc})
5220 This switch activates warnings for variables that are assigned (using
5221 an initialization value or with one or more assignment statements) but
5222 whose value is never read. The warning is suppressed for volatile
5223 variables and also for variables that are renamings of other variables
5224 or for which an address clause is given.
5225 The default is that these warnings are not given.
5227 @item -gnatwM
5228 @emph{Disable warnings on modified but unreferenced variables.}
5229 @cindex @option{-gnatwM} (@command{gcc})
5230 This switch disables warnings for variables that are assigned or
5231 initialized, but never read.
5233 @item -gnatw.m
5234 @emph{Activate warnings on suspicious modulus values.}
5235 @cindex @option{-gnatw.m} (@command{gcc})
5236 This switch activates warnings for modulus values that seem suspicious.
5237 The cases caught are where the size is the same as the modulus (e.g.
5238 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5239 with no size clause. The guess in both cases is that 2**x was intended
5240 rather than x. In addition expressions of the form 2*x for small x
5241 generate a warning (the almost certainly accurate guess being that
5242 2**x was intended). The default is that these warnings are given.
5244 @item -gnatw.M
5245 @emph{Disable warnings on suspicious modulus values.}
5246 @cindex @option{-gnatw.M} (@command{gcc})
5247 This switch disables warnings for suspicious modulus values.
5249 @item -gnatwn
5250 @emph{Set normal warnings mode.}
5251 @cindex @option{-gnatwn} (@command{gcc})
5252 This switch sets normal warning mode, in which enabled warnings are
5253 issued and treated as warnings rather than errors. This is the default
5254 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5255 an explicit @option{-gnatws} or
5256 @option{-gnatwe}. It also cancels the effect of the
5257 implicit @option{-gnatwe} that is activated by the
5258 use of @option{-gnatg}.
5260 @item -gnatw.n
5261 @emph{Activate warnings on atomic synchronization.}
5262 @cindex @option{-gnatw.n} (@command{gcc})
5263 @cindex Atomic Synchronization, warnings
5264 This switch actives warnings when an access to an atomic variable
5265 requires the generation of atomic synchronization code. These
5266 warnings are off by default.
5267 @item -gnatw.N
5268 @emph{Suppress warnings on atomic synchronization.}
5269 @cindex @option{-gnatw.n} (@command{gcc})
5270 @cindex Atomic Synchronization, warnings
5271 This switch suppresses warnings when an access to an atomic variable
5272 requires the generation of atomic synchronization code.
5274 @item -gnatwo
5275 @emph{Activate warnings on address clause overlays.}
5276 @cindex @option{-gnatwo} (@command{gcc})
5277 @cindex Address Clauses, warnings
5278 This switch activates warnings for possibly unintended initialization
5279 effects of defining address clauses that cause one variable to overlap
5280 another. The default is that such warnings are generated.
5282 @item -gnatwO
5283 @emph{Suppress warnings on address clause overlays.}
5284 @cindex @option{-gnatwO} (@command{gcc})
5285 This switch suppresses warnings on possibly unintended initialization
5286 effects of defining address clauses that cause one variable to overlap
5287 another.
5289 @item -gnatw.o
5290 @emph{Activate warnings on modified but unreferenced out parameters.}
5291 @cindex @option{-gnatw.o} (@command{gcc})
5292 This switch activates warnings for variables that are modified by using
5293 them as actuals for a call to a procedure with an out mode formal, where
5294 the resulting assigned value is never read. It is applicable in the case
5295 where there is more than one out mode formal. If there is only one out
5296 mode formal, the warning is issued by default (controlled by -gnatwu).
5297 The warning is suppressed for volatile
5298 variables and also for variables that are renamings of other variables
5299 or for which an address clause is given.
5300 The default is that these warnings are not given.
5302 @item -gnatw.O
5303 @emph{Disable warnings on modified but unreferenced out parameters.}
5304 @cindex @option{-gnatw.O} (@command{gcc})
5305 This switch suppresses warnings for variables that are modified by using
5306 them as actuals for a call to a procedure with an out mode formal, where
5307 the resulting assigned value is never read.
5309 @item -gnatwp
5310 @emph{Activate warnings on ineffective pragma Inlines.}
5311 @cindex @option{-gnatwp} (@command{gcc})
5312 @cindex Inlining, warnings
5313 This switch activates warnings for failure of front end inlining
5314 (activated by @option{-gnatN}) to inline a particular call. There are
5315 many reasons for not being able to inline a call, including most
5316 commonly that the call is too complex to inline. The default is
5317 that such warnings are not given.
5318 Warnings on ineffective inlining by the gcc back-end can be activated
5319 separately, using the gcc switch -Winline.
5321 @item -gnatwP
5322 @emph{Suppress warnings on ineffective pragma Inlines.}
5323 @cindex @option{-gnatwP} (@command{gcc})
5324 This switch suppresses warnings on ineffective pragma Inlines. If the
5325 inlining mechanism cannot inline a call, it will simply ignore the
5326 request silently.
5328 @item -gnatw.p
5329 @emph{Activate warnings on parameter ordering.}
5330 @cindex @option{-gnatw.p} (@command{gcc})
5331 @cindex Parameter order, warnings
5332 This switch activates warnings for cases of suspicious parameter
5333 ordering when the list of arguments are all simple identifiers that
5334 match the names of the formals, but are in a different order. The
5335 warning is suppressed if any use of named parameter notation is used,
5336 so this is the appropriate way to suppress a false positive (and
5337 serves to emphasize that the "misordering" is deliberate). The
5338 default is that such warnings are not given.
5340 @item -gnatw.P
5341 @emph{Suppress warnings on parameter ordering.}
5342 @cindex @option{-gnatw.P} (@command{gcc})
5343 This switch suppresses warnings on cases of suspicious parameter
5344 ordering.
5346 @item -gnatwq
5347 @emph{Activate warnings on questionable missing parentheses.}
5348 @cindex @option{-gnatwq} (@command{gcc})
5349 @cindex Parentheses, warnings
5350 This switch activates warnings for cases where parentheses are not used and
5351 the result is potential ambiguity from a readers point of view. For example
5352 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5353 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5354 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5355 follow the rule of always parenthesizing to make the association clear, and
5356 this warning switch warns if such parentheses are not present. The default
5357 is that these warnings are given.
5359 @item -gnatwQ
5360 @emph{Suppress warnings on questionable missing parentheses.}
5361 @cindex @option{-gnatwQ} (@command{gcc})
5362 This switch suppresses warnings for cases where the association is not
5363 clear and the use of parentheses is preferred.
5365 @item -gnatwr
5366 @emph{Activate warnings on redundant constructs.}
5367 @cindex @option{-gnatwr} (@command{gcc})
5368 This switch activates warnings for redundant constructs. The following
5369 is the current list of constructs regarded as redundant:
5371 @itemize @bullet
5372 @item
5373 Assignment of an item to itself.
5374 @item
5375 Type conversion that converts an expression to its own type.
5376 @item
5377 Use of the attribute @code{Base} where @code{typ'Base} is the same
5378 as @code{typ}.
5379 @item
5380 Use of pragma @code{Pack} when all components are placed by a record
5381 representation clause.
5382 @item
5383 Exception handler containing only a reraise statement (raise with no
5384 operand) which has no effect.
5385 @item
5386 Use of the operator abs on an operand that is known at compile time
5387 to be non-negative
5388 @item
5389 Comparison of boolean expressions to an explicit True value.
5390 @end itemize
5392 The default is that warnings for redundant constructs are not given.
5394 @item -gnatwR
5395 @emph{Suppress warnings on redundant constructs.}
5396 @cindex @option{-gnatwR} (@command{gcc})
5397 This switch suppresses warnings for redundant constructs.
5399 @item -gnatw.r
5400 @emph{Activate warnings for object renaming function.}
5401 @cindex @option{-gnatw.r} (@command{gcc})
5402 This switch activates warnings for an object renaming that renames a
5403 function call, which is equivalent to a constant declaration (as
5404 opposed to renaming the function itself).  The default is that these
5405 warnings are given.
5407 @item -gnatw.R
5408 @emph{Suppress warnings for object renaming function.}
5409 @cindex @option{-gnatwT} (@command{gcc})
5410 This switch suppresses warnings for object renaming function.
5412 @item -gnatws
5413 @emph{Suppress all warnings.}
5414 @cindex @option{-gnatws} (@command{gcc})
5415 This switch completely suppresses the
5416 output of all warning messages from the GNAT front end, including
5417 both warnings that can be controlled by switches described in this
5418 section, and those that are normally given unconditionally. The
5419 effect of this suppress action can only be cancelled by a subsequent
5420 use of the switch @option{-gnatwn}.
5422 Note that switch @option{-gnatws} does not suppress
5423 warnings from the @command{gcc} back end.
5424 To suppress these back end warnings as well, use the switch @option{-w}
5425 in addition to @option{-gnatws}. Also this switch has no effect on the
5426 handling of style check messages.
5428 @item -gnatw.s
5429 @emph{Activate warnings on overridden size clauses.}
5430 @cindex @option{-gnatw.s} (@command{gcc})
5431 @cindex Record Representation (component sizes)
5432 This switch activates warnings on component clauses in record
5433 representation clauses where the length given overrides that
5434 specified by an explicit size clause for the component type. A
5435 warning is similarly given in the array case if a specified
5436 component size overrides an explicit size clause for the array
5437 component type.
5439 @item -gnatw.S
5440 @emph{Suppress warnings on overridden size clauses.}
5441 @cindex @option{-gnatw.S} (@command{gcc})
5442 This switch suppresses warnings on component clauses in record
5443 representation clauses that override size clauses, and similar
5444 warnings when an array component size overrides a size clause.
5446 @item -gnatwt
5447 @emph{Activate warnings for tracking of deleted conditional code.}
5448 @cindex @option{-gnatwt} (@command{gcc})
5449 @cindex Deactivated code, warnings
5450 @cindex Deleted code, warnings
5451 This switch activates warnings for tracking of code in conditionals (IF and
5452 CASE statements) that is detected to be dead code which cannot be executed, and
5453 which is removed by the front end. This warning is off by default. This may be
5454 useful for detecting deactivated code in certified applications.
5456 @item -gnatwT
5457 @emph{Suppress warnings for tracking of deleted conditional code.}
5458 @cindex @option{-gnatwT} (@command{gcc})
5459 This switch suppresses warnings for tracking of deleted conditional code.
5461 @item -gnatw.t
5462 @emph{Activate warnings on suspicious contracts.}
5463 @cindex @option{-gnatw.t} (@command{gcc})
5464 This switch activates warnings on suspicious postconditions (whether a
5465 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5466 and suspicious contract cases (pragma @code{Contract_Cases}). A
5467 function postcondition or contract case is suspicious when no postcondition
5468 or contract case for this function mentions the result of the function.
5469 A procedure postcondition or contract case is suspicious when it only
5470 refers to the pre-state of the procedure, because in that case it should
5471 rather be expressed as a precondition. The default is that such warnings
5472 are not generated.
5474 @item -gnatw.T
5475 @emph{Suppress warnings on suspicious contracts.}
5476 @cindex @option{-gnatw.T} (@command{gcc})
5477 This switch suppresses warnings on suspicious postconditions.
5479 @item -gnatwu
5480 @emph{Activate warnings on unused entities.}
5481 @cindex @option{-gnatwu} (@command{gcc})
5482 This switch activates warnings to be generated for entities that
5483 are declared but not referenced, and for units that are @code{with}'ed
5484 and not
5485 referenced. In the case of packages, a warning is also generated if
5486 no entities in the package are referenced. This means that if a with'ed
5487 package is referenced but the only references are in @code{use}
5488 clauses or @code{renames}
5489 declarations, a warning is still generated. A warning is also generated
5490 for a generic package that is @code{with}'ed but never instantiated.
5491 In the case where a package or subprogram body is compiled, and there
5492 is a @code{with} on the corresponding spec
5493 that is only referenced in the body,
5494 a warning is also generated, noting that the
5495 @code{with} can be moved to the body. The default is that
5496 such warnings are not generated.
5497 This switch also activates warnings on unreferenced formals
5498 (it includes the effect of @option{-gnatwf}).
5500 @item -gnatwU
5501 @emph{Suppress warnings on unused entities.}
5502 @cindex @option{-gnatwU} (@command{gcc})
5503 This switch suppresses warnings for unused entities and packages.
5504 It also turns off warnings on unreferenced formals (and thus includes
5505 the effect of @option{-gnatwF}).
5507 @item -gnatw.u
5508 @emph{Activate warnings on unordered enumeration types.}
5509 @cindex @option{-gnatw.u} (@command{gcc})
5510 This switch causes enumeration types to be considered as conceptually
5511 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5512 The effect is to generate warnings in clients that use explicit comparisons
5513 or subranges, since these constructs both treat objects of the type as
5514 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5515 which the type is declared, or its body or subunits.) Please refer to
5516 the description of pragma @code{Ordered} in the
5517 @cite{@value{EDITION} Reference Manual} for further details.
5518 The default is that such warnings are not generated.
5520 @item -gnatw.U
5521 @emph{Deactivate warnings on unordered enumeration types.}
5522 @cindex @option{-gnatw.U} (@command{gcc})
5523 This switch causes all enumeration types to be considered as ordered, so
5524 that no warnings are given for comparisons or subranges for any type.
5526 @item -gnatwv
5527 @emph{Activate warnings on unassigned variables.}
5528 @cindex @option{-gnatwv} (@command{gcc})
5529 @cindex Unassigned variable warnings
5530 This switch activates warnings for access to variables which
5531 may not be properly initialized. The default is that
5532 such warnings are generated.
5534 @item -gnatwV
5535 @emph{Suppress warnings on unassigned variables.}
5536 @cindex @option{-gnatwV} (@command{gcc})
5537 This switch suppresses warnings for access to variables which
5538 may not be properly initialized.
5539 For variables of a composite type, the warning can also be suppressed in
5540 Ada 2005 by using a default initialization with a box. For example, if
5541 Table is an array of records whose components are only partially uninitialized,
5542 then the following code:
5544 @smallexample @c ada
5545    Tab : Table := (@b{others} => <>);
5546 @end smallexample
5548 will suppress warnings on subsequent statements that access components
5549 of variable Tab.
5551 @item -gnatw.v
5552 @emph{Activate info messages for non-default bit order.}
5553 @cindex @option{-gnatw.v} (@command{gcc})
5554 @cindex bit order warnings
5555 This switch activates messages (labeled "info", they are not warnings,
5556 just informational messages) about the effects of non-default bit-order
5557 on records to which a component clause is applied. The effect of specifying
5558 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5559 these messages, which are given by default, are useful in understanding the
5560 exact consequences of using this feature.
5562 @item -gnatw.V
5563 @emph{Suppress info messages for non-default bit order.}
5564 @cindex @option{-gnatw.V} (@command{gcc})
5565 This switch suppresses information messages for the effects of specifying
5566 non-default bit order on record components with component clauses.
5568 @item -gnatww
5569 @emph{Activate warnings on wrong low bound assumption.}
5570 @cindex @option{-gnatww} (@command{gcc})
5571 @cindex String indexing warnings
5572 This switch activates warnings for indexing an unconstrained string parameter
5573 with a literal or S'Length. This is a case where the code is assuming that the
5574 low bound is one, which is in general not true (for example when a slice is
5575 passed). The default is that such warnings are generated.
5577 @item -gnatwW
5578 @emph{Suppress warnings on wrong low bound assumption.}
5579 @cindex @option{-gnatwW} (@command{gcc})
5580 This switch suppresses warnings for indexing an unconstrained string parameter
5581 with a literal or S'Length. Note that this warning can also be suppressed
5582 in a particular case by adding an
5583 assertion that the lower bound is 1,
5584 as shown in the following example.
5586 @smallexample @c ada
5587    @b{procedure} K (S : String) @b{is}
5588       @b{pragma} Assert (S'First = 1);
5589       @dots{}
5590 @end smallexample
5592 @item -gnatw.w
5593 @emph{Activate warnings on Warnings Off pragmas}
5594 @cindex @option{-gnatw.w} (@command{gcc})
5595 @cindex Warnings Off control
5596 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5597 where either the pragma is entirely useless (because it suppresses no
5598 warnings), or it could be replaced by @code{pragma Unreferenced} or
5599 @code{pragma Unmodified}.
5600 Also activates warnings for the case of
5601 Warnings (Off, String), where either there is no matching
5602 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
5603 The default is that these warnings are not given.
5605 @item -gnatw.W
5606 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5607 @cindex @option{-gnatw.W} (@command{gcc})
5608 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
5610 @item -gnatwx
5611 @emph{Activate warnings on Export/Import pragmas.}
5612 @cindex @option{-gnatwx} (@command{gcc})
5613 @cindex Export/Import pragma warnings
5614 This switch activates warnings on Export/Import pragmas when
5615 the compiler detects a possible conflict between the Ada and
5616 foreign language calling sequences. For example, the use of
5617 default parameters in a convention C procedure is dubious
5618 because the C compiler cannot supply the proper default, so
5619 a warning is issued. The default is that such warnings are
5620 generated.
5622 @item -gnatwX
5623 @emph{Suppress warnings on Export/Import pragmas.}
5624 @cindex @option{-gnatwX} (@command{gcc})
5625 This switch suppresses warnings on Export/Import pragmas.
5626 The sense of this is that you are telling the compiler that
5627 you know what you are doing in writing the pragma, and it
5628 should not complain at you.
5630 @item -gnatw.x
5631 @emph{Activate warnings for No_Exception_Propagation mode.}
5632 @cindex @option{-gnatwm} (@command{gcc})
5633 This switch activates warnings for exception usage when pragma Restrictions
5634 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5635 explicit exception raises which are not covered by a local handler, and for
5636 exception handlers which do not cover a local raise. The default is that these
5637 warnings are not given.
5639 @item -gnatw.X
5640 @emph{Disable warnings for No_Exception_Propagation mode.}
5641 This switch disables warnings for exception usage when pragma Restrictions
5642 (No_Exception_Propagation) is in effect.
5644 @item -gnatwy
5645 @emph{Activate warnings for Ada compatibility issues.}
5646 @cindex @option{-gnatwy} (@command{gcc})
5647 @cindex Ada compatibility issues warnings
5648 For the most part, newer versions of Ada are upwards compatible
5649 with older versions. For example, Ada 2005 programs will almost
5650 always work when compiled as Ada 2012.
5651 However there are some exceptions (for example the fact that
5652 @code{some} is now a reserved word in Ada 2012). This
5653 switch activates several warnings to help in identifying
5654 and correcting such incompatibilities. The default is that
5655 these warnings are generated. Note that at one point Ada 2005
5656 was called Ada 0Y, hence the choice of character.
5658 @item -gnatwY
5659 @emph{Disable warnings for Ada compatibility issues.}
5660 @cindex @option{-gnatwY} (@command{gcc})
5661 @cindex Ada compatibility issues warnings
5662 This switch suppresses the warnings intended to help in identifying
5663 incompatibilities between Ada language versions.
5665 @item -gnatw.y
5666 @emph{Activate information messages for why package spec needs body}
5667 @cindex @option{-gnatw.y} (@command{gcc})
5668 @cindex Package spec needing body
5669 There are a number of cases in which a package spec needs a body.
5670 For example, the use of pragma Elaborate_Body, or the declaration
5671 of a procedure specification requiring a completion. This switch
5672 causes information messages to be output showing why a package
5673 specification requires a body. This can be useful in the case of
5674 a large package specification which is unexpectedly requiring a
5675 body. The default is that such information messages are not output.
5677 @item -gnatw.Y
5678 @emph{Disable information messages for why package spec needs body}
5679 @cindex @option{-gnatw.Y} (@command{gcc})
5680 @cindex No information messages for why package spec needs body
5681 This switch suppresses the output of information messages showing why
5682 a package specification needs a body.
5684 @item -gnatwz
5685 @emph{Activate warnings on unchecked conversions.}
5686 @cindex @option{-gnatwz} (@command{gcc})
5687 @cindex Unchecked_Conversion warnings
5688 This switch activates warnings for unchecked conversions
5689 where the types are known at compile time to have different
5690 sizes. The default
5691 is that such warnings are generated. Warnings are also
5692 generated for subprogram pointers with different conventions,
5693 and, on VMS only, for data pointers with different conventions.
5695 @item -gnatwZ
5696 @emph{Suppress warnings on unchecked conversions.}
5697 @cindex @option{-gnatwZ} (@command{gcc})
5698 This switch suppresses warnings for unchecked conversions
5699 where the types are known at compile time to have different
5700 sizes or conventions.
5702 @item -gnatw.z
5703 @emph{Activate warnings for size not a multiple of alignment.}
5704 @cindex @option{-gnatw.z} (@command{gcc})
5705 @cindex Size/Alignment warnings
5706 This switch activates warnings for cases of record types with
5707 specified @code{Size} and @code{Alignment} attributes where the
5708 size is not a multiple of the alignment, resulting in an object
5709 size that is greater than the specified size. The default
5710 is that such warnings are generated.
5712 @item -gnatw.Z
5713 @emph{Suppress warnings for size not a multiple of alignment.}
5714 @cindex @option{-gnatw.Z} (@command{gcc})
5715 @cindex Size/Alignment warnings
5716 This switch suppresses warnings for cases of record types with
5717 specified @code{Size} and @code{Alignment} attributes where the
5718 size is not a multiple of the alignment, resulting in an object
5719 size that is greater than the specified size.
5720 The warning can also be
5721 suppressed by giving an explicit @code{Object_Size} value.
5723 @item -Wunused
5724 @cindex @option{-Wunused}
5725 The warnings controlled by the @option{-gnatw} switch are generated by
5726 the front end of the compiler. The @option{GCC} back end can provide
5727 additional warnings and they are controlled by the @option{-W} switch.
5728 For example, @option{-Wunused} activates back end
5729 warnings for entities that are declared but not referenced.
5731 @item -Wuninitialized
5732 @cindex @option{-Wuninitialized}
5733 Similarly, @option{-Wuninitialized} activates
5734 the back end warning for uninitialized variables. This switch must be
5735 used in conjunction with an optimization level greater than zero.
5737 @item -Wstack-usage=@var{len}
5738 @cindex @option{-Wstack-usage}
5739 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5740 See @ref{Static Stack Usage Analysis} for details.
5742 @item -Wall
5743 @cindex @option{-Wall}
5744 This switch enables most warnings from the @option{GCC} back end.
5745 The code generator detects a number of warning situations that are missed
5746 by the @option{GNAT} front end, and this switch can be used to activate them.
5747 The use of this switch also sets the default front end warning mode to
5748 @option{-gnatwa}, that is, most front end warnings activated as well.
5750 @item -w
5751 @cindex @option{-w}
5752 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5753 The use of this switch also sets the default front end warning mode to
5754 @option{-gnatws}, that is, front end warnings suppressed as well.
5756 @item -Werror
5757 @cindex @option{-Werror}
5758 This switch causes warnings from the @option{GCC} back end to be treated as
5759 errors.  The warning string still appears, but the warning messages are
5760 counted as errors, and prevent the generation of an object file.
5762 @end table
5764 @noindent
5765 A string of warning parameters can be used in the same parameter. For example:
5767 @smallexample
5768 -gnatwaGe
5769 @end smallexample
5771 @noindent
5772 will turn on all optional warnings except for unrecognized pragma warnings,
5773 and also specify that warnings should be treated as errors.
5775 When no switch @option{-gnatw} is used, this is equivalent to:
5777 @table @option
5778 @c !sort!
5779 @item -gnatw.a
5780 @item -gnatwB
5781 @item -gnatw.b
5782 @item -gnatwC
5783 @item -gnatw.C
5784 @item -gnatwD
5785 @item -gnatwF
5786 @item -gnatwg
5787 @item -gnatwH
5788 @item -gnatwi
5789 @item -gnatw.I
5790 @item -gnatwJ
5791 @item -gnatwK
5792 @item -gnatwL
5793 @item -gnatw.L
5794 @item -gnatwM
5795 @item -gnatw.m
5796 @item -gnatwn
5797 @item -gnatwo
5798 @item -gnatw.O
5799 @item -gnatwP
5800 @item -gnatw.P
5801 @item -gnatwq
5802 @item -gnatwR
5803 @item -gnatw.R
5804 @item -gnatw.S
5805 @item -gnatwT
5806 @item -gnatw.T
5807 @item -gnatwU
5808 @item -gnatwv
5809 @item -gnatww
5810 @item -gnatw.W
5811 @item -gnatwx
5812 @item -gnatw.X
5813 @item -gnatwy
5814 @item -gnatwz
5816 @end table
5818 @node Debugging and Assertion Control
5819 @subsection Debugging and Assertion Control
5821 @table @option
5822 @item -gnata
5823 @cindex @option{-gnata} (@command{gcc})
5824 @findex Assert
5825 @findex Debug
5826 @cindex Assertions
5828 @noindent
5829 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5830 are ignored. This switch, where @samp{a} stands for assert, causes
5831 @code{Assert} and @code{Debug} pragmas to be activated.
5833 The pragmas have the form:
5835 @smallexample
5836 @cartouche
5837    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5838                       @var{static-string-expression}@r{]})
5839    @b{pragma} Debug (@var{procedure call})
5840 @end cartouche
5841 @end smallexample
5843 @noindent
5844 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5845 If the result is @code{True}, the pragma has no effect (other than
5846 possible side effects from evaluating the expression). If the result is
5847 @code{False}, the exception @code{Assert_Failure} declared in the package
5848 @code{System.Assertions} is
5849 raised (passing @var{static-string-expression}, if present, as the
5850 message associated with the exception). If no string expression is
5851 given the default is a string giving the file name and line number
5852 of the pragma.
5854 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5855 @code{pragma Debug} may appear within a declaration sequence, allowing
5856 debugging procedures to be called between declarations.
5858 @end table
5860 @node Validity Checking
5861 @subsection Validity Checking
5862 @findex Validity Checking
5864 @noindent
5865 The Ada Reference Manual defines the concept of invalid values (see
5866 RM 13.9.1). The primary source of invalid values is uninitialized
5867 variables. A scalar variable that is left uninitialized may contain
5868 an invalid value; the concept of invalid does not apply to access or
5869 composite types.
5871 It is an error to read an invalid value, but the RM does not require
5872 run-time checks to detect such errors, except for some minimal
5873 checking to prevent erroneous execution (i.e. unpredictable
5874 behavior). This corresponds to the @option{-gnatVd} switch below,
5875 which is the default. For example, by default, if the expression of a
5876 case statement is invalid, it will raise Constraint_Error rather than
5877 causing a wild jump, and if an array index on the left-hand side of an
5878 assignment is invalid, it will raise Constraint_Error rather than
5879 overwriting an arbitrary memory location.
5881 The @option{-gnatVa} may be used to enable additional validity checks,
5882 which are not required by the RM. These checks are often very
5883 expensive (which is why the RM does not require them). These checks
5884 are useful in tracking down uninitialized variables, but they are
5885 not usually recommended for production builds, and in particular
5886 we do not recommend using these extra validity checking options in
5887 combination with optimization, since this can confuse the optimizer.
5888 If performance is a consideration, leading to the need to optimize,
5889 then the validity checking options should not be used.
5891 The other @option{-gnatV@var{x}} switches below allow finer-grained
5892 control; you can enable whichever validity checks you desire. However,
5893 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5894 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5895 sufficient for non-debugging use.
5897 The @option{-gnatB} switch tells the compiler to assume that all
5898 values are valid (that is, within their declared subtype range)
5899 except in the context of a use of the Valid attribute. This means
5900 the compiler can generate more efficient code, since the range
5901 of values is better known at compile time. However, an uninitialized
5902 variable can cause wild jumps and memory corruption in this mode.
5904 The @option{-gnatV@var{x}} switch allows control over the validity
5905 checking mode as described below.
5906 The @code{x} argument is a string of letters that
5907 indicate validity checks that are performed or not performed in addition
5908 to the default checks required by Ada as described above.
5910 @table @option
5911 @c !sort!
5912 @item -gnatVa
5913 @emph{All validity checks.}
5914 @cindex @option{-gnatVa} (@command{gcc})
5915 All validity checks are turned on.
5916 That is, @option{-gnatVa} is
5917 equivalent to @option{gnatVcdfimorst}.
5919 @item -gnatVc
5920 @emph{Validity checks for copies.}
5921 @cindex @option{-gnatVc} (@command{gcc})
5922 The right hand side of assignments, and the initializing values of
5923 object declarations are validity checked.
5925 @item -gnatVd
5926 @emph{Default (RM) validity checks.}
5927 @cindex @option{-gnatVd} (@command{gcc})
5928 Some validity checks are done by default following normal Ada semantics
5929 (RM 13.9.1 (9-11)).
5930 A check is done in case statements that the expression is within the range
5931 of the subtype. If it is not, Constraint_Error is raised.
5932 For assignments to array components, a check is done that the expression used
5933 as index is within the range. If it is not, Constraint_Error is raised.
5934 Both these validity checks may be turned off using switch @option{-gnatVD}.
5935 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5936 switch @option{-gnatVd} will leave the checks turned on.
5937 Switch @option{-gnatVD} should be used only if you are sure that all such
5938 expressions have valid values. If you use this switch and invalid values
5939 are present, then the program is erroneous, and wild jumps or memory
5940 overwriting may occur.
5942 @item -gnatVe
5943 @emph{Validity checks for elementary components.}
5944 @cindex @option{-gnatVe} (@command{gcc})
5945 In the absence of this switch, assignments to record or array components are
5946 not validity checked, even if validity checks for assignments generally
5947 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5948 require valid data, but assignment of individual components does. So for
5949 example, there is a difference between copying the elements of an array with a
5950 slice assignment, compared to assigning element by element in a loop. This
5951 switch allows you to turn off validity checking for components, even when they
5952 are assigned component by component.
5954 @item -gnatVf
5955 @emph{Validity checks for floating-point values.}
5956 @cindex @option{-gnatVf} (@command{gcc})
5957 In the absence of this switch, validity checking occurs only for discrete
5958 values. If @option{-gnatVf} is specified, then validity checking also applies
5959 for floating-point values, and NaNs and infinities are considered invalid,
5960 as well as out of range values for constrained types. Note that this means
5961 that standard IEEE infinity mode is not allowed. The exact contexts
5962 in which floating-point values are checked depends on the setting of other
5963 options. For example,
5964 @option{-gnatVif} or
5965 @option{-gnatVfi}
5966 (the order does not matter) specifies that floating-point parameters of mode
5967 @code{in} should be validity checked.
5969 @item -gnatVi
5970 @emph{Validity checks for @code{in} mode parameters}
5971 @cindex @option{-gnatVi} (@command{gcc})
5972 Arguments for parameters of mode @code{in} are validity checked in function
5973 and procedure calls at the point of call.
5975 @item -gnatVm
5976 @emph{Validity checks for @code{in out} mode parameters.}
5977 @cindex @option{-gnatVm} (@command{gcc})
5978 Arguments for parameters of mode @code{in out} are validity checked in
5979 procedure calls at the point of call. The @code{'m'} here stands for
5980 modify, since this concerns parameters that can be modified by the call.
5981 Note that there is no specific option to test @code{out} parameters,
5982 but any reference within the subprogram will be tested in the usual
5983 manner, and if an invalid value is copied back, any reference to it
5984 will be subject to validity checking.
5986 @item -gnatVn
5987 @emph{No validity checks.}
5988 @cindex @option{-gnatVn} (@command{gcc})
5989 This switch turns off all validity checking, including the default checking
5990 for case statements and left hand side subscripts. Note that the use of
5991 the switch @option{-gnatp} suppresses all run-time checks, including
5992 validity checks, and thus implies @option{-gnatVn}. When this switch
5993 is used, it cancels any other @option{-gnatV} previously issued.
5995 @item -gnatVo
5996 @emph{Validity checks for operator and attribute operands.}
5997 @cindex @option{-gnatVo} (@command{gcc})
5998 Arguments for predefined operators and attributes are validity checked.
5999 This includes all operators in package @code{Standard},
6000 the shift operators defined as intrinsic in package @code{Interfaces}
6001 and operands for attributes such as @code{Pos}. Checks are also made
6002 on individual component values for composite comparisons, and on the
6003 expressions in type conversions and qualified expressions. Checks are
6004 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6006 @item -gnatVp
6007 @emph{Validity checks for parameters.}
6008 @cindex @option{-gnatVp} (@command{gcc})
6009 This controls the treatment of parameters within a subprogram (as opposed
6010 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6011 of parameters on a call. If either of these call options is used, then
6012 normally an assumption is made within a subprogram that the input arguments
6013 have been validity checking at the point of call, and do not need checking
6014 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6015 is not made, and parameters are not assumed to be valid, so their validity
6016 will be checked (or rechecked) within the subprogram.
6018 @item -gnatVr
6019 @emph{Validity checks for function returns.}
6020 @cindex @option{-gnatVr} (@command{gcc})
6021 The expression in @code{return} statements in functions is validity
6022 checked.
6024 @item -gnatVs
6025 @emph{Validity checks for subscripts.}
6026 @cindex @option{-gnatVs} (@command{gcc})
6027 All subscripts expressions are checked for validity, whether they appear
6028 on the right side or left side (in default mode only left side subscripts
6029 are validity checked).
6031 @item -gnatVt
6032 @emph{Validity checks for tests.}
6033 @cindex @option{-gnatVt} (@command{gcc})
6034 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6035 statements are checked, as well as guard expressions in entry calls.
6037 @end table
6039 @noindent
6040 The @option{-gnatV} switch may be followed by
6041 a string of letters
6042 to turn on a series of validity checking options.
6043 For example,
6044 @option{-gnatVcr}
6045 specifies that in addition to the default validity checking, copies and
6046 function return expressions are to be validity checked.
6047 In order to make it easier
6048 to specify the desired combination of effects,
6049 the upper case letters @code{CDFIMORST} may
6050 be used to turn off the corresponding lower case option.
6051 Thus
6052 @option{-gnatVaM}
6053 turns on all validity checking options except for
6054 checking of @code{@b{in out}} procedure arguments.
6056 The specification of additional validity checking generates extra code (and
6057 in the case of @option{-gnatVa} the code expansion can be substantial).
6058 However, these additional checks can be very useful in detecting
6059 uninitialized variables, incorrect use of unchecked conversion, and other
6060 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6061 is useful in conjunction with the extra validity checking, since this
6062 ensures that wherever possible uninitialized variables have invalid values.
6064 See also the pragma @code{Validity_Checks} which allows modification of
6065 the validity checking mode at the program source level, and also allows for
6066 temporary disabling of validity checks.
6068 @node Style Checking
6069 @subsection Style Checking
6070 @findex Style checking
6072 @noindent
6073 The @option{-gnatyx} switch
6074 @cindex @option{-gnaty} (@command{gcc})
6075 causes the compiler to
6076 enforce specified style rules. A limited set of style rules has been used
6077 in writing the GNAT sources themselves. This switch allows user programs
6078 to activate all or some of these checks. If the source program fails a
6079 specified style check, an appropriate message is given, preceded by
6080 the character sequence ``(style)''. This message does not prevent
6081 successful compilation (unless the @option{-gnatwe} switch is used).
6083 Note that this is by no means intended to be a general facility for
6084 checking arbitrary coding standards. It is simply an embedding of the
6085 style rules we have chosen for the GNAT sources. If you are starting
6086 a project which does not have established style standards, you may
6087 find it useful to adopt the entire set of GNAT coding standards, or
6088 some subset of them.
6089 @ifclear FSFEDITION
6090 If you already have an established set of coding
6091 standards, then the selected style checking options may
6092 indeed correspond to choices you have made, but for general checking
6093 of an existing set of coding rules, you should look to the gnatcheck
6094 tool, which is designed for that purpose.
6095 @end ifclear
6097 The string @var{x} is a sequence of letters or digits
6098 indicating the particular style
6099 checks to be performed. The following checks are defined:
6101 @table @option
6102 @c !sort!
6103 @item 0-9
6104 @emph{Specify indentation level.}
6105 If a digit from 1-9 appears
6106 in the string after @option{-gnaty}
6107 then proper indentation is checked, with the digit indicating the
6108 indentation level required. A value of zero turns off this style check.
6109 The general style of required indentation is as specified by
6110 the examples in the Ada Reference Manual. Full line comments must be
6111 aligned with the @code{--} starting on a column that is a multiple of
6112 the alignment level, or they may be aligned the same way as the following
6113 non-blank line (this is useful when full line comments appear in the middle
6114 of a statement, or they may be aligned with the source line on the previous
6115 non-blank line.
6117 @item a
6118 @emph{Check attribute casing.}
6119 Attribute names, including the case of keywords such as @code{digits}
6120 used as attributes names, must be written in mixed case, that is, the
6121 initial letter and any letter following an underscore must be uppercase.
6122 All other letters must be lowercase.
6124 @item A
6125 @emph{Use of array index numbers in array attributes.}
6126 When using the array attributes First, Last, Range,
6127 or Length, the index number must be omitted for one-dimensional arrays
6128 and is required for multi-dimensional arrays.
6130 @item b
6131 @emph{Blanks not allowed at statement end.}
6132 Trailing blanks are not allowed at the end of statements. The purpose of this
6133 rule, together with h (no horizontal tabs), is to enforce a canonical format
6134 for the use of blanks to separate source tokens.
6136 @item B
6137 @emph{Check Boolean operators.}
6138 The use of AND/OR operators is not permitted except in the cases of modular
6139 operands, array operands, and simple stand-alone boolean variables or
6140 boolean constants. In all other cases @code{and then}/@code{or else} are
6141 required.
6143 @item c
6144 @emph{Check comments, double space.}
6145 Comments must meet the following set of rules:
6147 @itemize @bullet
6149 @item
6150 The ``@code{--}'' that starts the column must either start in column one,
6151 or else at least one blank must precede this sequence.
6153 @item
6154 Comments that follow other tokens on a line must have at least one blank
6155 following the ``@code{--}'' at the start of the comment.
6157 @item
6158 Full line comments must have at least two blanks following the
6159 ``@code{--}'' that starts the comment, with the following exceptions.
6161 @item
6162 A line consisting only of the ``@code{--}'' characters, possibly preceded
6163 by blanks is permitted.
6165 @item
6166 A comment starting with ``@code{--x}'' where @code{x} is a special character
6167 is permitted.
6168 This allows proper processing of the output generated by specialized tools
6169 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6170 annotation
6171 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6172 special character is defined as being in one of the ASCII ranges
6173 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6174 Note that this usage is not permitted
6175 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6177 @item
6178 A line consisting entirely of minus signs, possibly preceded by blanks, is
6179 permitted. This allows the construction of box comments where lines of minus
6180 signs are used to form the top and bottom of the box.
6182 @item
6183 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6184 least one blank follows the initial ``@code{--}''. Together with the preceding
6185 rule, this allows the construction of box comments, as shown in the following
6186 example:
6187 @smallexample
6188 ---------------------------
6189 -- This is a box comment --
6190 -- with two text lines.  --
6191 ---------------------------
6192 @end smallexample
6193 @end itemize
6195 @item C
6196 @emph{Check comments, single space.}
6197 This is identical to @code{c} except that only one space
6198 is required following the @code{--} of a comment instead of two.
6200 @item d
6201 @emph{Check no DOS line terminators present.}
6202 All lines must be terminated by a single ASCII.LF
6203 character (in particular the DOS line terminator sequence CR/LF is not
6204 allowed).
6206 @item e
6207 @emph{Check end/exit labels.}
6208 Optional labels on @code{end} statements ending subprograms and on
6209 @code{exit} statements exiting named loops, are required to be present.
6211 @item f
6212 @emph{No form feeds or vertical tabs.}
6213 Neither form feeds nor vertical tab characters are permitted
6214 in the source text.
6216 @item g
6217 @emph{GNAT style mode.}
6218 The set of style check switches is set to match that used by the GNAT sources.
6219 This may be useful when developing code that is eventually intended to be
6220 incorporated into GNAT. Currently this is equivalent to @option{-gnatwydISux})
6221 but additional style switches may be added to this set in the future without
6222 advance notice.
6224 @item h
6225 @emph{No horizontal tabs.}
6226 Horizontal tab characters are not permitted in the source text.
6227 Together with the b (no blanks at end of line) check, this
6228 enforces a canonical form for the use of blanks to separate
6229 source tokens.
6231 @item i
6232 @emph{Check if-then layout.}
6233 The keyword @code{then} must appear either on the same
6234 line as corresponding @code{if}, or on a line on its own, lined
6235 up under the @code{if}.
6237 @item I
6238 @emph{check mode IN keywords.}
6239 Mode @code{in} (the default mode) is not
6240 allowed to be given explicitly. @code{in out} is fine,
6241 but not @code{in} on its own.
6243 @item k
6244 @emph{Check keyword casing.}
6245 All keywords must be in lower case (with the exception of keywords
6246 such as @code{digits} used as attribute names to which this check
6247 does not apply).
6249 @item l
6250 @emph{Check layout.}
6251 Layout of statement and declaration constructs must follow the
6252 recommendations in the Ada Reference Manual, as indicated by the
6253 form of the syntax rules. For example an @code{else} keyword must
6254 be lined up with the corresponding @code{if} keyword.
6256 There are two respects in which the style rule enforced by this check
6257 option are more liberal than those in the Ada Reference Manual. First
6258 in the case of record declarations, it is permissible to put the
6259 @code{record} keyword on the same line as the @code{type} keyword, and
6260 then the @code{end} in @code{end record} must line up under @code{type}.
6261 This is also permitted when the type declaration is split on two lines.
6262 For example, any of the following three layouts is acceptable:
6264 @smallexample @c ada
6265 @cartouche
6266 @b{type} q @b{is} @b{record}
6267    a : integer;
6268    b : integer;
6269 @b{end} @b{record};
6271 @b{type} q @b{is}
6272    @b{record}
6273       a : integer;
6274       b : integer;
6275    @b{end} @b{record};
6277 @b{type} q @b{is}
6278    @b{record}
6279       a : integer;
6280       b : integer;
6281 @b{end} @b{record};
6283 @end cartouche
6284 @end smallexample
6286 @noindent
6287 Second, in the case of a block statement, a permitted alternative
6288 is to put the block label on the same line as the @code{declare} or
6289 @code{begin} keyword, and then line the @code{end} keyword up under
6290 the block label. For example both the following are permitted:
6292 @smallexample @c ada
6293 @cartouche
6294 Block : @b{declare}
6295    A : Integer := 3;
6296 @b{begin}
6297    Proc (A, A);
6298 @b{end} Block;
6300 Block :
6301    @b{declare}
6302       A : Integer := 3;
6303    @b{begin}
6304       Proc (A, A);
6305    @b{end} Block;
6306 @end cartouche
6307 @end smallexample
6309 @noindent
6310 The same alternative format is allowed for loops. For example, both of
6311 the following are permitted:
6313 @smallexample @c ada
6314 @cartouche
6315 Clear : @b{while} J < 10 @b{loop}
6316    A (J) := 0;
6317 @b{end} @b{loop} Clear;
6319 Clear :
6320    @b{while} J < 10 @b{loop}
6321       A (J) := 0;
6322    @b{end} @b{loop} Clear;
6323 @end cartouche
6324 @end smallexample
6326 @item Lnnn
6327 @emph{Set maximum nesting level.}
6328 The maximum level of nesting of constructs (including subprograms, loops,
6329 blocks, packages, and conditionals) may not exceed the given value
6330 @option{nnn}. A value of zero disconnects this style check.
6332 @item m
6333 @emph{Check maximum line length.}
6334 The length of source lines must not exceed 79 characters, including
6335 any trailing blanks. The value of 79 allows convenient display on an
6336 80 character wide device or window, allowing for possible special
6337 treatment of 80 character lines. Note that this count is of
6338 characters in the source text. This means that a tab character counts
6339 as one character in this count and a wide character sequence counts as
6340 a single character (however many bytes are needed in the encoding).
6342 @item Mnnn
6343 @emph{Set maximum line length.}
6344 The length of lines must not exceed the
6345 given value @option{nnn}. The maximum value that can be specified is 32767.
6346 If neither style option for setting the line length is used, then the
6347 default is 255. This also controls the maximum length of lexical elements,
6348 where the only restriction is that they must fit on a single line.
6350 @item n
6351 @emph{Check casing of entities in Standard.}
6352 Any identifier from Standard must be cased
6353 to match the presentation in the Ada Reference Manual (for example,
6354 @code{Integer} and @code{ASCII.NUL}).
6356 @item N
6357 @emph{Turn off all style checks.}
6358 All style check options are turned off.
6360 @item o
6361 @emph{Check order of subprogram bodies.}
6362 All subprogram bodies in a given scope
6363 (e.g.@: a package body) must be in alphabetical order. The ordering
6364 rule uses normal Ada rules for comparing strings, ignoring casing
6365 of letters, except that if there is a trailing numeric suffix, then
6366 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6367 before Junk10).
6369 @item O
6370 @emph{Check that overriding subprograms are explicitly marked as such.}
6371 The declaration of a primitive operation of a type extension that overrides
6372 an inherited operation must carry an overriding indicator.
6374 @item p
6375 @emph{Check pragma casing.}
6376 Pragma names must be written in mixed case, that is, the
6377 initial letter and any letter following an underscore must be uppercase.
6378 All other letters must be lowercase. An exception is that SPARK_Mode is
6379 allowed as an alternative for Spark_Mode.
6381 @item r
6382 @emph{Check references.}
6383 All identifier references must be cased in the same way as the
6384 corresponding declaration. No specific casing style is imposed on
6385 identifiers. The only requirement is for consistency of references
6386 with declarations.
6388 @item s
6389 @emph{Check separate specs.}
6390 Separate declarations (``specs'') are required for subprograms (a
6391 body is not allowed to serve as its own declaration). The only
6392 exception is that parameterless library level procedures are
6393 not required to have a separate declaration. This exception covers
6394 the most frequent form of main program procedures.
6396 @item S
6397 @emph{Check no statements after @code{then}/@code{else}.}
6398 No statements are allowed
6399 on the same line as a @code{then} or @code{else} keyword following the
6400 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6401 affected, and a special exception allows a pragma to appear after @code{else}.
6403 @item t
6404 @emph{Check token spacing.}
6405 The following token spacing rules are enforced:
6407 @itemize @bullet
6409 @item
6410 The keywords @code{abs} and @code{not} must be followed by a space.
6412 @item
6413 The token @code{=>} must be surrounded by spaces.
6415 @item
6416 The token @code{<>} must be preceded by a space or a left parenthesis.
6418 @item
6419 Binary operators other than @code{**} must be surrounded by spaces.
6420 There is no restriction on the layout of the @code{**} binary operator.
6422 @item
6423 Colon must be surrounded by spaces.
6425 @item
6426 Colon-equal (assignment, initialization) must be surrounded by spaces.
6428 @item
6429 Comma must be the first non-blank character on the line, or be
6430 immediately preceded by a non-blank character, and must be followed
6431 by a space.
6433 @item
6434 If the token preceding a left parenthesis ends with a letter or digit, then
6435 a space must separate the two tokens.
6437 @item
6438 if the token following a right parenthesis starts with a letter or digit, then
6439 a space must separate the two tokens.
6441 @item
6442 A right parenthesis must either be the first non-blank character on
6443 a line, or it must be preceded by a non-blank character.
6445 @item
6446 A semicolon must not be preceded by a space, and must not be followed by
6447 a non-blank character.
6449 @item
6450 A unary plus or minus may not be followed by a space.
6452 @item
6453 A vertical bar must be surrounded by spaces.
6454 @end itemize
6456 @item
6457 Exactly one blank (and no other white space) must appear between
6458 a @code{not} token and a following @code{in} token.
6460 @item u
6461 @emph{Check unnecessary blank lines.}
6462 Unnecessary blank lines are not allowed. A blank line is considered
6463 unnecessary if it appears at the end of the file, or if more than
6464 one blank line occurs in sequence.
6466 @item x
6467 @emph{Check extra parentheses.}
6468 Unnecessary extra level of parentheses (C-style) are not allowed
6469 around conditions in @code{if} statements, @code{while} statements and
6470 @code{exit} statements.
6472 @item y
6473 @emph{Set all standard style check options}
6474 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6475 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6476 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6477 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6479 @item -
6480 @emph{Remove style check options}
6481 This causes any subsequent options in the string to act as canceling the
6482 corresponding style check option. To cancel maximum nesting level control,
6483 use @option{L} parameter witout any integer value after that, because any
6484 digit following @option{-} in the parameter string of the @option{-gnaty}
6485 option will be threated as canceling indentation check. The same is true
6486 for @option{M} parameter. @option{y} and @option{N} parameters are not
6487 allowed after @option{-}.
6489 @item +
6490 This causes any subsequent options in the string to enable the corresponding
6491 style check option. That is, it cancels the effect of a previous -,
6492 if any.
6494 @end table
6496 @noindent
6497 In the above rules, appearing in column one is always permitted, that is,
6498 counts as meeting either a requirement for a required preceding space,
6499 or as meeting a requirement for no preceding space.
6501 Appearing at the end of a line is also always permitted, that is, counts
6502 as meeting either a requirement for a following space, or as meeting
6503 a requirement for no following space.
6505 @noindent
6506 If any of these style rules is violated, a message is generated giving
6507 details on the violation. The initial characters of such messages are
6508 always ``@code{(style)}''. Note that these messages are treated as warning
6509 messages, so they normally do not prevent the generation of an object
6510 file. The @option{-gnatwe} switch can be used to treat warning messages,
6511 including style messages, as fatal errors.
6513 The switch
6514 @option{-gnaty} on its own (that is not
6515 followed by any letters or digits) is equivalent
6516 to the use of @option{-gnatyy} as described above, that is all
6517 built-in standard style check options are enabled.
6520 The switch
6521 @option{-gnatyN}
6522 clears any previously set style checks.
6524 @node Run-Time Checks
6525 @subsection Run-Time Checks
6526 @cindex Division by zero
6527 @cindex Access before elaboration
6528 @cindex Checks, division by zero
6529 @cindex Checks, access before elaboration
6530 @cindex Checks, stack overflow checking
6532 @noindent
6533 By default, the following checks are suppressed: integer overflow
6534 checks, stack overflow checks, and checks for access before
6535 elaboration on subprogram calls. All other checks, including range
6536 checks and array bounds checks, are turned on by default. The
6537 following @command{gcc} switches refine this default behavior.
6539 @table @option
6540 @c !sort!
6541 @item -gnatp
6542 @cindex @option{-gnatp} (@command{gcc})
6543 @cindex Suppressing checks
6544 @cindex Checks, suppressing
6545 @findex Suppress
6546 This switch causes the unit to be compiled
6547 as though @code{pragma Suppress (All_checks)}
6548 had been present in the source. Validity checks are also eliminated (in
6549 other words @option{-gnatp} also implies @option{-gnatVn}.
6550 Use this switch to improve the performance
6551 of the code at the expense of safety in the presence of invalid data or
6552 program bugs.
6554 Note that when checks are suppressed, the compiler is allowed, but not
6555 required, to omit the checking code. If the run-time cost of the
6556 checking code is zero or near-zero, the compiler will generate it even
6557 if checks are suppressed. In particular, if the compiler can prove
6558 that a certain check will necessarily fail, it will generate code to
6559 do an unconditional ``raise'', even if checks are suppressed. The
6560 compiler warns in this case. Another case in which checks may not be
6561 eliminated is when they are embedded in certain run time routines such
6562 as math library routines.
6564 Of course, run-time checks are omitted whenever the compiler can prove
6565 that they will not fail, whether or not checks are suppressed.
6567 Note that if you suppress a check that would have failed, program
6568 execution is erroneous, which means the behavior is totally
6569 unpredictable. The program might crash, or print wrong answers, or
6570 do anything else. It might even do exactly what you wanted it to do
6571 (and then it might start failing mysteriously next week or next
6572 year). The compiler will generate code based on the assumption that
6573 the condition being checked is true, which can result in erroneous
6574 execution if that assumption is wrong.
6576 The checks subject to suppression include all the checks defined by
6577 the Ada standard, the additional implementation defined checks
6578 @code{Alignment_Check},
6579 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, and
6580 @code{Validity_Check}, as well as any checks introduced using
6581 @code{pragma Check_Name}. Note that @code{Atomic_Synchronization}
6582 is not automatically suppressed by use of this option.
6584 If the code depends on certain checks being active, you can use
6585 pragma @code{Unsuppress} either as a configuration pragma or as
6586 a local pragma to make sure that a specified check is performed
6587 even if @option{gnatp} is specified.
6589 The @option{-gnatp} switch has no effect if a subsequent
6590 @option{-gnat-p} switch appears.
6592 @item -gnat-p
6593 @cindex @option{-gnat-p} (@command{gcc})
6594 @cindex Suppressing checks
6595 @cindex Checks, suppressing
6596 @findex Suppress
6597 This switch cancels the effect of a previous @option{gnatp} switch.
6599 @item -gnato??
6600 @cindex @option{-gnato??} (@command{gcc})
6601 @cindex Overflow checks
6602 @cindex Overflow mode
6603 @cindex Check, overflow
6604 This switch controls the mode used for computing intermediate
6605 arithmetic integer operations, and also enables overflow checking.
6606 For a full description of overflow mode and checking control, see
6607 the ``Overflow Check Handling in GNAT'' appendix in this
6608 User's Guide.
6610 Overflow checks are always enabled by this switch. The argument
6611 controls the mode, using the codes
6613 @itemize
6614 @item 1 = STRICT
6615 In STRICT mode, intermediate operations are always done using the
6616 base type, and overflow checking ensures that the result is within
6617 the base type range.
6619 @item 2 = MINIMIZED
6620 In MINIMIZED mode, overflows in intermediate operations are avoided
6621 where possible by using a larger integer type for the computation
6622 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6623 the result fits in this larger integer type.
6625 @item 3 = ELIMINATED
6626 In ELIMINATED mode, overflows in intermediate operations are avoided
6627 by using multi-precision arithmetic. In this case, overflow checking
6628 has no effect on intermediate operations (since overflow is impossible).
6629 @end itemize
6631 If two digits are present after @option{-gnato} then the first digit
6632 sets the mode for expressions outside assertions, and the second digit
6633 sets the mode for expressions within assertions. Here assertions is used
6634 in the technical sense (which includes for example precondition and
6635 postcondition expressions).
6637 If one digit is present, the corresponding mode is applicable to both
6638 expressions within and outside assertion expressions.
6640 If no digits are present, the default is to enable overflow checks
6641 and set STRICT mode for both kinds of expressions. This is compatible
6642 with the use of @option{-gnato} in previous versions of GNAT.
6644 @findex Machine_Overflows
6645 Note that the @option{-gnato??} switch does not affect the code generated
6646 for any floating-point operations; it applies only to integer semantics.
6647 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6648 attribute set to @code{False} and the normal mode of operation is to
6649 generate IEEE NaN and infinite values on overflow or invalid operations
6650 (such as dividing 0.0 by 0.0).
6652 The reason that we distinguish overflow checking from other kinds of
6653 range constraint checking is that a failure of an overflow check, unlike
6654 for example the failure of a range check, can result in an incorrect
6655 value, but cannot cause random memory destruction (like an out of range
6656 subscript), or a wild jump (from an out of range case value). Overflow
6657 checking is also quite expensive in time and space, since in general it
6658 requires the use of double length arithmetic.
6660 Note again that the default is @option{-gnato00},
6661 so overflow checking is not performed in default mode. This means that out of
6662 the box, with the default settings, @value{EDITION} does not do all the checks
6663 expected from the language description in the Ada Reference Manual.
6664 If you want all constraint checks to be performed, as described in this Manual,
6665 then you must explicitly use the @option{-gnato??}
6666 switch either on the @command{gnatmake} or @command{gcc} command.
6668 @item -gnatE
6669 @cindex @option{-gnatE} (@command{gcc})
6670 @cindex Elaboration checks
6671 @cindex Check, elaboration
6672 Enables dynamic checks for access-before-elaboration
6673 on subprogram calls and generic instantiations.
6674 Note that @option{-gnatE} is not necessary for safety, because in the
6675 default mode, GNAT ensures statically that the checks would not fail.
6676 For full details of the effect and use of this switch,
6677 @xref{Compiling with gcc}.
6679 @item -fstack-check
6680 @cindex @option{-fstack-check} (@command{gcc})
6681 @cindex Stack Overflow Checking
6682 @cindex Checks, stack overflow checking
6683 Activates stack overflow checking. For full details of the effect and use of
6684 this switch see @ref{Stack Overflow Checking}.
6685 @end table
6687 @findex Unsuppress
6688 @noindent
6689 The setting of these switches only controls the default setting of the
6690 checks. You may modify them using either @code{Suppress} (to remove
6691 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6692 the program source.
6694 @node Using gcc for Syntax Checking
6695 @subsection Using @command{gcc} for Syntax Checking
6696 @table @option
6697 @item -gnats
6698 @cindex @option{-gnats} (@command{gcc})
6700 @noindent
6701 The @code{s} stands for ``syntax''.
6703 Run GNAT in syntax checking only mode. For
6704 example, the command
6706 @smallexample
6707 $ gcc -c -gnats x.adb
6708 @end smallexample
6710 @noindent
6711 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6712 series of files in a single command
6713 , and can use wild cards to specify such a group of files.
6714 Note that you must specify the @option{-c} (compile
6715 only) flag in addition to the @option{-gnats} flag.
6717 You may use other switches in conjunction with @option{-gnats}. In
6718 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6719 format of any generated error messages.
6721 When the source file is empty or contains only empty lines and/or comments,
6722 the output is a warning:
6724 @smallexample
6725 $ gcc -c -gnats -x ada toto.txt
6726 toto.txt:1:01: warning: empty file, contains no compilation units
6728 @end smallexample
6730 Otherwise, the output is simply the error messages, if any. No object file or
6731 ALI file is generated by a syntax-only compilation. Also, no units other
6732 than the one specified are accessed. For example, if a unit @code{X}
6733 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6734 check only mode does not access the source file containing unit
6735 @code{Y}.
6737 @cindex Multiple units, syntax checking
6738 Normally, GNAT allows only a single unit in a source file. However, this
6739 restriction does not apply in syntax-check-only mode, and it is possible
6740 to check a file containing multiple compilation units concatenated
6741 together. This is primarily used by the @code{gnatchop} utility
6742 (@pxref{Renaming Files with gnatchop}).
6743 @end table
6745 @node Using gcc for Semantic Checking
6746 @subsection Using @command{gcc} for Semantic Checking
6747 @table @option
6748 @item -gnatc
6749 @cindex @option{-gnatc} (@command{gcc})
6751 @noindent
6752 The @code{c} stands for ``check''.
6753 Causes the compiler to operate in semantic check mode,
6754 with full checking for all illegalities specified in the
6755 Ada Reference Manual, but without generation of any object code
6756 (no object file is generated).
6758 Because dependent files must be accessed, you must follow the GNAT
6759 semantic restrictions on file structuring to operate in this mode:
6761 @itemize @bullet
6762 @item
6763 The needed source files must be accessible
6764 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6766 @item
6767 Each file must contain only one compilation unit.
6769 @item
6770 The file name and unit name must match (@pxref{File Naming Rules}).
6771 @end itemize
6773 The output consists of error messages as appropriate. No object file is
6774 generated. An @file{ALI} file is generated for use in the context of
6775 cross-reference tools, but this file is marked as not being suitable
6776 for binding (since no object file is generated).
6777 The checking corresponds exactly to the notion of
6778 legality in the Ada Reference Manual.
6780 Any unit can be compiled in semantics-checking-only mode, including
6781 units that would not normally be compiled (subunits,
6782 and specifications where a separate body is present).
6783 @end table
6785 @node Compiling Different Versions of Ada
6786 @subsection Compiling Different Versions of Ada
6788 @noindent
6789 The switches described in this section allow you to explicitly specify
6790 the version of the Ada language that your programs are written in.
6791 The default mode is Ada 2012,
6792 but you can also specify Ada 95, Ada 2005 mode, or
6793 indicate Ada 83 compatibility mode.
6795 @table @option
6796 @cindex Compatibility with Ada 83
6798 @item -gnat83 (Ada 83 Compatibility Mode)
6799 @cindex @option{-gnat83} (@command{gcc})
6800 @cindex ACVC, Ada 83 tests
6801 @cindex Ada 83 mode
6803 @noindent
6804 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6805 specifies that the program is to be compiled in Ada 83 mode. With
6806 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6807 semantics where this can be done easily.
6808 It is not possible to guarantee this switch does a perfect
6809 job; some subtle tests, such as are
6810 found in earlier ACVC tests (and that have been removed from the ACATS suite
6811 for Ada 95), might not compile correctly.
6812 Nevertheless, this switch may be useful in some circumstances, for example
6813 where, due to contractual reasons, existing code needs to be maintained
6814 using only Ada 83 features.
6816 With few exceptions (most notably the need to use @code{<>} on
6817 @cindex Generic formal parameters
6818 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6819 reserved words, and the use of packages
6820 with optional bodies), it is not necessary to specify the
6821 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6822 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6823 a correct Ada 83 program is usually also a correct program
6824 in these later versions of the language standard.
6825 For further information, please refer to @ref{Compatibility and Porting Guide}.
6827 @item -gnat95 (Ada 95 mode)
6828 @cindex @option{-gnat95} (@command{gcc})
6829 @cindex Ada 95 mode
6831 @noindent
6832 This switch directs the compiler to implement the Ada 95 version of the
6833 language.
6834 Since Ada 95 is almost completely upwards
6835 compatible with Ada 83, Ada 83 programs may generally be compiled using
6836 this switch (see the description of the @option{-gnat83} switch for further
6837 information about Ada 83 mode).
6838 If an Ada 2005 program is compiled in Ada 95 mode,
6839 uses of the new Ada 2005 features will cause error
6840 messages or warnings.
6842 This switch also can be used to cancel the effect of a previous
6843 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6844 switch earlier in the command line.
6846 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6847 @cindex @option{-gnat05} (@command{gcc})
6848 @cindex @option{-gnat2005} (@command{gcc})
6849 @cindex Ada 2005 mode
6851 @noindent
6852 This switch directs the compiler to implement the Ada 2005 version of the
6853 language, as documented in the official Ada standards document.
6854 Since Ada 2005 is almost completely upwards
6855 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6856 may generally be compiled using this switch (see the description of the
6857 @option{-gnat83} and @option{-gnat95} switches for further
6858 information).
6860 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6861 @cindex @option{-gnat12} (@command{gcc})
6862 @cindex @option{-gnat2012} (@command{gcc})
6863 @cindex Ada 2012 mode
6865 @noindent
6866 This switch directs the compiler to implement the Ada 2012 version of the
6867 language (also the default).
6868 Since Ada 2012 is almost completely upwards
6869 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6870 Ada 83 and Ada 95 programs
6871 may generally be compiled using this switch (see the description of the
6872 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6873 for further information).
6875 @item -gnatX (Enable GNAT Extensions)
6876 @cindex @option{-gnatX} (@command{gcc})
6877 @cindex Ada language extensions
6878 @cindex GNAT extensions
6880 @noindent
6881 This switch directs the compiler to implement the latest version of the
6882 language (currently Ada 2012) and also to enable certain GNAT implementation
6883 extensions that are not part of any Ada standard. For a full list of these
6884 extensions, see the GNAT reference manual.
6886 @end table
6888 @node Character Set Control
6889 @subsection Character Set Control
6890 @table @option
6891 @item -gnati@var{c}
6892 @cindex @option{-gnati} (@command{gcc})
6894 @noindent
6895 Normally GNAT recognizes the Latin-1 character set in source program
6896 identifiers, as described in the Ada Reference Manual.
6897 This switch causes
6898 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6899 single character  indicating the character set, as follows:
6901 @table @code
6902 @item 1
6903 ISO 8859-1 (Latin-1) identifiers
6905 @item 2
6906 ISO 8859-2 (Latin-2) letters allowed in identifiers
6908 @item 3
6909 ISO 8859-3 (Latin-3) letters allowed in identifiers
6911 @item 4
6912 ISO 8859-4 (Latin-4) letters allowed in identifiers
6914 @item 5
6915 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6917 @item 9
6918 ISO 8859-15 (Latin-9) letters allowed in identifiers
6920 @item p
6921 IBM PC letters (code page 437) allowed in identifiers
6923 @item 8
6924 IBM PC letters (code page 850) allowed in identifiers
6926 @item f
6927 Full upper-half codes allowed in identifiers
6929 @item n
6930 No upper-half codes allowed in identifiers
6932 @item w
6933 Wide-character codes (that is, codes greater than 255)
6934 allowed in identifiers
6935 @end table
6937 @xref{Foreign Language Representation}, for full details on the
6938 implementation of these character sets.
6940 @item -gnatW@var{e}
6941 @cindex @option{-gnatW} (@command{gcc})
6942 Specify the method of encoding for wide characters.
6943 @var{e} is one of the following:
6945 @table @code
6947 @item h
6948 Hex encoding (brackets coding also recognized)
6950 @item u
6951 Upper half encoding (brackets encoding also recognized)
6953 @item s
6954 Shift/JIS encoding (brackets encoding also recognized)
6956 @item e
6957 EUC encoding (brackets encoding also recognized)
6959 @item 8
6960 UTF-8 encoding (brackets encoding also recognized)
6962 @item b
6963 Brackets encoding only (default value)
6964 @end table
6965 For full details on these encoding
6966 methods see @ref{Wide_Character Encodings}.
6967 Note that brackets coding is always accepted, even if one of the other
6968 options is specified, so for example @option{-gnatW8} specifies that both
6969 brackets and UTF-8 encodings will be recognized. The units that are
6970 with'ed directly or indirectly will be scanned using the specified
6971 representation scheme, and so if one of the non-brackets scheme is
6972 used, it must be used consistently throughout the program. However,
6973 since brackets encoding is always recognized, it may be conveniently
6974 used in standard libraries, allowing these libraries to be used with
6975 any of the available coding schemes.
6977 Note that brackets encoding only applies to program text. Within comments,
6978 brackets are considered to be normal graphic characters, and bracket sequences
6979 are never recognized as wide characters.
6981 If no @option{-gnatW?} parameter is present, then the default
6982 representation is normally Brackets encoding only. However, if the
6983 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6984 byte order mark or BOM for UTF-8), then these three characters are
6985 skipped and the default representation for the file is set to UTF-8.
6987 Note that the wide character representation that is specified (explicitly
6988 or by default) for the main program also acts as the default encoding used
6989 for Wide_Text_IO files if not specifically overridden by a WCEM form
6990 parameter.
6992 @end table
6994 When no @option{-gnatW?} is specified, then characters (other than wide
6995 characters represented using brackets notation) are treated as 8-bit
6996 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
6997 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
6998 characters in the range 16#00#..16#1F# are not accepted in program text
6999 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7000 in program text, but allowed and ignored in comments. Note in particular
7001 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7002 as an end of line in this default mode. If your source program contains
7003 instances of the NEL character used as a line terminator,
7004 you must use UTF-8 encoding for the whole
7005 source program. In default mode, all lines must be ended by a standard
7006 end of line sequence (CR, CR/LF, or LF).
7008 Note that the convention of simply accepting all upper half characters in
7009 comments means that programs that use standard ASCII for program text, but
7010 UTF-8 encoding for comments are accepted in default mode, providing that the
7011 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7012 This is a common mode for many programs with foreign language comments.
7014 @node File Naming Control
7015 @subsection File Naming Control
7017 @table @option
7018 @item -gnatk@var{n}
7019 @cindex @option{-gnatk} (@command{gcc})
7020 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7021 1-999, indicates the maximum allowable length of a file name (not
7022 including the @file{.ads} or @file{.adb} extension). The default is not
7023 to enable file name krunching.
7025 For the source file naming rules, @xref{File Naming Rules}.
7026 @end table
7028 @node Subprogram Inlining Control
7029 @subsection Subprogram Inlining Control
7031 @table @option
7032 @c !sort!
7033 @item -gnatn[12]
7034 @cindex @option{-gnatn} (@command{gcc})
7035 The @code{n} here is intended to suggest the first syllable of the
7036 word ``inline''.
7037 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7038 inlining to actually occur, optimization must be enabled and, in order
7039 to enable inlining of subprograms specified by pragma @code{Inline},
7040 you must also specify this switch.
7041 In the absence of this switch, GNAT does not attempt
7042 inlining and does not need to access the bodies of
7043 subprograms for which @code{pragma Inline} is specified if they are not
7044 in the current unit.
7046 You can optionally specify the inlining level: 1 for moderate inlining across
7047 modules, which is a good compromise between compilation times and performances
7048 at run time, or 2 for full inlining across modules, which may bring about
7049 longer compilation times. If no inlining level is specified, the compiler will
7050 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7051 @option{-Os} and 2 for @option{-O3}.
7053 If you specify this switch the compiler will access these bodies,
7054 creating an extra source dependency for the resulting object file, and
7055 where possible, the call will be inlined.
7056 For further details on when inlining is possible
7057 see @ref{Inlining of Subprograms}.
7059 @item -gnatN
7060 @cindex @option{-gnatN} (@command{gcc})
7061 This switch activates front-end inlining which also
7062 generates additional dependencies.
7064 When using a gcc-based back end (in practice this means using any version
7065 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7066 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7067 Historically front end inlining was more extensive than the gcc back end
7068 inlining, but that is no longer the case.
7069 @end table
7071 @node Auxiliary Output Control
7072 @subsection Auxiliary Output Control
7074 @table @option
7075 @item -gnatt
7076 @cindex @option{-gnatt} (@command{gcc})
7077 @cindex Writing internal trees
7078 @cindex Internal trees, writing to file
7079 Causes GNAT to write the internal tree for a unit to a file (with the
7080 extension @file{.adt}.
7081 This not normally required, but is used by separate analysis tools.
7082 Typically
7083 these tools do the necessary compilations automatically, so you should
7084 not have to specify this switch in normal operation.
7085 Note that the combination of switches @option{-gnatct}
7086 generates a tree in the form required by ASIS applications.
7088 @item -gnatu
7089 @cindex @option{-gnatu} (@command{gcc})
7090 Print a list of units required by this compilation on @file{stdout}.
7091 The listing includes all units on which the unit being compiled depends
7092 either directly or indirectly.
7094 @item -pass-exit-codes
7095 @cindex @option{-pass-exit-codes} (@command{gcc})
7096 If this switch is not used, the exit code returned by @command{gcc} when
7097 compiling multiple files indicates whether all source files have
7098 been successfully used to generate object files or not.
7100 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7101 exit status and allows an integrated development environment to better
7102 react to a compilation failure. Those exit status are:
7104 @table @asis
7105 @item 5
7106 There was an error in at least one source file.
7107 @item 3
7108 At least one source file did not generate an object file.
7109 @item 2
7110 The compiler died unexpectedly (internal error for example).
7111 @item 0
7112 An object file has been generated for every source file.
7113 @end table
7114 @end table
7116 @node Debugging Control
7117 @subsection Debugging Control
7119 @table @option
7120 @c !sort!
7121 @cindex Debugging options
7122 @item -gnatd@var{x}
7123 @cindex @option{-gnatd} (@command{gcc})
7124 Activate internal debugging switches. @var{x} is a letter or digit, or
7125 string of letters or digits, which specifies the type of debugging
7126 outputs desired. Normally these are used only for internal development
7127 or system debugging purposes. You can find full documentation for these
7128 switches in the body of the @code{Debug} unit in the compiler source
7129 file @file{debug.adb}.
7131 @item -gnatG[=nn]
7132 @cindex @option{-gnatG} (@command{gcc})
7133 This switch causes the compiler to generate auxiliary output containing
7134 a pseudo-source listing of the generated expanded code. Like most Ada
7135 compilers, GNAT works by first transforming the high level Ada code into
7136 lower level constructs. For example, tasking operations are transformed
7137 into calls to the tasking run-time routines. A unique capability of GNAT
7138 is to list this expanded code in a form very close to normal Ada source.
7139 This is very useful in understanding the implications of various Ada
7140 usage on the efficiency of the generated code. There are many cases in
7141 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7142 generate a lot of run-time code. By using @option{-gnatG} you can identify
7143 these cases, and consider whether it may be desirable to modify the coding
7144 approach to improve efficiency.
7146 The optional parameter @code{nn} if present after -gnatG specifies an
7147 alternative maximum line length that overrides the normal default of 72.
7148 This value is in the range 40-999999, values less than 40 being silently
7149 reset to 40. The equal sign is optional.
7151 The format of the output is very similar to standard Ada source, and is
7152 easily understood by an Ada programmer. The following special syntactic
7153 additions correspond to low level features used in the generated code that
7154 do not have any exact analogies in pure Ada source form. The following
7155 is a partial list of these special constructions. See the spec
7156 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7158 If the switch @option{-gnatL} is used in conjunction with
7159 @cindex @option{-gnatL} (@command{gcc})
7160 @option{-gnatG}, then the original source lines are interspersed
7161 in the expanded source (as comment lines with the original line number).
7163 @table @code
7164 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7165 Shows the storage pool being used for an allocator.
7167 @item at end @var{procedure-name};
7168 Shows the finalization (cleanup) procedure for a scope.
7170 @item (if @var{expr} then @var{expr} else @var{expr})
7171 Conditional expression equivalent to the @code{x?y:z} construction in C.
7173 @item @var{target}^(@var{source})
7174 A conversion with floating-point truncation instead of rounding.
7176 @item @var{target}?(@var{source})
7177 A conversion that bypasses normal Ada semantic checking. In particular
7178 enumeration types and fixed-point types are treated simply as integers.
7180 @item @var{target}?^(@var{source})
7181 Combines the above two cases.
7183 @item @var{x} #/ @var{y}
7184 @itemx @var{x} #mod @var{y}
7185 @itemx @var{x} #* @var{y}
7186 @itemx @var{x} #rem @var{y}
7187 A division or multiplication of fixed-point values which are treated as
7188 integers without any kind of scaling.
7190 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7191 Shows the storage pool associated with a @code{free} statement.
7193 @item [subtype or type declaration]
7194 Used to list an equivalent declaration for an internally generated
7195 type that is referenced elsewhere in the listing.
7197 @c @item freeze @var{type-name} @ovar{actions}
7198 @c Expanding @ovar macro inline (explanation in macro def comments)
7199 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7200 Shows the point at which @var{type-name} is frozen, with possible
7201 associated actions to be performed at the freeze point.
7203 @item reference @var{itype}
7204 Reference (and hence definition) to internal type @var{itype}.
7206 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7207 Intrinsic function call.
7209 @item @var{label-name} : label
7210 Declaration of label @var{labelname}.
7212 @item #$ @var{subprogram-name}
7213 An implicit call to a run-time support routine
7214 (to meet the requirement of H.3.1(9) in a
7215 convenient manner).
7217 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7218 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7219 @var{expr}, but handled more efficiently).
7221 @item [constraint_error]
7222 Raise the @code{Constraint_Error} exception.
7224 @item @var{expression}'reference
7225 A pointer to the result of evaluating @var{expression}.
7227 @item @var{target-type}!(@var{source-expression})
7228 An unchecked conversion of @var{source-expression} to @var{target-type}.
7230 @item [@var{numerator}/@var{denominator}]
7231 Used to represent internal real literals (that) have no exact
7232 representation in base 2-16 (for example, the result of compile time
7233 evaluation of the expression 1.0/27.0).
7234 @end table
7236 @item -gnatD[=nn]
7237 @cindex @option{-gnatD} (@command{gcc})
7238 When used in conjunction with @option{-gnatG}, this switch causes
7239 the expanded source, as described above for
7240 @option{-gnatG} to be written to files with names
7241 @file{xxx.dg}, where @file{xxx} is the normal file name,
7242 instead of to the standard output file. For
7243 example, if the source file name is @file{hello.adb}, then a file
7244 @file{hello.adb.dg} will be written.  The debugging
7245 information generated by the @command{gcc} @option{-g} switch
7246 will refer to the generated @file{xxx.dg} file. This allows
7247 you to do source level debugging using the generated code which is
7248 sometimes useful for complex code, for example to find out exactly
7249 which part of a complex construction raised an exception. This switch
7250 also suppress generation of cross-reference information (see
7251 @option{-gnatx}) since otherwise the cross-reference information
7252 would refer to the @file{.dg} file, which would cause
7253 confusion since this is not the original source file.
7255 Note that @option{-gnatD} actually implies @option{-gnatG}
7256 automatically, so it is not necessary to give both options.
7257 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7259 If the switch @option{-gnatL} is used in conjunction with
7260 @cindex @option{-gnatL} (@command{gcc})
7261 @option{-gnatDG}, then the original source lines are interspersed
7262 in the expanded source (as comment lines with the original line number).
7264 The optional parameter @code{nn} if present after -gnatD specifies an
7265 alternative maximum line length that overrides the normal default of 72.
7266 This value is in the range 40-999999, values less than 40 being silently
7267 reset to 40. The equal sign is optional.
7269 @item -gnatr
7270 @cindex @option{-gnatr} (@command{gcc})
7271 @cindex pragma Restrictions
7272 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7273 so that violation of restrictions causes warnings rather than illegalities.
7274 This is useful during the development process when new restrictions are added
7275 or investigated. The switch also causes pragma Profile to be treated as
7276 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7277 restriction warnings rather than restrictions.
7279 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7280 @cindex @option{-gnatR} (@command{gcc})
7281 This switch controls output from the compiler of a listing showing
7282 representation information for declared types and objects. For
7283 @option{-gnatR0}, no information is output (equivalent to omitting
7284 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7285 so @option{-gnatR} with no parameter has the same effect), size and alignment
7286 information is listed for declared array and record types. For
7287 @option{-gnatR2}, size and alignment information is listed for all
7288 declared types and objects. The @code{Linker_Section} is also listed for any
7289 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7290 latter case occurs for objects of a type for which a @code{Linker_Section}
7291 is set).
7293 Finally @option{-gnatR3} includes symbolic
7294 expressions for values that are computed at run time for
7295 variant records. These symbolic expressions have a mostly obvious
7296 format with #n being used to represent the value of the n'th
7297 discriminant. See source files @file{repinfo.ads/adb} in the
7298 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7299 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7300 the output is to a file with the name @file{file.rep} where
7301 file is the name of the corresponding source file.
7303 @item -gnatRm[s]
7304 This form of the switch controls output of subprogram conventions
7305 and parameter passing mechanisms for all subprograms. A following
7306 @code{s} means output to a file as described above.
7308 Note that it is possible for record components to have zero size. In
7309 this case, the component clause uses an obvious extension of permitted
7310 Ada syntax, for example @code{at 0 range 0 .. -1}.
7312 Representation information requires that code be generated (since it is the
7313 code generator that lays out complex data structures). If an attempt is made
7314 to output representation information when no code is generated, for example
7315 when a subunit is compiled on its own, then no information can be generated
7316 and the compiler outputs a message to this effect.
7318 @item -gnatS
7319 @cindex @option{-gnatS} (@command{gcc})
7320 The use of the switch @option{-gnatS} for an
7321 Ada compilation will cause the compiler to output a
7322 representation of package Standard in a form very
7323 close to standard Ada. It is not quite possible to
7324 do this entirely in standard Ada (since new
7325 numeric base types cannot be created in standard
7326 Ada), but the output is easily
7327 readable to any Ada programmer, and is useful to
7328 determine the characteristics of target dependent
7329 types in package Standard.
7331 @item -gnatx
7332 @cindex @option{-gnatx} (@command{gcc})
7333 Normally the compiler generates full cross-referencing information in
7334 the @file{ALI} file. This information is used by a number of tools,
7335 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7336 suppresses this information. This saves some space and may slightly
7337 speed up compilation, but means that these tools cannot be used.
7338 @end table
7340 @node Exception Handling Control
7341 @subsection Exception Handling Control
7343 @noindent
7344 GNAT uses two methods for handling exceptions at run-time. The
7345 @code{setjmp/longjmp} method saves the context when entering
7346 a frame with an exception handler. Then when an exception is
7347 raised, the context can be restored immediately, without the
7348 need for tracing stack frames. This method provides very fast
7349 exception propagation, but introduces significant overhead for
7350 the use of exception handlers, even if no exception is raised.
7352 The other approach is called ``zero cost'' exception handling.
7353 With this method, the compiler builds static tables to describe
7354 the exception ranges. No dynamic code is required when entering
7355 a frame containing an exception handler. When an exception is
7356 raised, the tables are used to control a back trace of the
7357 subprogram invocation stack to locate the required exception
7358 handler. This method has considerably poorer performance for
7359 the propagation of exceptions, but there is no overhead for
7360 exception handlers if no exception is raised. Note that in this
7361 mode and in the context of mixed Ada and C/C++ programming,
7362 to propagate an exception through a C/C++ code, the C/C++ code
7363 must be compiled with the @option{-funwind-tables} GCC's
7364 option.
7366 The following switches may be used to control which of the
7367 two exception handling methods is used.
7369 @table @option
7370 @c !sort!
7372 @item --RTS=sjlj
7373 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7374 This switch causes the setjmp/longjmp run-time (when available) to be used
7375 for exception handling. If the default
7376 mechanism for the target is zero cost exceptions, then
7377 this switch can be used to modify this default, and must be
7378 used for all units in the partition.
7379 This option is rarely used. One case in which it may be
7380 advantageous is if you have an application where exception
7381 raising is common and the overall performance of the
7382 application is improved by favoring exception propagation.
7384 @item --RTS=zcx
7385 @cindex @option{--RTS=zcx} (@command{gnatmake})
7386 @cindex Zero Cost Exceptions
7387 This switch causes the zero cost approach to be used
7388 for exception handling. If this is the default mechanism for the
7389 target (see below), then this switch is unneeded. If the default
7390 mechanism for the target is setjmp/longjmp exceptions, then
7391 this switch can be used to modify this default, and must be
7392 used for all units in the partition.
7393 This option can only be used if the zero cost approach
7394 is available for the target in use, otherwise it will generate an error.
7395 @end table
7397 @noindent
7398 The same option @option{--RTS} must be used both for @command{gcc}
7399 and @command{gnatbind}. Passing this option to @command{gnatmake}
7400 (@pxref{Switches for gnatmake}) will ensure the required consistency
7401 through the compilation and binding steps.
7403 @node Units to Sources Mapping Files
7404 @subsection Units to Sources Mapping Files
7406 @table @option
7408 @item -gnatem=@var{path}
7409 @cindex @option{-gnatem} (@command{gcc})
7410 A mapping file is a way to communicate to the compiler two mappings:
7411 from unit names to file names (without any directory information) and from
7412 file names to path names (with full directory information). These mappings
7413 are used by the compiler to short-circuit the path search.
7415 The use of mapping files is not required for correct operation of the
7416 compiler, but mapping files can improve efficiency, particularly when
7417 sources are read over a slow network connection. In normal operation,
7418 you need not be concerned with the format or use of mapping files,
7419 and the @option{-gnatem} switch is not a switch that you would use
7420 explicitly. It is intended primarily for use by automatic tools such as
7421 @command{gnatmake} running under the project file facility. The
7422 description here of the format of mapping files is provided
7423 for completeness and for possible use by other tools.
7425 A mapping file is a sequence of sets of three lines. In each set, the
7426 first line is the unit name, in lower case, with @code{%s} appended
7427 for specs and @code{%b} appended for bodies; the second line is the
7428 file name; and the third line is the path name.
7430 Example:
7431 @smallexample
7432    main%b
7433    main.2.ada
7434    /gnat/project1/sources/main.2.ada
7435 @end smallexample
7437 When the switch @option{-gnatem} is specified, the compiler will
7438 create in memory the two mappings from the specified file. If there is
7439 any problem (nonexistent file, truncated file or duplicate entries),
7440 no mapping will be created.
7442 Several @option{-gnatem} switches may be specified; however, only the
7443 last one on the command line will be taken into account.
7445 When using a project file, @command{gnatmake} creates a temporary
7446 mapping file and communicates it to the compiler using this switch.
7448 @end table
7450 @node Integrated Preprocessing
7451 @subsection Integrated Preprocessing
7453 @noindent
7454 GNAT sources may be preprocessed immediately before compilation.
7455 In this case, the actual
7456 text of the source is not the text of the source file, but is derived from it
7457 through a process called preprocessing. Integrated preprocessing is specified
7458 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7459 indicates, through a text file, the preprocessing data to be used.
7460 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7461 Note that integrated preprocessing applies only to Ada source files, it is
7462 not available for configuration pragma files.
7464 @noindent
7465 Note that when integrated preprocessing is used, the output from the
7466 preprocessor is not written to any external file. Instead it is passed
7467 internally to the compiler. If you need to preserve the result of
7468 preprocessing in a file, then you should use @command{gnatprep}
7469 to perform the desired preprocessing in stand-alone mode.
7471 @noindent
7472 It is recommended that @command{gnatmake} switch -s should be
7473 used when Integrated Preprocessing is used. The reason is that preprocessing
7474 with another Preprocessing Data file without changing the sources will
7475 not trigger recompilation without this switch.
7477 @noindent
7478 Note that @command{gnatmake} switch -m will almost
7479 always trigger recompilation for sources that are preprocessed,
7480 because @command{gnatmake} cannot compute the checksum of the source after
7481 preprocessing.
7483 @noindent
7484 The actual preprocessing function is described in details in section
7485 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7486 preprocessing is triggered and parameterized.
7488 @table @code
7490 @item -gnatep=@var{file}
7491 @cindex @option{-gnatep} (@command{gcc})
7492 This switch indicates to the compiler the file name (without directory
7493 information) of the preprocessor data file to use. The preprocessor data file
7494 should be found in the source directories. Note that when the compiler is
7495 called by a builder such as (@command{gnatmake} with a project
7496 file, if the object directory is not also a source directory, the builder needs
7497 to be called with @option{-x}.
7499 @noindent
7500 A preprocessing data file is a text file with significant lines indicating
7501 how should be preprocessed either a specific source or all sources not
7502 mentioned in other lines. A significant line is a nonempty, non-comment line.
7503 Comments are similar to Ada comments.
7505 @noindent
7506 Each significant line starts with either a literal string or the character '*'.
7507 A literal string is the file name (without directory information) of the source
7508 to preprocess. A character '*' indicates the preprocessing for all the sources
7509 that are not specified explicitly on other lines (order of the lines is not
7510 significant). It is an error to have two lines with the same file name or two
7511 lines starting with the character '*'.
7513 @noindent
7514 After the file name or the character '*', another optional literal string
7515 indicating the file name of the definition file to be used for preprocessing
7516 (@pxref{Form of Definitions File}). The definition files are found by the
7517 compiler in one of the source directories. In some cases, when compiling
7518 a source in a directory other than the current directory, if the definition
7519 file is in the current directory, it may be necessary to add the current
7520 directory as a source directory through switch -I., otherwise
7521 the compiler would not find the definition file.
7523 @noindent
7524 Then, optionally, switches similar to those of @code{gnatprep} may
7525 be found. Those switches are:
7527 @table @code
7529 @item -b
7530 Causes both preprocessor lines and the lines deleted by
7531 preprocessing to be replaced by blank lines, preserving the line number.
7532 This switch is always implied; however, if specified after @option{-c}
7533 it cancels the effect of @option{-c}.
7535 @item -c
7536 Causes both preprocessor lines and the lines deleted
7537 by preprocessing to be retained as comments marked
7538 with the special string ``@code{--! }''.
7540 @item -Dsymbol=value
7541 Define or redefine a symbol, associated with value. A symbol is an Ada
7542 identifier, or an Ada reserved word, with the exception of @code{if},
7543 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7544 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7545 word. A symbol declared with this switch replaces a symbol with the
7546 same name defined in a definition file.
7548 @item -s
7549 Causes a sorted list of symbol names and values to be
7550 listed on the standard output file.
7552 @item -u
7553 Causes undefined symbols to be treated as having the value @code{FALSE}
7554 in the context
7555 of a preprocessor test. In the absence of this option, an undefined symbol in
7556 a @code{#if} or @code{#elsif} test will be treated as an error.
7558 @end table
7560 @noindent
7561 Examples of valid lines in a preprocessor data file:
7563 @smallexample
7564   "toto.adb"  "prep.def" -u
7565   --  preprocess "toto.adb", using definition file "prep.def",
7566   --  undefined symbol are False.
7568   * -c -DVERSION=V101
7569   --  preprocess all other sources without a definition file;
7570   --  suppressed lined are commented; symbol VERSION has the value V101.
7572   "titi.adb" "prep2.def" -s
7573   --  preprocess "titi.adb", using definition file "prep2.def";
7574   --  list all symbols with their values.
7575 @end smallexample
7577 @item -gnateDsymbol@r{[}=value@r{]}
7578 @cindex @option{-gnateD} (@command{gcc})
7579 Define or redefine a preprocessing symbol, associated with value. If no value
7580 is given on the command line, then the value of the symbol is @code{True}.
7581 A symbol is an identifier, following normal Ada (case-insensitive)
7582 rules for its syntax, and value is either an arbitrary string between double
7583 quotes or any sequence (including an empty sequence) of characters from the
7584 set (letters, digits, period, underline).
7585 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7586 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7588 @noindent
7589 Examples:
7591 @smallexample
7592    -gnateDToto=Titi
7593    -gnateDFoo
7594    -gnateDFoo=\"Foo-Bar\"
7595 @end smallexample
7597 @noindent
7598 A symbol declared with this switch on the command line replaces a
7599 symbol with the same name either in a definition file or specified with a
7600 switch -D in the preprocessor data file.
7602 @noindent
7603 This switch is similar to switch @option{-D} of @code{gnatprep}.
7605 @item -gnateG
7606 When integrated preprocessing is performed and the preprocessor modifies
7607 the source text, write the result of this preprocessing into a file
7608 <source>.prep.
7610 @end table
7612 @node Code Generation Control
7613 @subsection Code Generation Control
7615 @noindent
7617 The GCC technology provides a wide range of target dependent
7618 @option{-m} switches for controlling
7619 details of code generation with respect to different versions of
7620 architectures. This includes variations in instruction sets (e.g.@:
7621 different members of the power pc family), and different requirements
7622 for optimal arrangement of instructions (e.g.@: different members of
7623 the x86 family). The list of available @option{-m} switches may be
7624 found in the GCC documentation.
7626 Use of these @option{-m} switches may in some cases result in improved
7627 code performance.
7629 The @value{EDITION} technology is tested and qualified without any
7630 @option{-m} switches,
7631 so generally the most reliable approach is to avoid the use of these
7632 switches. However, we generally expect most of these switches to work
7633 successfully with @value{EDITION}, and many customers have reported successful
7634 use of these options.
7636 Our general advice is to avoid the use of @option{-m} switches unless
7637 special needs lead to requirements in this area. In particular,
7638 there is no point in using @option{-m} switches to improve performance
7639 unless you actually see a performance improvement.
7642 @node Search Paths and the Run-Time Library (RTL)
7643 @section Search Paths and the Run-Time Library (RTL)
7645 @noindent
7646 With the GNAT source-based library system, the compiler must be able to
7647 find source files for units that are needed by the unit being compiled.
7648 Search paths are used to guide this process.
7650 The compiler compiles one source file whose name must be given
7651 explicitly on the command line. In other words, no searching is done
7652 for this file. To find all other source files that are needed (the most
7653 common being the specs of units), the compiler examines the following
7654 directories, in the following order:
7656 @enumerate
7657 @item
7658 The directory containing the source file of the main unit being compiled
7659 (the file name on the command line).
7661 @item
7662 Each directory named by an @option{-I} switch given on the
7663 @command{gcc} command line, in the order given.
7665 @item
7666 @findex ADA_PRJ_INCLUDE_FILE
7667 Each of the directories listed in the text file whose name is given
7668 by the @env{ADA_PRJ_INCLUDE_FILE} environment variable.
7670 @noindent
7671 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
7672 driver when project files are used. It should not normally be set
7673 by other means.
7675 @item
7676 @findex ADA_INCLUDE_PATH
7677 Each of the directories listed in the value of the
7678 @env{ADA_INCLUDE_PATH} environment variable.
7679 Construct this value
7680 exactly as the @env{PATH} environment variable: a list of directory
7681 names separated by colons (semicolons when working with the NT version).
7683 @item
7684 The content of the @file{ada_source_path} file which is part of the GNAT
7685 installation tree and is used to store standard libraries such as the
7686 GNAT Run Time Library (RTL) source files.
7687 @ref{Installing a library}
7688 @end enumerate
7690 @noindent
7691 Specifying the switch @option{-I-}
7692 inhibits the use of the directory
7693 containing the source file named in the command line. You can still
7694 have this directory on your search path, but in this case it must be
7695 explicitly requested with a @option{-I} switch.
7697 Specifying the switch @option{-nostdinc}
7698 inhibits the search of the default location for the GNAT Run Time
7699 Library (RTL) source files.
7701 The compiler outputs its object files and ALI files in the current
7702 working directory.
7703 Caution: The object file can be redirected with the @option{-o} switch;
7704 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7705 so the @file{ALI} file will not go to the right place. Therefore, you should
7706 avoid using the @option{-o} switch.
7708 @findex System.IO
7709 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7710 children make up the GNAT RTL, together with the simple @code{System.IO}
7711 package used in the @code{"Hello World"} example. The sources for these units
7712 are needed by the compiler and are kept together in one directory. Not
7713 all of the bodies are needed, but all of the sources are kept together
7714 anyway. In a normal installation, you need not specify these directory
7715 names when compiling or binding. Either the environment variables or
7716 the built-in defaults cause these files to be found.
7718 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7719 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7720 consisting of child units of @code{GNAT}. This is a collection of generally
7721 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7722 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7724 Besides simplifying access to the RTL, a major use of search paths is
7725 in compiling sources from multiple directories. This can make
7726 development environments much more flexible.
7728 @node Order of Compilation Issues
7729 @section Order of Compilation Issues
7731 @noindent
7732 If, in our earlier example, there was a spec for the @code{hello}
7733 procedure, it would be contained in the file @file{hello.ads}; yet this
7734 file would not have to be explicitly compiled. This is the result of the
7735 model we chose to implement library management. Some of the consequences
7736 of this model are as follows:
7738 @itemize @bullet
7739 @item
7740 There is no point in compiling specs (except for package
7741 specs with no bodies) because these are compiled as needed by clients. If
7742 you attempt a useless compilation, you will receive an error message.
7743 It is also useless to compile subunits because they are compiled as needed
7744 by the parent.
7746 @item
7747 There are no order of compilation requirements: performing a
7748 compilation never obsoletes anything. The only way you can obsolete
7749 something and require recompilations is to modify one of the
7750 source files on which it depends.
7752 @item
7753 There is no library as such, apart from the ALI files
7754 (@pxref{The Ada Library Information Files}, for information on the format
7755 of these files). For now we find it convenient to create separate ALI files,
7756 but eventually the information therein may be incorporated into the object
7757 file directly.
7759 @item
7760 When you compile a unit, the source files for the specs of all units
7761 that it @code{with}'s, all its subunits, and the bodies of any generics it
7762 instantiates must be available (reachable by the search-paths mechanism
7763 described above), or you will receive a fatal error message.
7764 @end itemize
7766 @node Examples
7767 @section Examples
7769 @noindent
7770 The following are some typical Ada compilation command line examples:
7772 @table @code
7773 @item $ gcc -c xyz.adb
7774 Compile body in file @file{xyz.adb} with all default options.
7776 @item $ gcc -c -O2 -gnata xyz-def.adb
7778 Compile the child unit package in file @file{xyz-def.adb} with extensive
7779 optimizations, and pragma @code{Assert}/@code{Debug} statements
7780 enabled.
7782 @item $ gcc -c -gnatc abc-def.adb
7783 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7784 mode.
7785 @end table
7787 @node Binding with gnatbind
7788 @chapter Binding with @code{gnatbind}
7789 @findex gnatbind
7791 @menu
7792 * Running gnatbind::
7793 * Switches for gnatbind::
7794 * Command-Line Access::
7795 * Search Paths for gnatbind::
7796 * Examples of gnatbind Usage::
7797 @end menu
7799 @noindent
7800 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7801 to bind compiled GNAT objects.
7803 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7804 driver (see @ref{The GNAT Driver and Project Files}).
7806 The @code{gnatbind} program performs four separate functions:
7808 @enumerate
7809 @item
7810 Checks that a program is consistent, in accordance with the rules in
7811 Chapter 10 of the Ada Reference Manual. In particular, error
7812 messages are generated if a program uses inconsistent versions of a
7813 given unit.
7815 @item
7816 Checks that an acceptable order of elaboration exists for the program
7817 and issues an error message if it cannot find an order of elaboration
7818 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7820 @item
7821 Generates a main program incorporating the given elaboration order.
7822 This program is a small Ada package (body and spec) that
7823 must be subsequently compiled
7824 using the GNAT compiler. The necessary compilation step is usually
7825 performed automatically by @command{gnatlink}. The two most important
7826 functions of this program
7827 are to call the elaboration routines of units in an appropriate order
7828 and to call the main program.
7830 @item
7831 Determines the set of object files required by the given main program.
7832 This information is output in the forms of comments in the generated program,
7833 to be read by the @command{gnatlink} utility used to link the Ada application.
7834 @end enumerate
7836 @node Running gnatbind
7837 @section Running @code{gnatbind}
7839 @noindent
7840 The form of the @code{gnatbind} command is
7842 @smallexample
7843 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7844 @c Expanding @ovar macro inline (explanation in macro def comments)
7845 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7846 @end smallexample
7848 @noindent
7849 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7850 unit body. @code{gnatbind} constructs an Ada
7851 package in two files whose names are
7852 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7853 For example, if given the
7854 parameter @file{hello.ali}, for a main program contained in file
7855 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7856 and @file{b~hello.adb}.
7858 When doing consistency checking, the binder takes into consideration
7859 any source files it can locate. For example, if the binder determines
7860 that the given main program requires the package @code{Pack}, whose
7861 @file{.ALI}
7862 file is @file{pack.ali} and whose corresponding source spec file is
7863 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7864 (using the same search path conventions as previously described for the
7865 @command{gcc} command). If it can locate this source file, it checks that
7866 the time stamps
7867 or source checksums of the source and its references to in @file{ALI} files
7868 match. In other words, any @file{ALI} files that mentions this spec must have
7869 resulted from compiling this version of the source file (or in the case
7870 where the source checksums match, a version close enough that the
7871 difference does not matter).
7873 @cindex Source files, use by binder
7874 The effect of this consistency checking, which includes source files, is
7875 that the binder ensures that the program is consistent with the latest
7876 version of the source files that can be located at bind time. Editing a
7877 source file without compiling files that depend on the source file cause
7878 error messages to be generated by the binder.
7880 For example, suppose you have a main program @file{hello.adb} and a
7881 package @code{P}, from file @file{p.ads} and you perform the following
7882 steps:
7884 @enumerate
7885 @item
7886 Enter @code{gcc -c hello.adb} to compile the main program.
7888 @item
7889 Enter @code{gcc -c p.ads} to compile package @code{P}.
7891 @item
7892 Edit file @file{p.ads}.
7894 @item
7895 Enter @code{gnatbind hello}.
7896 @end enumerate
7898 @noindent
7899 At this point, the file @file{p.ali} contains an out-of-date time stamp
7900 because the file @file{p.ads} has been edited. The attempt at binding
7901 fails, and the binder generates the following error messages:
7903 @smallexample
7904 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7905 error: "p.ads" has been modified and must be recompiled
7906 @end smallexample
7908 @noindent
7909 Now both files must be recompiled as indicated, and then the bind can
7910 succeed, generating a main program. You need not normally be concerned
7911 with the contents of this file, but for reference purposes a sample
7912 binder output file is given in @ref{Example of Binder Output File}.
7914 In most normal usage, the default mode of @command{gnatbind} which is to
7915 generate the main package in Ada, as described in the previous section.
7916 In particular, this means that any Ada programmer can read and understand
7917 the generated main program. It can also be debugged just like any other
7918 Ada code provided the @option{-g} switch is used for
7919 @command{gnatbind} and @command{gnatlink}.
7921 @node Switches for gnatbind
7922 @section Switches for @command{gnatbind}
7924 @noindent
7925 The following switches are available with @code{gnatbind}; details will
7926 be presented in subsequent sections.
7928 @menu
7929 * Consistency-Checking Modes::
7930 * Binder Error Message Control::
7931 * Elaboration Control::
7932 * Output Control::
7933 * Dynamic Allocation Control::
7934 * Binding with Non-Ada Main Programs::
7935 * Binding Programs with No Main Subprogram::
7936 @end menu
7938 @table @option
7939 @c !sort!
7941 @item --version
7942 @cindex @option{--version} @command{gnatbind}
7943 Display Copyright and version, then exit disregarding all other options.
7945 @item --help
7946 @cindex @option{--help} @command{gnatbind}
7947 If @option{--version} was not used, display usage, then exit disregarding
7948 all other options.
7950 @item -a
7951 @cindex @option{-a} @command{gnatbind}
7952 Indicates that, if supported by the platform, the adainit procedure should
7953 be treated as an initialisation routine by the linker (a constructor). This
7954 is intended to be used by the Project Manager to automatically initialize
7955 shared Stand-Alone Libraries.
7957 @item -aO
7958 @cindex @option{-aO} (@command{gnatbind})
7959 Specify directory to be searched for ALI files.
7961 @item -aI
7962 @cindex @option{-aI} (@command{gnatbind})
7963 Specify directory to be searched for source file.
7965 @item -A@r{[=}@var{filename}@r{]}
7966 @cindex @option{-A} (@command{gnatbind})
7967 Output ALI list (to standard output or to the named file).
7969 @item -b
7970 @cindex @option{-b} (@command{gnatbind})
7971 Generate brief messages to @file{stderr} even if verbose mode set.
7973 @item -c
7974 @cindex @option{-c} (@command{gnatbind})
7975 Check only, no generation of binder output file.
7977 @item -d@var{nn}@r{[}k@r{|}m@r{]}
7978 @cindex @option{-d@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7979 This switch can be used to change the default task stack size value
7980 to a specified size @var{nn}, which is expressed in bytes by default, or
7981 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7982 with @var{m}.
7983 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7984 in effect, to completing all task specs with
7985 @smallexample @c ada
7986    @b{pragma} Storage_Size (nn);
7987 @end smallexample
7988 When they do not already have such a pragma.
7990 @item -D@var{nn}@r{[}k@r{|}m@r{]}
7991 @cindex @option{-D} (@command{gnatbind})
7992 This switch can be used to change the default secondary stack size value
7993 to a specified size @var{nn}, which is expressed in bytes by default, or
7994 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7995 with @var{m}.
7997 The secondary stack is used to deal with functions that return a variable
7998 sized result, for example a function returning an unconstrained
7999 String. There are two ways in which this secondary stack is allocated.
8001 For most targets, the secondary stack is growing on demand and is allocated
8002 as a chain of blocks in the heap. The -D option is not very
8003 relevant. It only give some control over the size of the allocated
8004 blocks (whose size is the minimum of the default secondary stack size value,
8005 and the actual size needed for the current allocation request).
8007 For certain targets, notably VxWorks 653,
8008 the secondary stack is allocated by carving off a fixed ratio chunk of the
8009 primary task stack. The -D option is used to define the
8010 size of the environment task's secondary stack.
8012 @item -e
8013 @cindex @option{-e} (@command{gnatbind})
8014 Output complete list of elaboration-order dependencies.
8016 @item -E
8017 @cindex @option{-E} (@command{gnatbind})
8018 Store tracebacks in exception occurrences when the target supports it.
8019 @ignore
8020 @c The following may get moved to an appendix
8021 This option is currently supported on the following targets:
8022 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8023 @end ignore
8024 See also the packages @code{GNAT.Traceback} and
8025 @code{GNAT.Traceback.Symbolic} for more information.
8026 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8027 @command{gcc} option.
8029 @item -F
8030 @cindex @option{-F} (@command{gnatbind})
8031 Force the checks of elaboration flags. @command{gnatbind} does not normally
8032 generate checks of elaboration flags for the main executable, except when
8033 a Stand-Alone Library is used. However, there are cases when this cannot be
8034 detected by gnatbind. An example is importing an interface of a Stand-Alone
8035 Library through a pragma Import and only specifying through a linker switch
8036 this Stand-Alone Library. This switch is used to guarantee that elaboration
8037 flag checks are generated.
8039 @item -h
8040 @cindex @option{-h} (@command{gnatbind})
8041 Output usage (help) information
8043 @item -H32
8044 @cindex @option{-H32} (@command{gnatbind})
8045 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8046 For further details see @ref{Dynamic Allocation Control}.
8048 @item -H64
8049 @cindex @option{-H64} (@command{gnatbind})
8050 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8051 @cindex @code{__gnat_malloc}
8052 For further details see @ref{Dynamic Allocation Control}.
8054 @item -I
8055 @cindex @option{-I} (@command{gnatbind})
8056 Specify directory to be searched for source and ALI files.
8058 @item -I-
8059 @cindex @option{-I-} (@command{gnatbind})
8060 Do not look for sources in the current directory where @code{gnatbind} was
8061 invoked, and do not look for ALI files in the directory containing the
8062 ALI file named in the @code{gnatbind} command line.
8064 @item -l
8065 @cindex @option{-l} (@command{gnatbind})
8066 Output chosen elaboration order.
8068 @item -L@var{xxx}
8069 @cindex @option{-L} (@command{gnatbind})
8070 Bind the units for library building. In this case the adainit and
8071 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8072 are renamed to @var{xxx}init and
8073 @var{xxx}final.
8074 Implies -n.
8075 (@xref{GNAT and Libraries}, for more details.)
8077 @item -Mxyz
8078 @cindex @option{-M} (@command{gnatbind})
8079 Rename generated main program from main to xyz. This option is
8080 supported on cross environments only.
8082 @item -m@var{n}
8083 @cindex @option{-m} (@command{gnatbind})
8084 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8085 in the range 1..999999. The default value if no switch is
8086 given is 9999. If the number of warnings reaches this limit, then a
8087 message is output and further warnings are suppressed, the bind
8088 continues in this case. If the number of errors reaches this
8089 limit, then a message is output and the bind is abandoned.
8090 A value of zero means that no limit is enforced. The equal
8091 sign is optional.
8093 @item -n
8094 @cindex @option{-n} (@command{gnatbind})
8095 No main program.
8097 @item -nostdinc
8098 @cindex @option{-nostdinc} (@command{gnatbind})
8099 Do not look for sources in the system default directory.
8101 @item -nostdlib
8102 @cindex @option{-nostdlib} (@command{gnatbind})
8103 Do not look for library files in the system default directory.
8105 @item --RTS=@var{rts-path}
8106 @cindex @option{--RTS} (@code{gnatbind})
8107 Specifies the default location of the runtime library. Same meaning as the
8108 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8110 @item -o @var{file}
8111 @cindex @option{-o } (@command{gnatbind})
8112 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8113 Note that if this option is used, then linking must be done manually,
8114 gnatlink cannot be used.
8116 @item -O@r{[=}@var{filename}@r{]}
8117 @cindex @option{-O} (@command{gnatbind})
8118 Output object list (to standard output or to the named file).
8120 @item -p
8121 @cindex @option{-p} (@command{gnatbind})
8122 Pessimistic (worst-case) elaboration order
8124 @item -P
8125 @cindex @option{-P} (@command{gnatbind})
8126 Generate binder file suitable for CodePeer.
8128 @item -R
8129 @cindex @option{-R} (@command{gnatbind})
8130 Output closure source list, which includes all non-run-time units that are
8131 included in the bind.
8133 @item -Ra
8134 @cindex @option{-Ra} (@command{gnatbind})
8135 Like @option{-R} but the list includes run-time units.
8137 @item -s
8138 @cindex @option{-s} (@command{gnatbind})
8139 Require all source files to be present.
8141 @item -S@var{xxx}
8142 @cindex @option{-S} (@command{gnatbind})
8143 Specifies the value to be used when detecting uninitialized scalar
8144 objects with pragma Initialize_Scalars.
8145 The @var{xxx} string specified with the switch is one of:
8146 @itemize @bullet
8148 @item ``@option{in}'' for an invalid 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 one bits. For floating-point types, a NaN value is set
8155 (see body of package System.Scalar_Values for exact values).
8157 @item ``@option{lo}'' for low value
8158 If zero is invalid for the discrete type in question,
8159 then the scalar value is set to all zero bits.
8160 For signed discrete types, the largest possible negative value of
8161 the underlying scalar is set (i.e. a one bit followed by all zero bits).
8162 For unsigned discrete types, the underlying scalar value is set to all
8163 zero bits. For floating-point, a small value is set
8164 (see body of package System.Scalar_Values for exact values).
8166 @item ``@option{hi}'' for high value
8167 If zero is invalid for the discrete type in question,
8168 then the scalar value is set to all one bits.
8169 For signed discrete types, the largest possible positive value of
8170 the underlying scalar is set (i.e. a zero bit followed by all one bits).
8171 For unsigned discrete types, the underlying scalar value is set to all
8172 one bits. For floating-point, a large value is set
8173 (see body of package System.Scalar_Values for exact values).
8175 @item ``@option{@var{xx}}'' for hex value (two hex digits)
8176 The underlying scalar is set to a value consisting of repeated bytes, whose
8177 value corresponds to the given value. For example if @option{BF} is given,
8178 then a 32-bit scalar value will be set to the bit patterm 16#BFBFBFBF#.
8179 @end itemize
8181 In addition, you can specify @option{-Sev} to indicate that the value is
8182 to be set at run time. In this case, the program will look for an environment
8183 @cindex GNAT_INIT_SCALARS
8184 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8185 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8186 If no environment variable is found, or if it does not have a valid value,
8187 then the default is @option{in} (invalid values).
8189 @item -static
8190 @cindex @option{-static} (@code{gnatbind})
8191 Link against a static GNAT run time.
8193 @item -shared
8194 @cindex @option{-shared} (@code{gnatbind})
8195 Link against a shared GNAT run time when available.
8197 @item -t
8198 @cindex @option{-t} (@code{gnatbind})
8199 Tolerate time stamp and other consistency errors
8201 @item -T@var{n}
8202 @cindex @option{-T} (@code{gnatbind})
8203 Set the time slice value to @var{n} milliseconds. If the system supports
8204 the specification of a specific time slice value, then the indicated value
8205 is used. If the system does not support specific time slice values, but
8206 does support some general notion of round-robin scheduling, then any
8207 nonzero value will activate round-robin scheduling.
8209 A value of zero is treated specially. It turns off time
8210 slicing, and in addition, indicates to the tasking run time that the
8211 semantics should match as closely as possible the Annex D
8212 requirements of the Ada RM, and in particular sets the default
8213 scheduling policy to @code{FIFO_Within_Priorities}.
8215 @item -u@var{n}
8216 @cindex @option{-u} (@code{gnatbind})
8217 Enable dynamic stack usage, with @var{n} results stored and displayed
8218 at program termination. A result is generated when a task
8219 terminates. Results that can't be stored are displayed on the fly, at
8220 task termination. This option is currently not supported on Itanium
8221 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8223 @item -v
8224 @cindex @option{-v} (@code{gnatbind})
8225 Verbose mode. Write error messages, header, summary output to
8226 @file{stdout}.
8228 @item -w@var{x}
8229 @cindex @option{-w} (@code{gnatbind})
8230 Warning mode (@var{x}=s/e for suppress/treat as error)
8233 @item -Wx@var{e}
8234 @cindex @option{-Wx} (@code{gnatbind})
8235 Override default wide character encoding for standard Text_IO files.
8237 @item -x
8238 @cindex @option{-x} (@code{gnatbind})
8239 Exclude source files (check object consistency only).
8242 @item -X@var{nnn}
8243 @cindex @option{-X@var{nnn}} (@code{gnatbind})
8244 Set default exit status value, normally 0 for POSIX compliance.
8247 @item -y
8248 @cindex @option{-y} (@code{gnatbind})
8249 Enable leap seconds support in @code{Ada.Calendar} and its children.
8251 @item -z
8252 @cindex @option{-z} (@code{gnatbind})
8253 No main subprogram.
8254 @end table
8256 @noindent
8257 You may obtain this listing of switches by running @code{gnatbind} with
8258 no arguments.
8260 @node Consistency-Checking Modes
8261 @subsection Consistency-Checking Modes
8263 @noindent
8264 As described earlier, by default @code{gnatbind} checks
8265 that object files are consistent with one another and are consistent
8266 with any source files it can locate. The following switches control binder
8267 access to sources.
8269 @table @option
8270 @c !sort!
8271 @item -s
8272 @cindex @option{-s} (@code{gnatbind})
8273 Require source files to be present. In this mode, the binder must be
8274 able to locate all source files that are referenced, in order to check
8275 their consistency. In normal mode, if a source file cannot be located it
8276 is simply ignored. If you specify this switch, a missing source
8277 file is an error.
8279 @item -Wx@var{e}
8280 @cindex @option{-Wx} (@code{gnatbind})
8281 Override default wide character encoding for standard Text_IO files.
8282 Normally the default wide character encoding method used for standard
8283 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8284 the main source input (see description of switch
8285 @option{-gnatWx} for the compiler). The
8286 use of this switch for the binder (which has the same set of
8287 possible arguments) overrides this default as specified.
8289 @item -x
8290 @cindex @option{-x} (@code{gnatbind})
8291 Exclude source files. In this mode, the binder only checks that ALI
8292 files are consistent with one another. Source files are not accessed.
8293 The binder runs faster in this mode, and there is still a guarantee that
8294 the resulting program is self-consistent.
8295 If a source file has been edited since it was last compiled, and you
8296 specify this switch, the binder will not detect that the object
8297 file is out of date with respect to the source file. Note that this is the
8298 mode that is automatically used by @command{gnatmake} because in this
8299 case the checking against sources has already been performed by
8300 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8302 @end table
8304 @node Binder Error Message Control
8305 @subsection Binder Error Message Control
8307 @noindent
8308 The following switches provide control over the generation of error
8309 messages from the binder:
8311 @table @option
8312 @c !sort!
8313 @item -v
8314 @cindex @option{-v} (@code{gnatbind})
8315 Verbose mode. In the normal mode, brief error messages are generated to
8316 @file{stderr}. If this switch is present, a header is written
8317 to @file{stdout} and any error messages are directed to @file{stdout}.
8318 All that is written to @file{stderr} is a brief summary message.
8320 @item -b
8321 @cindex @option{-b} (@code{gnatbind})
8322 Generate brief error messages to @file{stderr} even if verbose mode is
8323 specified. This is relevant only when used with the
8324 @option{-v} switch.
8326 @item -m@var{n}
8327 @cindex @option{-m} (@code{gnatbind})
8328 Limits the number of error messages to @var{n}, a decimal integer in the
8329 range 1-999. The binder terminates immediately if this limit is reached.
8331 @item -M@var{xxx}
8332 @cindex @option{-M} (@code{gnatbind})
8333 Renames the generated main program from @code{main} to @code{xxx}.
8334 This is useful in the case of some cross-building environments, where
8335 the actual main program is separate from the one generated
8336 by @code{gnatbind}.
8338 @item -ws
8339 @cindex @option{-ws} (@code{gnatbind})
8340 @cindex Warnings
8341 Suppress all warning messages.
8343 @item -we
8344 @cindex @option{-we} (@code{gnatbind})
8345 Treat any warning messages as fatal errors.
8348 @item -t
8349 @cindex @option{-t} (@code{gnatbind})
8350 @cindex Time stamp checks, in binder
8351 @cindex Binder consistency checks
8352 @cindex Consistency checks, in binder
8353 The binder performs a number of consistency checks including:
8355 @itemize @bullet
8356 @item
8357 Check that time stamps of a given source unit are consistent
8358 @item
8359 Check that checksums of a given source unit are consistent
8360 @item
8361 Check that consistent versions of @code{GNAT} were used for compilation
8362 @item
8363 Check consistency of configuration pragmas as required
8364 @end itemize
8366 @noindent
8367 Normally failure of such checks, in accordance with the consistency
8368 requirements of the Ada Reference Manual, causes error messages to be
8369 generated which abort the binder and prevent the output of a binder
8370 file and subsequent link to obtain an executable.
8372 The @option{-t} switch converts these error messages
8373 into warnings, so that
8374 binding and linking can continue to completion even in the presence of such
8375 errors. The result may be a failed link (due to missing symbols), or a
8376 non-functional executable which has undefined semantics.
8377 @emph{This means that
8378 @option{-t} should be used only in unusual situations,
8379 with extreme care.}
8380 @end table
8382 @node Elaboration Control
8383 @subsection Elaboration Control
8385 @noindent
8386 The following switches provide additional control over the elaboration
8387 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8389 @table @option
8390 @item -p
8391 @cindex @option{-p} (@code{gnatbind})
8392 Normally the binder attempts to choose an elaboration order that is
8393 likely to minimize the likelihood of an elaboration order error resulting
8394 in raising a @code{Program_Error} exception. This switch reverses the
8395 action of the binder, and requests that it deliberately choose an order
8396 that is likely to maximize the likelihood of an elaboration error.
8397 This is useful in ensuring portability and avoiding dependence on
8398 accidental fortuitous elaboration ordering.
8400 Normally it only makes sense to use the @option{-p}
8401 switch if dynamic
8402 elaboration checking is used (@option{-gnatE} switch used for compilation).
8403 This is because in the default static elaboration mode, all necessary
8404 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8405 These implicit pragmas are still respected by the binder in
8406 @option{-p} mode, so a
8407 safe elaboration order is assured.
8409 Note that @option{-p} is not intended for
8410 production use; it is more for debugging/experimental use.
8411 @end table
8413 @node Output Control
8414 @subsection Output Control
8416 @noindent
8417 The following switches allow additional control over the output
8418 generated by the binder.
8420 @table @option
8421 @c !sort!
8423 @item -c
8424 @cindex @option{-c} (@code{gnatbind})
8425 Check only. Do not generate the binder output file. In this mode the
8426 binder performs all error checks but does not generate an output file.
8428 @item -e
8429 @cindex @option{-e} (@code{gnatbind})
8430 Output complete list of elaboration-order dependencies, showing the
8431 reason for each dependency. This output can be rather extensive but may
8432 be useful in diagnosing problems with elaboration order. The output is
8433 written to @file{stdout}.
8435 @item -h
8436 @cindex @option{-h} (@code{gnatbind})
8437 Output usage information. The output is written to @file{stdout}.
8439 @item -K
8440 @cindex @option{-K} (@code{gnatbind})
8441 Output linker options to @file{stdout}. Includes library search paths,
8442 contents of pragmas Ident and Linker_Options, and libraries added
8443 by @code{gnatbind}.
8445 @item -l
8446 @cindex @option{-l} (@code{gnatbind})
8447 Output chosen elaboration order. The output is written to @file{stdout}.
8449 @item -O
8450 @cindex @option{-O} (@code{gnatbind})
8451 Output full names of all the object files that must be linked to provide
8452 the Ada component of the program. The output is written to @file{stdout}.
8453 This list includes the files explicitly supplied and referenced by the user
8454 as well as implicitly referenced run-time unit files. The latter are
8455 omitted if the corresponding units reside in shared libraries. The
8456 directory names for the run-time units depend on the system configuration.
8458 @item -o @var{file}
8459 @cindex @option{-o} (@code{gnatbind})
8460 Set name of output file to @var{file} instead of the normal
8461 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8462 binder generated body filename.
8463 Note that if this option is used, then linking must be done manually.
8464 It is not possible to use gnatlink in this case, since it cannot locate
8465 the binder file.
8467 @item -r
8468 @cindex @option{-r} (@code{gnatbind})
8469 Generate list of @code{pragma Restrictions} that could be applied to
8470 the current unit. This is useful for code audit purposes, and also may
8471 be used to improve code generation in some cases.
8473 @end table
8475 @node Dynamic Allocation Control
8476 @subsection Dynamic Allocation Control
8478 @noindent
8479 The heap control switches -- @option{-H32} and @option{-H64} --
8480 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8481 They only affect compiler-generated allocations via @code{__gnat_malloc};
8482 explicit calls to @code{malloc} and related functions from the C
8483 run-time library are unaffected.
8485 @table @option
8486 @item -H32
8487 Allocate memory on 32-bit heap
8489 @item -H64
8490 Allocate memory on 64-bit heap.  This is the default
8491 unless explicitly overridden by a @code{'Size} clause on the access type.
8492 @end table
8494 @noindent
8495 These switches are only effective on VMS platforms.
8498 @node Binding with Non-Ada Main Programs
8499 @subsection Binding with Non-Ada Main Programs
8501 @noindent
8502 In our description so far we have assumed that the main
8503 program is in Ada, and that the task of the binder is to generate a
8504 corresponding function @code{main} that invokes this Ada main
8505 program. GNAT also supports the building of executable programs where
8506 the main program is not in Ada, but some of the called routines are
8507 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8508 The following switch is used in this situation:
8510 @table @option
8511 @item -n
8512 @cindex @option{-n} (@code{gnatbind})
8513 No main program. The main program is not in Ada.
8514 @end table
8516 @noindent
8517 In this case, most of the functions of the binder are still required,
8518 but instead of generating a main program, the binder generates a file
8519 containing the following callable routines:
8521 @table @code
8522 @item adainit
8523 @findex adainit
8524 You must call this routine to initialize the Ada part of the program by
8525 calling the necessary elaboration routines. A call to @code{adainit} is
8526 required before the first call to an Ada subprogram.
8528 Note that it is assumed that the basic execution environment must be setup
8529 to be appropriate for Ada execution at the point where the first Ada
8530 subprogram is called. In particular, if the Ada code will do any
8531 floating-point operations, then the FPU must be setup in an appropriate
8532 manner. For the case of the x86, for example, full precision mode is
8533 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8534 that the FPU is in the right state.
8536 @item adafinal
8537 @findex adafinal
8538 You must call this routine to perform any library-level finalization
8539 required by the Ada subprograms. A call to @code{adafinal} is required
8540 after the last call to an Ada subprogram, and before the program
8541 terminates.
8542 @end table
8544 @noindent
8545 If the @option{-n} switch
8546 @cindex @option{-n} (@command{gnatbind})
8547 @cindex Binder, multiple input files
8548 is given, more than one ALI file may appear on
8549 the command line for @code{gnatbind}. The normal @dfn{closure}
8550 calculation is performed for each of the specified units. Calculating
8551 the closure means finding out the set of units involved by tracing
8552 @code{with} references. The reason it is necessary to be able to
8553 specify more than one ALI file is that a given program may invoke two or
8554 more quite separate groups of Ada units.
8556 The binder takes the name of its output file from the last specified ALI
8557 file, unless overridden by the use of the @option{-o file}.
8558 @cindex @option{-o} (@command{gnatbind})
8559 The output is an Ada unit in source form that can be compiled with GNAT.
8560 This compilation occurs automatically as part of the @command{gnatlink}
8561 processing.
8563 Currently the GNAT run time requires a FPU using 80 bits mode
8564 precision. Under targets where this is not the default it is required to
8565 call GNAT.Float_Control.Reset before using floating point numbers (this
8566 include float computation, float input and output) in the Ada code. A
8567 side effect is that this could be the wrong mode for the foreign code
8568 where floating point computation could be broken after this call.
8570 @node Binding Programs with No Main Subprogram
8571 @subsection Binding Programs with No Main Subprogram
8573 @noindent
8574 It is possible to have an Ada program which does not have a main
8575 subprogram. This program will call the elaboration routines of all the
8576 packages, then the finalization routines.
8578 The following switch is used to bind programs organized in this manner:
8580 @table @option
8581 @item -z
8582 @cindex @option{-z} (@code{gnatbind})
8583 Normally the binder checks that the unit name given on the command line
8584 corresponds to a suitable main subprogram. When this switch is used,
8585 a list of ALI files can be given, and the execution of the program
8586 consists of elaboration of these units in an appropriate order. Note
8587 that the default wide character encoding method for standard Text_IO
8588 files is always set to Brackets if this switch is set (you can use
8589 the binder switch
8590 @option{-Wx} to override this default).
8591 @end table
8593 @node Command-Line Access
8594 @section Command-Line Access
8596 @noindent
8597 The package @code{Ada.Command_Line} provides access to the command-line
8598 arguments and program name. In order for this interface to operate
8599 correctly, the two variables
8601 @smallexample
8602 @group
8603 int gnat_argc;
8604 char **gnat_argv;
8605 @end group
8606 @end smallexample
8608 @noindent
8609 @findex gnat_argv
8610 @findex gnat_argc
8611 are declared in one of the GNAT library routines. These variables must
8612 be set from the actual @code{argc} and @code{argv} values passed to the
8613 main program. With no @option{n} present, @code{gnatbind}
8614 generates the C main program to automatically set these variables.
8615 If the @option{n} switch is used, there is no automatic way to
8616 set these variables. If they are not set, the procedures in
8617 @code{Ada.Command_Line} will not be available, and any attempt to use
8618 them will raise @code{Constraint_Error}. If command line access is
8619 required, your main program must set @code{gnat_argc} and
8620 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8623 @node Search Paths for gnatbind
8624 @section Search Paths for @code{gnatbind}
8626 @noindent
8627 The binder takes the name of an ALI file as its argument and needs to
8628 locate source files as well as other ALI files to verify object consistency.
8630 For source files, it follows exactly the same search rules as @command{gcc}
8631 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8632 directories searched are:
8634 @enumerate
8635 @item
8636 The directory containing the ALI file named in the command line, unless
8637 the switch @option{-I-} is specified.
8639 @item
8640 All directories specified by @option{-I}
8641 switches on the @code{gnatbind}
8642 command line, in the order given.
8644 @item
8645 @findex ADA_PRJ_OBJECTS_FILE
8646 Each of the directories listed in the text file whose name is given
8647 by the @env{ADA_PRJ_OBJECTS_FILE} environment variable.
8649 @noindent
8650 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
8651 driver when project files are used. It should not normally be set
8652 by other means.
8654 @item
8655 @findex ADA_OBJECTS_PATH
8656 Each of the directories listed in the value of the
8657 @env{ADA_OBJECTS_PATH} environment variable.
8658 Construct this value
8659 exactly as the @env{PATH} environment variable: a list of directory
8660 names separated by colons (semicolons when working with the NT version
8661 of GNAT).
8663 @item
8664 The content of the @file{ada_object_path} file which is part of the GNAT
8665 installation tree and is used to store standard libraries such as the
8666 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8667 specified.
8668 @ref{Installing a library}
8669 @end enumerate
8671 @noindent
8672 In the binder the switch @option{-I}
8673 @cindex @option{-I} (@command{gnatbind})
8674 is used to specify both source and
8675 library file paths. Use @option{-aI}
8676 @cindex @option{-aI} (@command{gnatbind})
8677 instead if you want to specify
8678 source paths only, and @option{-aO}
8679 @cindex @option{-aO} (@command{gnatbind})
8680 if you want to specify library paths
8681 only. This means that for the binder
8682 @option{-I}@var{dir} is equivalent to
8683 @option{-aI}@var{dir}
8684 @option{-aO}@var{dir}.
8685 The binder generates the bind file (a C language source file) in the
8686 current working directory.
8688 @findex Ada
8689 @findex System
8690 @findex Interfaces
8691 @findex GNAT
8692 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8693 children make up the GNAT Run-Time Library, together with the package
8694 GNAT and its children, which contain a set of useful additional
8695 library functions provided by GNAT. The sources for these units are
8696 needed by the compiler and are kept together in one directory. The ALI
8697 files and object files generated by compiling the RTL are needed by the
8698 binder and the linker and are kept together in one directory, typically
8699 different from the directory containing the sources. In a normal
8700 installation, you need not specify these directory names when compiling
8701 or binding. Either the environment variables or the built-in defaults
8702 cause these files to be found.
8704 Besides simplifying access to the RTL, a major use of search paths is
8705 in compiling sources from multiple directories. This can make
8706 development environments much more flexible.
8708 @node Examples of gnatbind Usage
8709 @section Examples of @code{gnatbind} Usage
8711 @noindent
8712 This section contains a number of examples of using the GNAT binding
8713 utility @code{gnatbind}.
8715 @table @code
8716 @item gnatbind hello
8717 The main program @code{Hello} (source program in @file{hello.adb}) is
8718 bound using the standard switch settings. The generated main program is
8719 @file{b~hello.adb}. This is the normal, default use of the binder.
8721 @item gnatbind hello -o mainprog.adb
8722 The main program @code{Hello} (source program in @file{hello.adb}) is
8723 bound using the standard switch settings. The generated main program is
8724 @file{mainprog.adb} with the associated spec in
8725 @file{mainprog.ads}. Note that you must specify the body here not the
8726 spec. Note that if this option is used, then linking must be done manually,
8727 since gnatlink will not be able to find the generated file.
8728 @end table
8730 @c ------------------------------------
8731 @node Linking with gnatlink
8732 @chapter Linking with @command{gnatlink}
8733 @c ------------------------------------
8734 @findex gnatlink
8736 @noindent
8737 This chapter discusses @command{gnatlink}, a tool that links
8738 an Ada program and builds an executable file. This utility
8739 invokes the system linker (via the @command{gcc} command)
8740 with a correct list of object files and library references.
8741 @command{gnatlink} automatically determines the list of files and
8742 references for the Ada part of a program. It uses the binder file
8743 generated by the @command{gnatbind} to determine this list.
8745 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8746 driver (see @ref{The GNAT Driver and Project Files}).
8748 @menu
8749 * Running gnatlink::
8750 * Switches for gnatlink::
8751 @end menu
8753 @node Running gnatlink
8754 @section Running @command{gnatlink}
8756 @noindent
8757 The form of the @command{gnatlink} command is
8759 @smallexample
8760 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8761 @c            @ovar{non-Ada objects} @ovar{linker options}
8762 @c Expanding @ovar macro inline (explanation in macro def comments)
8763 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8764            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8766 @end smallexample
8768 @noindent
8769 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8770 non-Ada objects
8771 or linker options) may be in any order, provided that no non-Ada object may
8772 be mistaken for a main @file{ALI} file.
8773 Any file name @file{F} without the @file{.ali}
8774 extension will be taken as the main @file{ALI} file if a file exists
8775 whose name is the concatenation of @file{F} and @file{.ali}.
8777 @noindent
8778 @file{@var{mainprog}.ali} references the ALI file of the main program.
8779 The @file{.ali} extension of this file can be omitted. From this
8780 reference, @command{gnatlink} locates the corresponding binder file
8781 @file{b~@var{mainprog}.adb} and, using the information in this file along
8782 with the list of non-Ada objects and linker options, constructs a
8783 linker command file to create the executable.
8785 The arguments other than the @command{gnatlink} switches and the main
8786 @file{ALI} file are passed to the linker uninterpreted.
8787 They typically include the names of
8788 object files for units written in other languages than Ada and any library
8789 references required to resolve references in any of these foreign language
8790 units, or in @code{Import} pragmas in any Ada units.
8792 @var{linker options} is an optional list of linker specific
8793 switches.
8794 The default linker called by gnatlink is @command{gcc} which in
8795 turn calls the appropriate system linker.
8797 One useful option for the linker is @option{-s}: it reduces the size of the
8798 executable by removing all symbol table and relocation information from the
8799 executable.
8801 Standard options for the linker such as @option{-lmy_lib} or
8802 @option{-Ldir} can be added as is.
8803 For options that are not recognized by
8804 @command{gcc} as linker options, use the @command{gcc} switches
8805 @option{-Xlinker} or @option{-Wl,}.
8807 Refer to the GCC documentation for
8808 details.
8810 Here is an example showing how to generate a linker map:
8812 @smallexample
8813 $ gnatlink my_prog -Wl,-Map,MAPFILE
8814 @end smallexample
8816 Using @var{linker options} it is possible to set the program stack and
8817 heap size.
8818 See @ref{Setting Stack Size from gnatlink} and
8819 @ref{Setting Heap Size from gnatlink}.
8821 @command{gnatlink} determines the list of objects required by the Ada
8822 program and prepends them to the list of objects passed to the linker.
8823 @command{gnatlink} also gathers any arguments set by the use of
8824 @code{pragma Linker_Options} and adds them to the list of arguments
8825 presented to the linker.
8828 @node Switches for gnatlink
8829 @section Switches for @command{gnatlink}
8831 @noindent
8832 The following switches are available with the @command{gnatlink} utility:
8834 @table @option
8835 @c !sort!
8837 @item --version
8838 @cindex @option{--version} @command{gnatlink}
8839 Display Copyright and version, then exit disregarding all other options.
8841 @item --help
8842 @cindex @option{--help} @command{gnatlink}
8843 If @option{--version} was not used, display usage, then exit disregarding
8844 all other options.
8846 @item -f
8847 @cindex Command line length
8848 @cindex @option{-f} (@command{gnatlink})
8849 On some targets, the command line length is limited, and @command{gnatlink}
8850 will generate a separate file for the linker if the list of object files
8851 is too long.
8852 The @option{-f} switch forces this file
8853 to be generated even if
8854 the limit is not exceeded. This is useful in some cases to deal with
8855 special situations where the command line length is exceeded.
8857 @item -g
8858 @cindex Debugging information, including
8859 @cindex @option{-g} (@command{gnatlink})
8860 The option to include debugging information causes the Ada bind file (in
8861 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8862 @option{-g}.
8863 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8864 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8865 Without @option{-g}, the binder removes these files by
8866 default. The same procedure apply if a C bind file was generated using
8867 @option{-C} @code{gnatbind} option, in this case the filenames
8868 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8870 @item -n
8871 @cindex @option{-n} (@command{gnatlink})
8872 Do not compile the file generated by the binder. This may be used when
8873 a link is rerun with different options, but there is no need to recompile
8874 the binder file.
8876 @item -v
8877 @cindex @option{-v} (@command{gnatlink})
8878 Causes additional information to be output, including a full list of the
8879 included object files. This switch option is most useful when you want
8880 to see what set of object files are being used in the link step.
8882 @item -v -v
8883 @cindex @option{-v -v} (@command{gnatlink})
8884 Very verbose mode. Requests that the compiler operate in verbose mode when
8885 it compiles the binder file, and that the system linker run in verbose mode.
8887 @item -o @var{exec-name}
8888 @cindex @option{-o} (@command{gnatlink})
8889 @var{exec-name} specifies an alternate name for the generated
8890 executable program. If this switch is omitted, the executable has the same
8891 name as the main unit. For example, @code{gnatlink try.ali} creates
8892 an executable called @file{try}.
8894 @item -b @var{target}
8895 @cindex @option{-b} (@command{gnatlink})
8896 Compile your program to run on @var{target}, which is the name of a
8897 system configuration. You must have a GNAT cross-compiler built if
8898 @var{target} is not the same as your host system.
8900 @item -B@var{dir}
8901 @cindex @option{-B} (@command{gnatlink})
8902 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8903 from @var{dir} instead of the default location. Only use this switch
8904 when multiple versions of the GNAT compiler are available.
8905 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8906 for further details. You would normally use the @option{-b} or
8907 @option{-V} switch instead.
8909 @item -M
8910 When linking an executable, create a map file. The name of the map file
8911 has the same name as the executable with extension ".map".
8913 @item -M=mapfile
8914 When linking an executable, create a map file. The name of the map file is
8915 "mapfile".
8917 @item --GCC=@var{compiler_name}
8918 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8919 Program used for compiling the binder file. The default is
8920 @command{gcc}. You need to use quotes around @var{compiler_name} if
8921 @code{compiler_name} contains spaces or other separator characters.
8922 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8923 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8924 inserted after your command name. Thus in the above example the compiler
8925 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8926 A limitation of this syntax is that the name and path name of the executable
8927 itself must not include any embedded spaces. If the compiler executable is
8928 different from the default one (gcc or <prefix>-gcc), then the back-end
8929 switches in the ALI file are not used to compile the binder generated source.
8930 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8931 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8932 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8933 is taken into account. However, all the additional switches are also taken
8934 into account. Thus,
8935 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8936 @option{--GCC="bar -x -y -z -t"}.
8938 @item --LINK=@var{name}
8939 @cindex @option{--LINK=} (@command{gnatlink})
8940 @var{name} is the name of the linker to be invoked. This is especially
8941 useful in mixed language programs since languages such as C++ require
8942 their own linker to be used. When this switch is omitted, the default
8943 name for the linker is @command{gcc}. When this switch is used, the
8944 specified linker is called instead of @command{gcc} with exactly the same
8945 parameters that would have been passed to @command{gcc} so if the desired
8946 linker requires different parameters it is necessary to use a wrapper
8947 script that massages the parameters before invoking the real linker. It
8948 may be useful to control the exact invocation by using the verbose
8949 switch.
8953 @end table
8955 @node The GNAT Make Program gnatmake
8956 @chapter The GNAT Make Program @command{gnatmake}
8957 @findex gnatmake
8959 @menu
8960 * Running gnatmake::
8961 * Switches for gnatmake::
8962 * Mode Switches for gnatmake::
8963 * Notes on the Command Line::
8964 * How gnatmake Works::
8965 * Examples of gnatmake Usage::
8966 @end menu
8967 @noindent
8968 A typical development cycle when working on an Ada program consists of
8969 the following steps:
8971 @enumerate
8972 @item
8973 Edit some sources to fix bugs.
8975 @item
8976 Add enhancements.
8978 @item
8979 Compile all sources affected.
8981 @item
8982 Rebind and relink.
8984 @item
8985 Test.
8986 @end enumerate
8988 @noindent
8989 The third step can be tricky, because not only do the modified files
8990 @cindex Dependency rules
8991 have to be compiled, but any files depending on these files must also be
8992 recompiled. The dependency rules in Ada can be quite complex, especially
8993 in the presence of overloading, @code{use} clauses, generics and inlined
8994 subprograms.
8996 @command{gnatmake} automatically takes care of the third and fourth steps
8997 of this process. It determines which sources need to be compiled,
8998 compiles them, and binds and links the resulting object files.
9000 Unlike some other Ada make programs, the dependencies are always
9001 accurately recomputed from the new sources. The source based approach of
9002 the GNAT compilation model makes this possible. This means that if
9003 changes to the source program cause corresponding changes in
9004 dependencies, they will always be tracked exactly correctly by
9005 @command{gnatmake}.
9007 @node Running gnatmake
9008 @section Running @command{gnatmake}
9010 @noindent
9011 The usual form of the @command{gnatmake} command is
9013 @smallexample
9014 @c $ gnatmake @ovar{switches} @var{file_name}
9015 @c       @ovar{file_names} @ovar{mode_switches}
9016 @c Expanding @ovar macro inline (explanation in macro def comments)
9017 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9018       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9019 @end smallexample
9021 @noindent
9022 The only required argument is one @var{file_name}, which specifies
9023 a compilation unit that is a main program. Several @var{file_names} can be
9024 specified: this will result in several executables being built.
9025 If @code{switches} are present, they can be placed before the first
9026 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9027 If @var{mode_switches} are present, they must always be placed after
9028 the last @var{file_name} and all @code{switches}.
9030 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9031 extension may be omitted from the @var{file_name} arguments. However, if
9032 you are using non-standard extensions, then it is required that the
9033 extension be given. A relative or absolute directory path can be
9034 specified in a @var{file_name}, in which case, the input source file will
9035 be searched for in the specified directory only. Otherwise, the input
9036 source file will first be searched in the directory where
9037 @command{gnatmake} was invoked and if it is not found, it will be search on
9038 the source path of the compiler as described in
9039 @ref{Search Paths and the Run-Time Library (RTL)}.
9041 All @command{gnatmake} output (except when you specify
9042 @option{-M}) is to
9043 @file{stderr}. The output produced by the
9044 @option{-M} switch is send to
9045 @file{stdout}.
9047 @node Switches for gnatmake
9048 @section Switches for @command{gnatmake}
9050 @noindent
9051 You may specify any of the following switches to @command{gnatmake}:
9053 @table @option
9054 @c !sort!
9056 @item --version
9057 @cindex @option{--version} @command{gnatmake}
9058 Display Copyright and version, then exit disregarding all other options.
9060 @item --help
9061 @cindex @option{--help} @command{gnatmake}
9062 If @option{--version} was not used, display usage, then exit disregarding
9063 all other options.
9065 @item --GCC=@var{compiler_name}
9066 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9067 Program used for compiling. The default is `@command{gcc}'. You need to use
9068 quotes around @var{compiler_name} if @code{compiler_name} contains
9069 spaces or other separator characters. As an example @option{--GCC="foo -x
9070 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9071 compiler. A limitation of this syntax is that the name and path name of
9072 the executable itself must not include any embedded spaces. Note that
9073 switch @option{-c} is always inserted after your command name. Thus in the
9074 above example the compiler command that will be used by @command{gnatmake}
9075 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9076 used, only the last @var{compiler_name} is taken into account. However,
9077 all the additional switches are also taken into account. Thus,
9078 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9079 @option{--GCC="bar -x -y -z -t"}.
9081 @item --GNATBIND=@var{binder_name}
9082 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9083 Program used for binding. The default is `@code{gnatbind}'. You need to
9084 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9085 or other separator characters. As an example @option{--GNATBIND="bar -x
9086 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9087 binder. Binder switches that are normally appended by @command{gnatmake}
9088 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9089 A limitation of this syntax is that the name and path name of the executable
9090 itself must not include any embedded spaces.
9092 @item --GNATLINK=@var{linker_name}
9093 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9094 Program used for linking. The default is `@command{gnatlink}'. You need to
9095 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9096 or other separator characters. As an example @option{--GNATLINK="lan -x
9097 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9098 linker. Linker switches that are normally appended by @command{gnatmake} to
9099 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9100 A limitation of this syntax is that the name and path name of the executable
9101 itself must not include any embedded spaces.
9104 @item --subdirs=subdir
9105 Actual object directory of each project file is the subdirectory subdir of the
9106 object directory specified or defaulted in the project file.
9108 @item --single-compile-per-obj-dir
9109 Disallow simultaneous compilations in the same object directory when
9110 project files are used.
9112 @item --unchecked-shared-lib-imports
9113 By default, shared library projects are not allowed to import static library
9114 projects. When this switch is used on the command line, this restriction is
9115 relaxed.
9117 @item --source-info=<source info file>
9118 Specify a source info file. This switch is active only when project files
9119 are used. If the source info file is specified as a relative path, then it is
9120 relative to the object directory of the main project. If the source info file
9121 does not exist, then after the Project Manager has successfully parsed and
9122 processed the project files and found the sources, it creates the source info
9123 file. If the source info file already exists and can be read successfully,
9124 then the Project Manager will get all the needed information about the sources
9125 from the source info file and will not look for them. This reduces the time
9126 to process the project files, especially when looking for sources that take a
9127 long time. If the source info file exists but cannot be parsed successfully,
9128 the Project Manager will attempt to recreate it. If the Project Manager fails
9129 to create the source info file, a message is issued, but gnatmake does not
9130 fail. @command{gnatmake} "trusts" the source info file. This means that
9131 if the source files have changed (addition, deletion, moving to a different
9132 source directory), then the source info file need to be deleted and recreated.
9134 @item --create-map-file
9135 When linking an executable, create a map file. The name of the map file
9136 has the same name as the executable with extension ".map".
9138 @item --create-map-file=mapfile
9139 When linking an executable, create a map file. The name of the map file is
9140 "mapfile".
9143 @item -a
9144 @cindex @option{-a} (@command{gnatmake})
9145 Consider all files in the make process, even the GNAT internal system
9146 files (for example, the predefined Ada library files), as well as any
9147 locked files. Locked files are files whose ALI file is write-protected.
9148 By default,
9149 @command{gnatmake} does not check these files,
9150 because the assumption is that the GNAT internal files are properly up
9151 to date, and also that any write protected ALI files have been properly
9152 installed. Note that if there is an installation problem, such that one
9153 of these files is not up to date, it will be properly caught by the
9154 binder.
9155 You may have to specify this switch if you are working on GNAT
9156 itself. The switch @option{-a} is also useful
9157 in conjunction with @option{-f}
9158 if you need to recompile an entire application,
9159 including run-time files, using special configuration pragmas,
9160 such as a @code{Normalize_Scalars} pragma.
9162 By default
9163 @code{gnatmake -a} compiles all GNAT
9164 internal files with
9165 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9167 @item -b
9168 @cindex @option{-b} (@command{gnatmake})
9169 Bind only. Can be combined with @option{-c} to do
9170 compilation and binding, but no link.
9171 Can be combined with @option{-l}
9172 to do binding and linking. When not combined with
9173 @option{-c}
9174 all the units in the closure of the main program must have been previously
9175 compiled and must be up to date. The root unit specified by @var{file_name}
9176 may be given without extension, with the source extension or, if no GNAT
9177 Project File is specified, with the ALI file extension.
9179 @item -c
9180 @cindex @option{-c} (@command{gnatmake})
9181 Compile only. Do not perform binding, except when @option{-b}
9182 is also specified. Do not perform linking, except if both
9183 @option{-b} and
9184 @option{-l} are also specified.
9185 If the root unit specified by @var{file_name} is not a main unit, this is the
9186 default. Otherwise @command{gnatmake} will attempt binding and linking
9187 unless all objects are up to date and the executable is more recent than
9188 the objects.
9190 @item -C
9191 @cindex @option{-C} (@command{gnatmake})
9192 Use a temporary mapping file. A mapping file is a way to communicate
9193 to the compiler two mappings: from unit names to file names (without
9194 any directory information) and from file names to path names (with
9195 full directory information). A mapping file can make the compiler's
9196 file searches faster, especially if there are many source directories,
9197 or the sources are read over a slow network connection. If
9198 @option{-P} is used, a mapping file is always used, so
9199 @option{-C} is unnecessary; in this case the mapping file
9200 is initially populated based on the project file. If
9201 @option{-C} is used without
9202 @option{-P},
9203 the mapping file is initially empty. Each invocation of the compiler
9204 will add any newly accessed sources to the mapping file.
9206 @item -C=@var{file}
9207 @cindex @option{-C=} (@command{gnatmake})
9208 Use a specific mapping file. The file, specified as a path name (absolute or
9209 relative) by this switch, should already exist, otherwise the switch is
9210 ineffective. The specified mapping file will be communicated to the compiler.
9211 This switch is not compatible with a project file
9212 (-P@var{file}) or with multiple compiling processes
9213 (-jnnn, when nnn is greater than 1).
9215 @item -d
9216 @cindex @option{-d} (@command{gnatmake})
9217 Display progress for each source, up to date or not, as a single line
9219 @smallexample
9220 completed x out of y (zz%)
9221 @end smallexample
9223 If the file needs to be compiled this is displayed after the invocation of
9224 the compiler. These lines are displayed even in quiet output mode.
9226 @item -D @var{dir}
9227 @cindex @option{-D} (@command{gnatmake})
9228 Put all object files and ALI file in directory @var{dir}.
9229 If the @option{-D} switch is not used, all object files
9230 and ALI files go in the current working directory.
9232 This switch cannot be used when using a project file.
9234 @item -eInnn
9235 @cindex @option{-eI} (@command{gnatmake})
9236 Indicates that the main source is a multi-unit source and the rank of the unit
9237 in the source file is nnn. nnn needs to be a positive number and a valid
9238 index in the source. This switch cannot be used when @command{gnatmake} is
9239 invoked for several mains.
9241 @item -eL
9242 @cindex @option{-eL} (@command{gnatmake})
9243 @cindex symbolic links
9244 Follow all symbolic links when processing project files.
9245 This should be used if your project uses symbolic links for files or
9246 directories, but is not needed in other cases.
9248 @cindex naming scheme
9249 This also assumes that no directory matches the naming scheme for files (for
9250 instance that you do not have a directory called "sources.ads" when using the
9251 default GNAT naming scheme).
9253 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9254 save a lot of system calls (several per source file and object file), which
9255 can result in a significant speed up to load and manipulate a project file,
9256 especially when using source files from a remote system.
9259 @item -eS
9260 @cindex @option{-eS} (@command{gnatmake})
9261 Output the commands for the compiler, the binder and the linker
9262 on standard output,
9263 instead of standard error.
9265 @item -f
9266 @cindex @option{-f} (@command{gnatmake})
9267 Force recompilations. Recompile all sources, even though some object
9268 files may be up to date, but don't recompile predefined or GNAT internal
9269 files or locked files (files with a write-protected ALI file),
9270 unless the @option{-a} switch is also specified.
9272 @item -F
9273 @cindex @option{-F} (@command{gnatmake})
9274 When using project files, if some errors or warnings are detected during
9275 parsing and verbose mode is not in effect (no use of switch
9276 -v), then error lines start with the full path name of the project
9277 file, rather than its simple file name.
9279 @item -g
9280 @cindex @option{-g} (@command{gnatmake})
9281 Enable debugging. This switch is simply passed to the compiler and to the
9282 linker.
9284 @item -i
9285 @cindex @option{-i} (@command{gnatmake})
9286 In normal mode, @command{gnatmake} compiles all object files and ALI files
9287 into the current directory. If the @option{-i} switch is used,
9288 then instead object files and ALI files that already exist are overwritten
9289 in place. This means that once a large project is organized into separate
9290 directories in the desired manner, then @command{gnatmake} will automatically
9291 maintain and update this organization. If no ALI files are found on the
9292 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9293 the new object and ALI files are created in the
9294 directory containing the source being compiled. If another organization
9295 is desired, where objects and sources are kept in different directories,
9296 a useful technique is to create dummy ALI files in the desired directories.
9297 When detecting such a dummy file, @command{gnatmake} will be forced to
9298 recompile the corresponding source file, and it will be put the resulting
9299 object and ALI files in the directory where it found the dummy file.
9301 @item -j@var{n}
9302 @cindex @option{-j} (@command{gnatmake})
9303 @cindex Parallel make
9304 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9305 machine compilations will occur in parallel. If @var{n} is 0, then the
9306 maximum number of parallel compilations is the number of core processors
9307 on the platform. In the event of compilation errors, messages from various
9308 compilations might get interspersed (but @command{gnatmake} will give you the
9309 full ordered list of failing compiles at the end). If this is problematic,
9310 rerun the make process with n set to 1 to get a clean list of messages.
9312 @item -k
9313 @cindex @option{-k} (@command{gnatmake})
9314 Keep going. Continue as much as possible after a compilation error. To
9315 ease the programmer's task in case of compilation errors, the list of
9316 sources for which the compile fails is given when @command{gnatmake}
9317 terminates.
9319 If @command{gnatmake} is invoked with several @file{file_names} and with this
9320 switch, if there are compilation errors when building an executable,
9321 @command{gnatmake} will not attempt to build the following executables.
9323 @item -l
9324 @cindex @option{-l} (@command{gnatmake})
9325 Link only. Can be combined with @option{-b} to binding
9326 and linking. Linking will not be performed if combined with
9327 @option{-c}
9328 but not with @option{-b}.
9329 When not combined with @option{-b}
9330 all the units in the closure of the main program must have been previously
9331 compiled and must be up to date, and the main program needs to have been bound.
9332 The root unit specified by @var{file_name}
9333 may be given without extension, with the source extension or, if no GNAT
9334 Project File is specified, with the ALI file extension.
9336 @item -m
9337 @cindex @option{-m} (@command{gnatmake})
9338 Specify that the minimum necessary amount of recompilations
9339 be performed. In this mode @command{gnatmake} ignores time
9340 stamp differences when the only
9341 modifications to a source file consist in adding/removing comments,
9342 empty lines, spaces or tabs. This means that if you have changed the
9343 comments in a source file or have simply reformatted it, using this
9344 switch will tell @command{gnatmake} not to recompile files that depend on it
9345 (provided other sources on which these files depend have undergone no
9346 semantic modifications). Note that the debugging information may be
9347 out of date with respect to the sources if the @option{-m} switch causes
9348 a compilation to be switched, so the use of this switch represents a
9349 trade-off between compilation time and accurate debugging information.
9351 @item -M
9352 @cindex Dependencies, producing list
9353 @cindex @option{-M} (@command{gnatmake})
9354 Check if all objects are up to date. If they are, output the object
9355 dependences to @file{stdout} in a form that can be directly exploited in
9356 a @file{Makefile}. By default, each source file is prefixed with its
9357 (relative or absolute) directory name. This name is whatever you
9358 specified in the various @option{-aI}
9359 and @option{-I} switches. If you use
9360 @code{gnatmake -M}
9361 @option{-q}
9362 (see below), only the source file names,
9363 without relative paths, are output. If you just specify the
9364 @option{-M}
9365 switch, dependencies of the GNAT internal system files are omitted. This
9366 is typically what you want. If you also specify
9367 the @option{-a} switch,
9368 dependencies of the GNAT internal files are also listed. Note that
9369 dependencies of the objects in external Ada libraries (see switch
9370 @option{-aL}@var{dir} in the following list)
9371 are never reported.
9373 @item -n
9374 @cindex @option{-n} (@command{gnatmake})
9375 Don't compile, bind, or link. Checks if all objects are up to date.
9376 If they are not, the full name of the first file that needs to be
9377 recompiled is printed.
9378 Repeated use of this option, followed by compiling the indicated source
9379 file, will eventually result in recompiling all required units.
9381 @item -o @var{exec_name}
9382 @cindex @option{-o} (@command{gnatmake})
9383 Output executable name. The name of the final executable program will be
9384 @var{exec_name}. If the @option{-o} switch is omitted the default
9385 name for the executable will be the name of the input file in appropriate form
9386 for an executable file on the host system.
9388 This switch cannot be used when invoking @command{gnatmake} with several
9389 @file{file_names}.
9391 @item -p or --create-missing-dirs
9392 @cindex @option{-p} (@command{gnatmake})
9393 When using project files (-P@var{project}), create
9394 automatically missing object directories, library directories and exec
9395 directories.
9397 @item -P@var{project}
9398 @cindex @option{-P} (@command{gnatmake})
9399 Use project file @var{project}. Only one such switch can be used.
9400 @xref{gnatmake and Project Files}.
9402 @item -q
9403 @cindex @option{-q} (@command{gnatmake})
9404 Quiet. When this flag is not set, the commands carried out by
9405 @command{gnatmake} are displayed.
9407 @item -s
9408 @cindex @option{-s} (@command{gnatmake})
9409 Recompile if compiler switches have changed since last compilation.
9410 All compiler switches but -I and -o are taken into account in the
9411 following way:
9412 orders between different ``first letter'' switches are ignored, but
9413 orders between same switches are taken into account. For example,
9414 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9415 is equivalent to @option{-O -g}.
9417 This switch is recommended when Integrated Preprocessing is used.
9419 @item -u
9420 @cindex @option{-u} (@command{gnatmake})
9421 Unique. Recompile at most the main files. It implies -c. Combined with
9422 -f, it is equivalent to calling the compiler directly. Note that using
9423 -u with a project file and no main has a special meaning
9424 (@pxref{Project Files and Main Subprograms}).
9426 @item -U
9427 @cindex @option{-U} (@command{gnatmake})
9428 When used without a project file or with one or several mains on the command
9429 line, is equivalent to -u. When used with a project file and no main
9430 on the command line, all sources of all project files are checked and compiled
9431 if not up to date, and libraries are rebuilt, if necessary.
9433 @item -v
9434 @cindex @option{-v} (@command{gnatmake})
9435 Verbose. Display the reason for all recompilations @command{gnatmake}
9436 decides are necessary, with the highest verbosity level.
9438 @item -vl
9439 @cindex @option{-vl} (@command{gnatmake})
9440 Verbosity level Low. Display fewer lines than in verbosity Medium.
9442 @item -vm
9443 @cindex @option{-vm} (@command{gnatmake})
9444 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9446 @item -vh
9447 @cindex @option{-vm} (@command{gnatmake})
9448 Verbosity level High. Equivalent to -v.
9450 @item -vP@emph{x}
9451 Indicate the verbosity of the parsing of GNAT project files.
9452 @xref{Switches Related to Project Files}.
9454 @item -x
9455 @cindex @option{-x} (@command{gnatmake})
9456 Indicate that sources that are not part of any Project File may be compiled.
9457 Normally, when using Project Files, only sources that are part of a Project
9458 File may be compile. When this switch is used, a source outside of all Project
9459 Files may be compiled. The ALI file and the object file will be put in the
9460 object directory of the main Project. The compilation switches used will only
9461 be those specified on the command line. Even when
9462 @option{-x} is used, mains specified on the
9463 command line need to be sources of a project file.
9465 @item -X@var{name=value}
9466 Indicate that external variable @var{name} has the value @var{value}.
9467 The Project Manager will use this value for occurrences of
9468 @code{external(name)} when parsing the project file.
9469 @xref{Switches Related to Project Files}.
9471 @item -z
9472 @cindex @option{-z} (@command{gnatmake})
9473 No main subprogram. Bind and link the program even if the unit name
9474 given on the command line is a package name. The resulting executable
9475 will execute the elaboration routines of the package and its closure,
9476 then the finalization routines.
9478 @end table
9480 @table @asis
9481 @item @command{gcc} @asis{switches}
9482 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9483 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9484 @end table
9486 @noindent
9487 Source and library search path switches:
9489 @table @option
9490 @c !sort!
9491 @item -aI@var{dir}
9492 @cindex @option{-aI} (@command{gnatmake})
9493 When looking for source files also look in directory @var{dir}.
9494 The order in which source files search is undertaken is
9495 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9497 @item -aL@var{dir}
9498 @cindex @option{-aL} (@command{gnatmake})
9499 Consider @var{dir} as being an externally provided Ada library.
9500 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9501 files have been located in directory @var{dir}. This allows you to have
9502 missing bodies for the units in @var{dir} and to ignore out of date bodies
9503 for the same units. You still need to specify
9504 the location of the specs for these units by using the switches
9505 @option{-aI@var{dir}}
9506 or @option{-I@var{dir}}.
9507 Note: this switch is provided for compatibility with previous versions
9508 of @command{gnatmake}. The easier method of causing standard libraries
9509 to be excluded from consideration is to write-protect the corresponding
9510 ALI files.
9512 @item -aO@var{dir}
9513 @cindex @option{-aO} (@command{gnatmake})
9514 When searching for library and object files, look in directory
9515 @var{dir}. The order in which library files are searched is described in
9516 @ref{Search Paths for gnatbind}.
9518 @item -A@var{dir}
9519 @cindex Search paths, for @command{gnatmake}
9520 @cindex @option{-A} (@command{gnatmake})
9521 Equivalent to @option{-aL@var{dir}
9522 -aI@var{dir}}.
9524 @item -I@var{dir}
9525 @cindex @option{-I} (@command{gnatmake})
9526 Equivalent to @option{-aO@var{dir}
9527 -aI@var{dir}}.
9529 @item -I-
9530 @cindex @option{-I-} (@command{gnatmake})
9531 @cindex Source files, suppressing search
9532 Do not look for source files in the directory containing the source
9533 file named in the command line.
9534 Do not look for ALI or object files in the directory
9535 where @command{gnatmake} was invoked.
9537 @item -L@var{dir}
9538 @cindex @option{-L} (@command{gnatmake})
9539 @cindex Linker libraries
9540 Add directory @var{dir} to the list of directories in which the linker
9541 will search for libraries. This is equivalent to
9542 @option{-largs -L}@var{dir}.
9543 Furthermore, under Windows, the sources pointed to by the libraries path
9544 set in the registry are not searched for.
9546 @item -nostdinc
9547 @cindex @option{-nostdinc} (@command{gnatmake})
9548 Do not look for source files in the system default directory.
9550 @item -nostdlib
9551 @cindex @option{-nostdlib} (@command{gnatmake})
9552 Do not look for library files in the system default directory.
9554 @item --RTS=@var{rts-path}
9555 @cindex @option{--RTS} (@command{gnatmake})
9556 Specifies the default location of the runtime library. GNAT looks for the
9557 runtime
9558 in the following directories, and stops as soon as a valid runtime is found
9559 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9560 @file{ada_object_path} present):
9562 @itemize @bullet
9563 @item <current directory>/$rts_path
9565 @item <default-search-dir>/$rts_path
9567 @item <default-search-dir>/rts-$rts_path
9568 @end itemize
9570 @noindent
9571 The selected path is handled like a normal RTS path.
9573 @end table
9575 @node Mode Switches for gnatmake
9576 @section Mode Switches for @command{gnatmake}
9578 @noindent
9579 The mode switches (referred to as @code{mode_switches}) allow the
9580 inclusion of switches that are to be passed to the compiler itself, the
9581 binder or the linker. The effect of a mode switch is to cause all
9582 subsequent switches up to the end of the switch list, or up to the next
9583 mode switch, to be interpreted as switches to be passed on to the
9584 designated component of GNAT.
9586 @table @option
9587 @c !sort!
9588 @item -cargs @var{switches}
9589 @cindex @option{-cargs} (@command{gnatmake})
9590 Compiler switches. Here @var{switches} is a list of switches
9591 that are valid switches for @command{gcc}. They will be passed on to
9592 all compile steps performed by @command{gnatmake}.
9594 @item -bargs @var{switches}
9595 @cindex @option{-bargs} (@command{gnatmake})
9596 Binder switches. Here @var{switches} is a list of switches
9597 that are valid switches for @code{gnatbind}. They will be passed on to
9598 all bind steps performed by @command{gnatmake}.
9600 @item -largs @var{switches}
9601 @cindex @option{-largs} (@command{gnatmake})
9602 Linker switches. Here @var{switches} is a list of switches
9603 that are valid switches for @command{gnatlink}. They will be passed on to
9604 all link steps performed by @command{gnatmake}.
9606 @item -margs @var{switches}
9607 @cindex @option{-margs} (@command{gnatmake})
9608 Make switches. The switches are directly interpreted by @command{gnatmake},
9609 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9610 or @option{-largs}.
9611 @end table
9613 @node Notes on the Command Line
9614 @section Notes on the Command Line
9616 @noindent
9617 This section contains some additional useful notes on the operation
9618 of the @command{gnatmake} command.
9620 @itemize @bullet
9621 @item
9622 @cindex Recompilation, by @command{gnatmake}
9623 If @command{gnatmake} finds no ALI files, it recompiles the main program
9624 and all other units required by the main program.
9625 This means that @command{gnatmake}
9626 can be used for the initial compile, as well as during subsequent steps of
9627 the development cycle.
9629 @item
9630 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9631 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9632 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9633 warning.
9635 @item
9636 In @command{gnatmake} the switch @option{-I}
9637 is used to specify both source and
9638 library file paths. Use @option{-aI}
9639 instead if you just want to specify
9640 source paths only and @option{-aO}
9641 if you want to specify library paths
9642 only.
9644 @item
9645 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9646 This may conveniently be used to exclude standard libraries from
9647 consideration and in particular it means that the use of the
9648 @option{-f} switch will not recompile these files
9649 unless @option{-a} is also specified.
9651 @item
9652 @command{gnatmake} has been designed to make the use of Ada libraries
9653 particularly convenient. Assume you have an Ada library organized
9654 as follows: @i{obj-dir} contains the objects and ALI files for
9655 of your Ada compilation units,
9656 whereas @i{include-dir} contains the
9657 specs of these units, but no bodies. Then to compile a unit
9658 stored in @code{main.adb}, which uses this Ada library you would just type
9660 @smallexample
9661 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9662 @end smallexample
9664 @item
9665 Using @command{gnatmake} along with the
9666 @option{-m (minimal recompilation)}
9667 switch provides a mechanism for avoiding unnecessary recompilations. Using
9668 this switch,
9669 you can update the comments/format of your
9670 source files without having to recompile everything. Note, however, that
9671 adding or deleting lines in a source files may render its debugging
9672 info obsolete. If the file in question is a spec, the impact is rather
9673 limited, as that debugging info will only be useful during the
9674 elaboration phase of your program. For bodies the impact can be more
9675 significant. In all events, your debugger will warn you if a source file
9676 is more recent than the corresponding object, and alert you to the fact
9677 that the debugging information may be out of date.
9678 @end itemize
9680 @node How gnatmake Works
9681 @section How @command{gnatmake} Works
9683 @noindent
9684 Generally @command{gnatmake} automatically performs all necessary
9685 recompilations and you don't need to worry about how it works. However,
9686 it may be useful to have some basic understanding of the @command{gnatmake}
9687 approach and in particular to understand how it uses the results of
9688 previous compilations without incorrectly depending on them.
9690 First a definition: an object file is considered @dfn{up to date} if the
9691 corresponding ALI file exists and if all the source files listed in the
9692 dependency section of this ALI file have time stamps matching those in
9693 the ALI file. This means that neither the source file itself nor any
9694 files that it depends on have been modified, and hence there is no need
9695 to recompile this file.
9697 @command{gnatmake} works by first checking if the specified main unit is up
9698 to date. If so, no compilations are required for the main unit. If not,
9699 @command{gnatmake} compiles the main program to build a new ALI file that
9700 reflects the latest sources. Then the ALI file of the main unit is
9701 examined to find all the source files on which the main program depends,
9702 and @command{gnatmake} recursively applies the above procedure on all these
9703 files.
9705 This process ensures that @command{gnatmake} only trusts the dependencies
9706 in an existing ALI file if they are known to be correct. Otherwise it
9707 always recompiles to determine a new, guaranteed accurate set of
9708 dependencies. As a result the program is compiled ``upside down'' from what may
9709 be more familiar as the required order of compilation in some other Ada
9710 systems. In particular, clients are compiled before the units on which
9711 they depend. The ability of GNAT to compile in any order is critical in
9712 allowing an order of compilation to be chosen that guarantees that
9713 @command{gnatmake} will recompute a correct set of new dependencies if
9714 necessary.
9716 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9717 imported by several of the executables, it will be recompiled at most once.
9719 Note: when using non-standard naming conventions
9720 (@pxref{Using Other File Names}), changing through a configuration pragmas
9721 file the version of a source and invoking @command{gnatmake} to recompile may
9722 have no effect, if the previous version of the source is still accessible
9723 by @command{gnatmake}. It may be necessary to use the switch
9726 @node Examples of gnatmake Usage
9727 @section Examples of @command{gnatmake} Usage
9729 @table @code
9730 @item gnatmake hello.adb
9731 Compile all files necessary to bind and link the main program
9732 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9733 resulting object files to generate an executable file @file{hello}.
9735 @item gnatmake main1 main2 main3
9736 Compile all files necessary to bind and link the main programs
9737 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9738 (containing unit @code{Main2}) and @file{main3.adb}
9739 (containing unit @code{Main3}) and bind and link the resulting object files
9740 to generate three executable files @file{main1},
9741 @file{main2}
9742 and @file{main3}.
9744 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9746 Compile all files necessary to bind and link the main program unit
9747 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9748 be done with optimization level 2 and the order of elaboration will be
9749 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9750 displaying commands it is executing.
9751 @end table
9753 @c *************************
9754 @node Improving Performance
9755 @chapter Improving Performance
9756 @cindex Improving performance
9758 @noindent
9759 This chapter presents several topics related to program performance.
9760 It first describes some of the tradeoffs that need to be considered
9761 and some of the techniques for making your program run faster.
9762 It then documents
9763 @ifclear FSFEDITION
9764 the @command{gnatelim} tool and
9765 @end ifclear
9766 unused subprogram/data
9767 elimination feature, which can reduce the size of program executables.
9769 @ifnottex
9770 @menu
9771 * Performance Considerations::
9772 * Text_IO Suggestions::
9773 @ifclear FSFEDITION
9774 * Reducing Size of Ada Executables with gnatelim::
9775 @end ifclear
9776 * Reducing Size of Executables with unused subprogram/data elimination::
9777 @end menu
9778 @end ifnottex
9780 @c *****************************
9781 @node Performance Considerations
9782 @section Performance Considerations
9784 @noindent
9785 The GNAT system provides a number of options that allow a trade-off
9786 between
9788 @itemize @bullet
9789 @item
9790 performance of the generated code
9792 @item
9793 speed of compilation
9795 @item
9796 minimization of dependences and recompilation
9798 @item
9799 the degree of run-time checking.
9800 @end itemize
9802 @noindent
9803 The defaults (if no options are selected) aim at improving the speed
9804 of compilation and minimizing dependences, at the expense of performance
9805 of the generated code:
9807 @itemize @bullet
9808 @item
9809 no optimization
9811 @item
9812 no inlining of subprogram calls
9814 @item
9815 all run-time checks enabled except overflow and elaboration checks
9816 @end itemize
9818 @noindent
9819 These options are suitable for most program development purposes. This
9820 chapter describes how you can modify these choices, and also provides
9821 some guidelines on debugging optimized code.
9823 @menu
9824 * Controlling Run-Time Checks::
9825 * Use of Restrictions::
9826 * Optimization Levels::
9827 * Debugging Optimized Code::
9828 * Inlining of Subprograms::
9829 * Vectorization of loops::
9830 * Other Optimization Switches::
9831 * Optimization and Strict Aliasing::
9832 * Aliased Variables and Optimization::
9833 * Atomic Variables and Optimization::
9834 * Passive Task Optimization::
9836 @end menu
9838 @node Controlling Run-Time Checks
9839 @subsection Controlling Run-Time Checks
9841 @noindent
9842 By default, GNAT generates all run-time checks, except integer overflow
9843 checks, stack overflow checks, and checks for access before elaboration on
9844 subprogram calls. The latter are not required in default mode, because all
9845 necessary checking is done at compile time.
9846 @cindex @option{-gnatp} (@command{gcc})
9847 @cindex @option{-gnato} (@command{gcc})
9848 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9849 be modified. @xref{Run-Time Checks}.
9851 Our experience is that the default is suitable for most development
9852 purposes.
9854 We treat integer overflow specially because these
9855 are quite expensive and in our experience are not as important as other
9856 run-time checks in the development process. Note that division by zero
9857 is not considered an overflow check, and divide by zero checks are
9858 generated where required by default.
9860 Elaboration checks are off by default, and also not needed by default, since
9861 GNAT uses a static elaboration analysis approach that avoids the need for
9862 run-time checking. This manual contains a full chapter discussing the issue
9863 of elaboration checks, and if the default is not satisfactory for your use,
9864 you should read this chapter.
9866 For validity checks, the minimal checks required by the Ada Reference
9867 Manual (for case statements and assignments to array elements) are on
9868 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9869 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9870 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9871 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9872 are also suppressed entirely if @option{-gnatp} is used.
9874 @cindex Overflow checks
9875 @cindex Checks, overflow
9876 @findex Suppress
9877 @findex Unsuppress
9878 @cindex pragma Suppress
9879 @cindex pragma Unsuppress
9880 Note that the setting of the switches controls the default setting of
9881 the checks. They may be modified using either @code{pragma Suppress} (to
9882 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9883 checks) in the program source.
9885 @node Use of Restrictions
9886 @subsection Use of Restrictions
9888 @noindent
9889 The use of pragma Restrictions allows you to control which features are
9890 permitted in your program. Apart from the obvious point that if you avoid
9891 relatively expensive features like finalization (enforceable by the use
9892 of pragma Restrictions (No_Finalization), the use of this pragma does not
9893 affect the generated code in most cases.
9895 One notable exception to this rule is that the possibility of task abort
9896 results in some distributed overhead, particularly if finalization or
9897 exception handlers are used. The reason is that certain sections of code
9898 have to be marked as non-abortable.
9900 If you use neither the @code{abort} statement, nor asynchronous transfer
9901 of control (@code{select @dots{} then abort}), then this distributed overhead
9902 is removed, which may have a general positive effect in improving
9903 overall performance.  Especially code involving frequent use of tasking
9904 constructs and controlled types will show much improved performance.
9905 The relevant restrictions pragmas are
9907 @smallexample @c ada
9908    @b{pragma} Restrictions (No_Abort_Statements);
9909    @b{pragma} Restrictions (Max_Asynchronous_Select_Nesting => 0);
9910 @end smallexample
9912 @noindent
9913 It is recommended that these restriction pragmas be used if possible. Note
9914 that this also means that you can write code without worrying about the
9915 possibility of an immediate abort at any point.
9917 @node Optimization Levels
9918 @subsection Optimization Levels
9919 @cindex @option{-O} (@command{gcc})
9921 @noindent
9922 Without any optimization option,
9923 the compiler's goal is to reduce the cost of
9924 compilation and to make debugging produce the expected results.
9925 Statements are independent: if you stop the program with a breakpoint between
9926 statements, you can then assign a new value to any variable or change
9927 the program counter to any other statement in the subprogram and get exactly
9928 the results you would expect from the source code.
9930 Turning on optimization makes the compiler attempt to improve the
9931 performance and/or code size at the expense of compilation time and
9932 possibly the ability to debug the program.
9934 If you use multiple
9935 -O options, with or without level numbers,
9936 the last such option is the one that is effective.
9938 @noindent
9939 The default is optimization off. This results in the fastest compile
9940 times, but GNAT makes absolutely no attempt to optimize, and the
9941 generated programs are considerably larger and slower than when
9942 optimization is enabled. You can use the
9943 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9944 @option{-O2}, @option{-O3}, and @option{-Os})
9945 to @command{gcc} to control the optimization level:
9947 @table @option
9948 @item -O0
9949 No optimization (the default);
9950 generates unoptimized code but has
9951 the fastest compilation time.
9953 Note that many other compilers do fairly extensive optimization
9954 even if ``no optimization'' is specified. With gcc, it is
9955 very unusual to use -O0 for production if
9956 execution time is of any concern, since -O0
9957 really does mean no optimization at all. This difference between
9958 gcc and other compilers should be kept in mind when doing
9959 performance comparisons.
9961 @item -O1
9962 Moderate optimization;
9963 optimizes reasonably well but does not
9964 degrade compilation time significantly.
9966 @item -O2
9967 Full optimization;
9968 generates highly optimized code and has
9969 the slowest compilation time.
9971 @item -O3
9972 Full optimization as in @option{-O2};
9973 also uses more aggressive automatic inlining of subprograms within a unit
9974 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
9976 @item -Os
9977 Optimize space usage (code and data) of resulting program.
9978 @end table
9980 @noindent
9981 Higher optimization levels perform more global transformations on the
9982 program and apply more expensive analysis algorithms in order to generate
9983 faster and more compact code. The price in compilation time, and the
9984 resulting improvement in execution time,
9985 both depend on the particular application and the hardware environment.
9986 You should experiment to find the best level for your application.
9988 Since the precise set of optimizations done at each level will vary from
9989 release to release (and sometime from target to target), it is best to think
9990 of the optimization settings in general terms.
9991 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
9992 the GNU Compiler Collection (GCC)}, for details about
9993 the @option{-O} settings and a number of @option{-f} options that
9994 individually enable or disable specific optimizations.
9996 Unlike some other compilation systems, @command{gcc} has
9997 been tested extensively at all optimization levels. There are some bugs
9998 which appear only with optimization turned on, but there have also been
9999 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10000 level of optimization does not improve the reliability of the code
10001 generator, which in practice is highly reliable at all optimization
10002 levels.
10004 Note regarding the use of @option{-O3}: The use of this optimization level
10005 is generally discouraged with GNAT, since it often results in larger
10006 executables which may run more slowly. See further discussion of this point
10007 in @ref{Inlining of Subprograms}.
10009 @node Debugging Optimized Code
10010 @subsection Debugging Optimized Code
10011 @cindex Debugging optimized code
10012 @cindex Optimization and debugging
10014 @noindent
10015 Although it is possible to do a reasonable amount of debugging at
10016 nonzero optimization levels,
10017 the higher the level the more likely that
10018 source-level constructs will have been eliminated by optimization.
10019 For example, if a loop is strength-reduced, the loop
10020 control variable may be completely eliminated and thus cannot be
10021 displayed in the debugger.
10022 This can only happen at @option{-O2} or @option{-O3}.
10023 Explicit temporary variables that you code might be eliminated at
10024 level @option{-O1} or higher.
10026 The use of the @option{-g} switch,
10027 @cindex @option{-g} (@command{gcc})
10028 which is needed for source-level debugging,
10029 affects the size of the program executable on disk,
10030 and indeed the debugging information can be quite large.
10031 However, it has no effect on the generated code (and thus does not
10032 degrade performance)
10034 Since the compiler generates debugging tables for a compilation unit before
10035 it performs optimizations, the optimizing transformations may invalidate some
10036 of the debugging data.  You therefore need to anticipate certain
10037 anomalous situations that may arise while debugging optimized code.
10038 These are the most common cases:
10040 @enumerate
10041 @item
10042 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10043 commands show
10044 the PC bouncing back and forth in the code.  This may result from any of
10045 the following optimizations:
10047 @itemize @bullet
10048 @item
10049 @i{Common subexpression elimination:} using a single instance of code for a
10050 quantity that the source computes several times.  As a result you
10051 may not be able to stop on what looks like a statement.
10053 @item
10054 @i{Invariant code motion:} moving an expression that does not change within a
10055 loop, to the beginning of the loop.
10057 @item
10058 @i{Instruction scheduling:} moving instructions so as to
10059 overlap loads and stores (typically) with other code, or in
10060 general to move computations of values closer to their uses. Often
10061 this causes you to pass an assignment statement without the assignment
10062 happening and then later bounce back to the statement when the
10063 value is actually needed.  Placing a breakpoint on a line of code
10064 and then stepping over it may, therefore, not always cause all the
10065 expected side-effects.
10066 @end itemize
10068 @item
10069 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10070 two identical pieces of code are merged and the program counter suddenly
10071 jumps to a statement that is not supposed to be executed, simply because
10072 it (and the code following) translates to the same thing as the code
10073 that @emph{was} supposed to be executed.  This effect is typically seen in
10074 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10075 a @code{break} in a C @code{switch} statement.
10077 @item
10078 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10079 There are various reasons for this effect:
10081 @itemize @bullet
10082 @item
10083 In a subprogram prologue, a parameter may not yet have been moved to its
10084 ``home''.
10086 @item
10087 A variable may be dead, and its register re-used.  This is
10088 probably the most common cause.
10090 @item
10091 As mentioned above, the assignment of a value to a variable may
10092 have been moved.
10094 @item
10095 A variable may be eliminated entirely by value propagation or
10096 other means.  In this case, GCC may incorrectly generate debugging
10097 information for the variable
10098 @end itemize
10100 @noindent
10101 In general, when an unexpected value appears for a local variable or parameter
10102 you should first ascertain if that value was actually computed by
10103 your program, as opposed to being incorrectly reported by the debugger.
10104 Record fields or
10105 array elements in an object designated by an access value
10106 are generally less of a problem, once you have ascertained that the access
10107 value is sensible.
10108 Typically, this means checking variables in the preceding code and in the
10109 calling subprogram to verify that the value observed is explainable from other
10110 values (one must apply the procedure recursively to those
10111 other values); or re-running the code and stopping a little earlier
10112 (perhaps before the call) and stepping to better see how the variable obtained
10113 the value in question; or continuing to step @emph{from} the point of the
10114 strange value to see if code motion had simply moved the variable's
10115 assignments later.
10116 @end enumerate
10118 @noindent
10119 In light of such anomalies, a recommended technique is to use @option{-O0}
10120 early in the software development cycle, when extensive debugging capabilities
10121 are most needed, and then move to @option{-O1} and later @option{-O2} as
10122 the debugger becomes less critical.
10123 Whether to use the @option{-g} switch in the release version is
10124 a release management issue.
10125 Note that if you use @option{-g} you can then use the @command{strip} program
10126 on the resulting executable,
10127 which removes both debugging information and global symbols.
10129 @node Inlining of Subprograms
10130 @subsection Inlining of Subprograms
10132 @noindent
10133 A call to a subprogram in the current unit is inlined if all the
10134 following conditions are met:
10136 @itemize @bullet
10137 @item
10138 The optimization level is at least @option{-O1}.
10140 @item
10141 The called subprogram is suitable for inlining: It must be small enough
10142 and not contain something that @command{gcc} cannot support in inlined
10143 subprograms.
10145 @item
10146 @cindex pragma Inline
10147 @findex Inline
10148 Any one of the following applies: @code{pragma Inline} is applied to the
10149 subprogram and the @option{-gnatn} switch is specified; the
10150 subprogram is local to the unit and called once from within it; the
10151 subprogram is small and optimization level @option{-O2} is specified;
10152 optimization level @option{-O3} is specified.
10153 @end itemize
10155 @noindent
10156 Calls to subprograms in @code{with}'ed units are normally not inlined.
10157 To achieve actual inlining (that is, replacement of the call by the code
10158 in the body of the subprogram), the following conditions must all be true:
10160 @itemize @bullet
10161 @item
10162 The optimization level is at least @option{-O1}.
10164 @item
10165 The called subprogram is suitable for inlining: It must be small enough
10166 and not contain something that @command{gcc} cannot support in inlined
10167 subprograms.
10169 @item
10170 The call appears in a body (not in a package spec).
10172 @item
10173 There is a @code{pragma Inline} for the subprogram.
10175 @item
10176 The @option{-gnatn} switch is used on the command line.
10177 @end itemize
10179 Even if all these conditions are met, it may not be possible for
10180 the compiler to inline the call, due to the length of the body,
10181 or features in the body that make it impossible for the compiler
10182 to do the inlining.
10184 Note that specifying the @option{-gnatn} switch causes additional
10185 compilation dependencies. Consider the following:
10187 @smallexample @c ada
10188 @cartouche
10189 @b{package} R @b{is}
10190    @b{procedure} Q;
10191    @b{pragma} Inline (Q);
10192 @b{end} R;
10193 @b{package} @b{body} R @b{is}
10194    @dots{}
10195 @b{end} R;
10197 @b{with} R;
10198 @b{procedure} Main @b{is}
10199 @b{begin}
10200    @dots{}
10201    R.Q;
10202 @b{end} Main;
10203 @end cartouche
10204 @end smallexample
10206 @noindent
10207 With the default behavior (no @option{-gnatn} switch specified), the
10208 compilation of the @code{Main} procedure depends only on its own source,
10209 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10210 means that editing the body of @code{R} does not require recompiling
10211 @code{Main}.
10213 On the other hand, the call @code{R.Q} is not inlined under these
10214 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10215 is compiled, the call will be inlined if the body of @code{Q} is small
10216 enough, but now @code{Main} depends on the body of @code{R} in
10217 @file{r.adb} as well as on the spec. This means that if this body is edited,
10218 the main program must be recompiled. Note that this extra dependency
10219 occurs whether or not the call is in fact inlined by @command{gcc}.
10221 The use of front end inlining with @option{-gnatN} generates similar
10222 additional dependencies.
10224 @cindex @option{-fno-inline} (@command{gcc})
10225 Note: The @option{-fno-inline} switch
10226 can be used to prevent
10227 all inlining. This switch overrides all other conditions and ensures
10228 that no inlining occurs. The extra dependences resulting from
10229 @option{-gnatn} will still be active, even if
10230 this switch is used to suppress the resulting inlining actions.
10232 @cindex @option{-fno-inline-functions} (@command{gcc})
10233 Note: The @option{-fno-inline-functions} switch can be used to prevent
10234 automatic inlining of subprograms if @option{-O3} is used.
10236 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10237 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10238 automatic inlining of small subprograms if @option{-O2} is used.
10240 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10241 Note: The @option{-fno-inline-functions-called-once} switch
10242 can be used to prevent inlining of subprograms local to the unit
10243 and called once from within it if @option{-O1} is used.
10245 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10246 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10247 specified in lieu of it, @option{-gnatn} being translated into one of them
10248 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10249 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10250 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10251 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10252 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
10253 effect of inlining subprograms you did not think should be inlined. We have
10254 found that the use of @option{-O3} may slow down the compilation and increase
10255 the code size by performing excessive inlining, leading to increased
10256 instruction cache pressure from the increased code size and thus minor
10257 performance improvements. So the bottom line here is that you should not
10258 automatically assume that @option{-O3} is better than @option{-O2}, and
10259 indeed you should use @option{-O3} only if tests show that it actually
10260 improves performance for your program.
10262 @node Vectorization of loops
10263 @subsection Vectorization of loops
10264 @cindex Optimization Switches
10266 You can take advantage of the auto-vectorizer present in the @command{gcc}
10267 back end to vectorize loops with GNAT.  The corresponding command line switch
10268 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10269 and other aggressive optimizations helpful for vectorization also are enabled
10270 by default at this level, using @option{-O3} directly is recommended.
10272 You also need to make sure that the target architecture features a supported
10273 SIMD instruction set.  For example, for the x86 architecture, you should at
10274 least specify @option{-msse2} to get significant vectorization (but you don't
10275 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10276 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10278 The preferred loop form for vectorization is the @code{for} iteration scheme.
10279 Loops with a @code{while} iteration scheme can also be vectorized if they are
10280 very simple, but the vectorizer will quickly give up otherwise.  With either
10281 iteration scheme, the flow of control must be straight, in particular no
10282 @code{exit} statement may appear in the loop body.  The loop may however
10283 contain a single nested loop, if it can be vectorized when considered alone:
10285 @smallexample @c ada
10286 @cartouche
10287    A : @b{array} (1..4, 1..4) @b{of} Long_Float;
10288    S : @b{array} (1..4) @b{of} Long_Float;
10290    @b{procedure} Sum @b{is}
10291    @b{begin}
10292       @b{for} I @b{in} A'Range(1) @b{loop}
10293          @b{for} J @b{in} A'Range(2) @b{loop}
10294             S (I) := S (I) + A (I, J);
10295          @b{end} @b{loop};
10296       @b{end} @b{loop};
10297    @b{end} Sum;
10298 @end cartouche
10299 @end smallexample
10301 The vectorizable operations depend on the targeted SIMD instruction set, but
10302 the adding and some of the multiplying operators are generally supported, as
10303 well as the logical operators for modular types.  Note that, in the former
10304 case, enabling overflow checks, for example with @option{-gnato}, totally
10305 disables vectorization.  The other checks are not supposed to have the same
10306 definitive effect, although compiling with @option{-gnatp} might well reveal
10307 cases where some checks do thwart vectorization.
10309 Type conversions may also prevent vectorization if they involve semantics that
10310 are not directly supported by the code generator or the SIMD instruction set.
10311 A typical example is direct conversion from floating-point to integer types.
10312 The solution in this case is to use the following idiom:
10314 @smallexample @c ada
10315    Integer (S'Truncation (F))
10316 @end smallexample
10318 @noindent
10319 if @code{S} is the subtype of floating-point object @code{F}.
10321 In most cases, the vectorizable loops are loops that iterate over arrays.
10322 All kinds of array types are supported, i.e. constrained array types with
10323 static bounds:
10325 @smallexample @c ada
10326    @b{type} Array_Type @b{is} @b{array} (1 .. 4) @b{of} Long_Float;
10327 @end smallexample
10329 @noindent
10330 constrained array types with dynamic bounds:
10332 @smallexample @c ada
10333    @b{type} Array_Type @b{is} @b{array} (1 .. Q.N) @b{of} Long_Float;
10335    @b{type} Array_Type @b{is} @b{array} (Q.K .. 4) @b{of} Long_Float;
10337    @b{type} Array_Type @b{is} @b{array} (Q.K .. Q.N) @b{of} Long_Float;
10338 @end smallexample
10340 @noindent
10341 or unconstrained array types:
10343 @smallexample @c ada
10344   @b{type} Array_Type @b{is} @b{array} (Positive @b{range} <>) @b{of} Long_Float;
10345 @end smallexample
10347 @noindent
10348 The quality of the generated code decreases when the dynamic aspect of the
10349 array type increases, the worst code being generated for unconstrained array
10350 types.  This is so because, the less information the compiler has about the
10351 bounds of the array, the more fallback code it needs to generate in order to
10352 fix things up at run time.
10354 It is possible to specify that a given loop should be subject to vectorization
10355 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10357 @smallexample @c ada
10358   @b{pragma} Loop_Optimize (Vector);
10359 @end smallexample
10361 @noindent
10362 placed immediately within the loop will convey the appropriate hint to the
10363 compiler for this loop.
10365 It is also possible to help the compiler generate better vectorized code
10366 for a given loop by asserting that there are no loop-carried dependencies
10367 in the loop.  Consider for example the procedure:
10369 @smallexample @c ada
10370   @b{type} Arr @b{is} @b{array} (1 .. 4) @b{of} Long_Float;
10372   @b{procedure} Add (X, Y : @b{not} @b{null} @b{access} Arr; R : @b{not} @b{null} @b{access} Arr) @b{is}
10373   @b{begin}
10374     @b{for} I @b{in} Arr'Range @b{loop}
10375       R(I) := X(I) + Y(I);
10376     @b{end} @b{loop};
10377   @b{end};
10378 @end smallexample
10380 @noindent
10381 By default, the compiler cannot unconditionally vectorize the loop because
10382 assigning to a component of the array designated by R in one iteration could
10383 change the value read from the components of the array designated by X or Y
10384 in a later iteration.  As a result, the compiler will generate two versions
10385 of the loop in the object code, one vectorized and the other not vectorized,
10386 as well as a test to select the appropriate version at run time.  This can
10387 be overcome by another hint:
10389 @smallexample @c ada
10390   @b{pragma} Loop_Optimize (Ivdep);
10391 @end smallexample
10393 @noindent
10394 placed immediately within the loop will tell the compiler that it can safely
10395 omit the non-vectorized version of the loop as well as the run-time test.
10397 @node Other Optimization Switches
10398 @subsection Other Optimization Switches
10399 @cindex Optimization Switches
10401 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10402 @command{gcc} optimization switches are potentially usable. These switches
10403 have not been extensively tested with GNAT but can generally be expected
10404 to work. Examples of switches in this category are @option{-funroll-loops}
10405 and the various target-specific @option{-m} options (in particular, it has
10406 been observed that @option{-march=xxx} can significantly improve performance
10407 on appropriate machines). For full details of these switches, see
10408 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10409 the GNU Compiler Collection (GCC)}.
10411 @node Optimization and Strict Aliasing
10412 @subsection Optimization and Strict Aliasing
10413 @cindex Aliasing
10414 @cindex Strict Aliasing
10415 @cindex No_Strict_Aliasing
10417 @noindent
10418 The strong typing capabilities of Ada allow an optimizer to generate
10419 efficient code in situations where other languages would be forced to
10420 make worst case assumptions preventing such optimizations. Consider
10421 the following example:
10423 @smallexample @c ada
10424 @cartouche
10425 @b{procedure} R @b{is}
10426    @b{type} Int1 @b{is} @b{new} Integer;
10427    @b{type} Int2 @b{is} @b{new} Integer;
10428    @b{type} Int1A @b{is} @b{access} Int1;
10429    @b{type} Int2A @b{is} @b{access} Int2;
10430    Int1V : Int1A;
10431    Int2V : Int2A;
10432    @dots{}
10434 @b{begin}
10435    @dots{}
10436    @b{for} J @b{in} Data'Range @b{loop}
10437       @b{if} Data (J) = Int1V.@b{all} @b{then}
10438          Int2V.@b{all} := Int2V.@b{all} + 1;
10439       @b{end} @b{if};
10440    @b{end} @b{loop};
10441    @dots{}
10442 @b{end} R;
10443 @end cartouche
10444 @end smallexample
10446 @noindent
10447 In this example, since the variable @code{Int1V} can only access objects
10448 of type @code{Int1}, and @code{Int2V} can only access objects of type
10449 @code{Int2}, there is no possibility that the assignment to
10450 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10451 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10452 for all iterations of the loop and avoid the extra memory reference
10453 required to dereference it each time through the loop.
10455 This kind of optimization, called strict aliasing analysis, is
10456 triggered by specifying an optimization level of @option{-O2} or
10457 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10458 when access values are involved.
10460 However, although this optimization is always correct in terms of
10461 the formal semantics of the Ada Reference Manual, difficulties can
10462 arise if features like @code{Unchecked_Conversion} are used to break
10463 the typing system. Consider the following complete program example:
10465 @smallexample @c ada
10466 @cartouche
10467 @b{package} p1 @b{is}
10468    @b{type} int1 @b{is} @b{new} integer;
10469    @b{type} int2 @b{is} @b{new} integer;
10470    @b{type} a1 @b{is} @b{access} int1;
10471    @b{type} a2 @b{is} @b{access} int2;
10472 @b{end} p1;
10474 @b{with} p1; @b{use} p1;
10475 @b{package} p2 @b{is}
10476    @b{function} to_a2 (Input : a1) @b{return} a2;
10477 @b{end} p2;
10479 @b{with} Unchecked_Conversion;
10480 @b{package} @b{body} p2 @b{is}
10481    @b{function} to_a2 (Input : a1) @b{return} a2 @b{is}
10482       @b{function} to_a2u @b{is}
10483         @b{new} Unchecked_Conversion (a1, a2);
10484    @b{begin}
10485       @b{return} to_a2u (Input);
10486    @b{end} to_a2;
10487 @b{end} p2;
10489 @b{with} p2; @b{use} p2;
10490 @b{with} p1; @b{use} p1;
10491 @b{with} Text_IO; @b{use} Text_IO;
10492 @b{procedure} m @b{is}
10493    v1 : a1 := @b{new} int1;
10494    v2 : a2 := to_a2 (v1);
10495 @b{begin}
10496    v1.@b{all} := 1;
10497    v2.@b{all} := 0;
10498    put_line (int1'image (v1.@b{all}));
10499 @b{end};
10500 @end cartouche
10501 @end smallexample
10503 @noindent
10504 This program prints out 0 in @option{-O0} or @option{-O1}
10505 mode, but it prints out 1 in @option{-O2} mode. That's
10506 because in strict aliasing mode, the compiler can and
10507 does assume that the assignment to @code{v2.all} could not
10508 affect the value of @code{v1.all}, since different types
10509 are involved.
10511 This behavior is not a case of non-conformance with the standard, since
10512 the Ada RM specifies that an unchecked conversion where the resulting
10513 bit pattern is not a correct value of the target type can result in an
10514 abnormal value and attempting to reference an abnormal value makes the
10515 execution of a program erroneous.  That's the case here since the result
10516 does not point to an object of type @code{int2}.  This means that the
10517 effect is entirely unpredictable.
10519 However, although that explanation may satisfy a language
10520 lawyer, in practice an applications programmer expects an
10521 unchecked conversion involving pointers to create true
10522 aliases and the behavior of printing 1 seems plain wrong.
10523 In this case, the strict aliasing optimization is unwelcome.
10525 Indeed the compiler recognizes this possibility, and the
10526 unchecked conversion generates a warning:
10528 @smallexample
10529 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10530 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10531 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10532 @end smallexample
10534 @noindent
10535 Unfortunately the problem is recognized when compiling the body of
10536 package @code{p2}, but the actual "bad" code is generated while
10537 compiling the body of @code{m} and this latter compilation does not see
10538 the suspicious @code{Unchecked_Conversion}.
10540 As implied by the warning message, there are approaches you can use to
10541 avoid the unwanted strict aliasing optimization in a case like this.
10543 One possibility is to simply avoid the use of @option{-O2}, but
10544 that is a bit drastic, since it throws away a number of useful
10545 optimizations that do not involve strict aliasing assumptions.
10547 A less drastic approach is to compile the program using the
10548 option @option{-fno-strict-aliasing}. Actually it is only the
10549 unit containing the dereferencing of the suspicious pointer
10550 that needs to be compiled. So in this case, if we compile
10551 unit @code{m} with this switch, then we get the expected
10552 value of zero printed. Analyzing which units might need
10553 the switch can be painful, so a more reasonable approach
10554 is to compile the entire program with options @option{-O2}
10555 and @option{-fno-strict-aliasing}. If the performance is
10556 satisfactory with this combination of options, then the
10557 advantage is that the entire issue of possible "wrong"
10558 optimization due to strict aliasing is avoided.
10560 To avoid the use of compiler switches, the configuration
10561 pragma @code{No_Strict_Aliasing} with no parameters may be
10562 used to specify that for all access types, the strict
10563 aliasing optimization should be suppressed.
10565 However, these approaches are still overkill, in that they causes
10566 all manipulations of all access values to be deoptimized. A more
10567 refined approach is to concentrate attention on the specific
10568 access type identified as problematic.
10570 First, if a careful analysis of uses of the pointer shows
10571 that there are no possible problematic references, then
10572 the warning can be suppressed by bracketing the
10573 instantiation of @code{Unchecked_Conversion} to turn
10574 the warning off:
10576 @smallexample @c ada
10577    @b{pragma} Warnings (Off);
10578    @b{function} to_a2u @b{is}
10579      @b{new} Unchecked_Conversion (a1, a2);
10580    @b{pragma} Warnings (On);
10581 @end smallexample
10583 @noindent
10584 Of course that approach is not appropriate for this particular
10585 example, since indeed there is a problematic reference. In this
10586 case we can take one of two other approaches.
10588 The first possibility is to move the instantiation of unchecked
10589 conversion to the unit in which the type is declared. In
10590 this example, we would move the instantiation of
10591 @code{Unchecked_Conversion} from the body of package
10592 @code{p2} to the spec of package @code{p1}. Now the
10593 warning disappears. That's because any use of the
10594 access type knows there is a suspicious unchecked
10595 conversion, and the strict aliasing optimization
10596 is automatically suppressed for the type.
10598 If it is not practical to move the unchecked conversion to the same unit
10599 in which the destination access type is declared (perhaps because the
10600 source type is not visible in that unit), you may use pragma
10601 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10602 same declarative sequence as the declaration of the access type:
10604 @smallexample @c ada
10605    @b{type} a2 @b{is} @b{access} int2;
10606    @b{pragma} No_Strict_Aliasing (a2);
10607 @end smallexample
10609 @noindent
10610 Here again, the compiler now knows that the strict aliasing optimization
10611 should be suppressed for any reference to type @code{a2} and the
10612 expected behavior is obtained.
10614 Finally, note that although the compiler can generate warnings for
10615 simple cases of unchecked conversions, there are tricker and more
10616 indirect ways of creating type incorrect aliases which the compiler
10617 cannot detect. Examples are the use of address overlays and unchecked
10618 conversions involving composite types containing access types as
10619 components. In such cases, no warnings are generated, but there can
10620 still be aliasing problems. One safe coding practice is to forbid the
10621 use of address clauses for type overlaying, and to allow unchecked
10622 conversion only for primitive types. This is not really a significant
10623 restriction since any possible desired effect can be achieved by
10624 unchecked conversion of access values.
10626 The aliasing analysis done in strict aliasing mode can certainly
10627 have significant benefits. We have seen cases of large scale
10628 application code where the time is increased by up to 5% by turning
10629 this optimization off. If you have code that includes significant
10630 usage of unchecked conversion, you might want to just stick with
10631 @option{-O1} and avoid the entire issue. If you get adequate
10632 performance at this level of optimization level, that's probably
10633 the safest approach. If tests show that you really need higher
10634 levels of optimization, then you can experiment with @option{-O2}
10635 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10636 has on size and speed of the code. If you really need to use
10637 @option{-O2} with strict aliasing in effect, then you should
10638 review any uses of unchecked conversion of access types,
10639 particularly if you are getting the warnings described above.
10641 @node Aliased Variables and Optimization
10642 @subsection Aliased Variables and Optimization
10643 @cindex Aliasing
10644 There are scenarios in which programs may
10645 use low level techniques to modify variables
10646 that otherwise might be considered to be unassigned. For example,
10647 a variable can be passed to a procedure by reference, which takes
10648 the address of the parameter and uses the address to modify the
10649 variable's value, even though it is passed as an IN parameter.
10650 Consider the following example:
10652 @smallexample @c ada
10653 @b{procedure} P @b{is}
10654    Max_Length : @b{constant} Natural := 16;
10655    @b{type} Char_Ptr @b{is} @b{access} @b{all} Character;
10657    @b{procedure} Get_String(Buffer: Char_Ptr; Size : Integer);
10658    @b{pragma} Import (C, Get_String, "get_string");
10660    Name : @b{aliased} String (1 .. Max_Length) := (@b{others} => ' ');
10661    Temp : Char_Ptr;
10663    @b{function} Addr (S : String) @b{return} Char_Ptr @b{is}
10664       @b{function} To_Char_Ptr @b{is}
10665         @b{new} Ada.Unchecked_Conversion (System.Address, Char_Ptr);
10666    @b{begin}
10667       @b{return} To_Char_Ptr (S (S'First)'Address);
10668    @b{end};
10670 @b{begin}
10671    Temp := Addr (Name);
10672    Get_String (Temp, Max_Length);
10673 @b{end};
10674 @end smallexample
10676 @noindent
10677 where Get_String is a C function that uses the address in Temp to
10678 modify the variable @code{Name}. This code is dubious, and arguably
10679 erroneous, and the compiler would be entitled to assume that
10680 @code{Name} is never modified, and generate code accordingly.
10682 However, in practice, this would cause some existing code that
10683 seems to work with no optimization to start failing at high
10684 levels of optimzization.
10686 What the compiler does for such cases is to assume that marking
10687 a variable as aliased indicates that some "funny business" may
10688 be going on. The optimizer recognizes the aliased keyword and
10689 inhibits optimizations that assume the value cannot be assigned.
10690 This means that the above example will in fact "work" reliably,
10691 that is, it will produce the expected results.
10693 @node Atomic Variables and Optimization
10694 @subsection Atomic Variables and Optimization
10695 @cindex Atomic
10696 There are two considerations with regard to performance when
10697 atomic variables are used.
10699 First, the RM only guarantees that access to atomic variables
10700 be atomic, it has nothing to say about how this is achieved,
10701 though there is a strong implication that this should not be
10702 achieved by explicit locking code. Indeed GNAT will never
10703 generate any locking code for atomic variable access (it will
10704 simply reject any attempt to make a variable or type atomic
10705 if the atomic access cannot be achieved without such locking code).
10707 That being said, it is important to understand that you cannot
10708 assume that the entire variable will always be accessed. Consider
10709 this example:
10711 @smallexample @c ada
10712 @b{type} R @b{is} @b{record}
10713    A,B,C,D : Character;
10714 @b{end} @b{record};
10715 @b{for} R'Size @b{use} 32;
10716 @b{for} R'Alignment @b{use} 4;
10718 RV : R;
10719 @b{pragma} Atomic (RV);
10720 X : Character;
10722 X := RV.B;
10723 @end smallexample
10725 @noindent
10726 You cannot assume that the reference to @code{RV.B}
10727 will read the entire 32-bit
10728 variable with a single load instruction. It is perfectly legitimate if
10729 the hardware allows it to do a byte read of just the B field. This read
10730 is still atomic, which is all the RM requires. GNAT can and does take
10731 advantage of this, depending on the architecture and optimization level.
10732 Any assumption to the contrary is non-portable and risky. Even if you
10733 examine the assembly language and see a full 32-bit load, this might
10734 change in a future version of the compiler.
10736 If your application requires that all accesses to @code{RV} in this
10737 example be full 32-bit loads, you need to make a copy for the access
10738 as in:
10740 @smallexample @c ada
10741 @b{declare}
10742    RV_Copy : @b{constant} R := RV;
10743 @b{begin}
10744    X := RV_Copy.B;
10745 @b{end};
10746 @end smallexample
10749 @noindent
10750 Now the reference to RV must read the whole variable.
10751 Actually one can imagine some compiler which figures
10752 out that the whole copy is not required (because only
10753 the B field is actually accessed), but GNAT
10754 certainly won't do that, and we don't know of any
10755 compiler that would not handle this right, and the
10756 above code will in practice work portably across
10757 all architectures (that permit the Atomic declaration).
10759 The second issue with atomic variables has to do with
10760 the possible requirement of generating synchronization
10761 code. For more details on this, consult the sections on
10762 the pragmas Enable/Disable_Atomic_Synchronization in the
10763 GNAT Reference Manual. If performance is critical, and
10764 such synchronization code is not required, it may be
10765 useful to disable it.
10767 @node Passive Task Optimization
10768 @subsection Passive Task Optimization
10769 @cindex Passive Task
10771 A passive task is one which is sufficiently simple that
10772 in theory a compiler could recognize it an implement it
10773 efficiently without creating a new thread. The original design
10774 of Ada 83 had in mind this kind of passive task optimization, but
10775 only a few Ada 83 compilers attempted it. The problem was that
10776 it was difficult to determine the exact conditions under which
10777 the optimization was possible. The result is a very fragile
10778 optimization where a very minor change in the program can
10779 suddenly silently make a task non-optimizable.
10781 With the revisiting of this issue in Ada 95, there was general
10782 agreement that this approach was fundamentally flawed, and the
10783 notion of protected types was introduced. When using protected
10784 types, the restrictions are well defined, and you KNOW that the
10785 operations will be optimized, and furthermore this optimized
10786 performance is fully portable.
10788 Although it would theoretically be possible for GNAT to attempt to
10789 do this optimization, but it really doesn't make sense in the
10790 context of Ada 95, and none of the Ada 95 compilers implement
10791 this optimization as far as we know. In particular GNAT never
10792 attempts to perform this optimization.
10794 In any new Ada 95 code that is written, you should always
10795 use protected types in place of tasks that might be able to
10796 be optimized in this manner.
10797 Of course this does not help if you have legacy Ada 83 code
10798 that depends on this optimization, but it is unusual to encounter
10799 a case where the performance gains from this optimization
10800 are significant.
10802 Your program should work correctly without this optimization. If
10803 you have performance problems, then the most practical
10804 approach is to figure out exactly where these performance problems
10805 arise, and update those particular tasks to be protected types. Note
10806 that typically clients of the tasks who call entries, will not have
10807 to be modified, only the task definition itself.
10811 @node Text_IO Suggestions
10812 @section @code{Text_IO} Suggestions
10813 @cindex @code{Text_IO} and performance
10815 @noindent
10816 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10817 the requirement of maintaining page and line counts. If performance
10818 is critical, a recommendation is to use @code{Stream_IO} instead of
10819 @code{Text_IO} for volume output, since this package has less overhead.
10821 If @code{Text_IO} must be used, note that by default output to the standard
10822 output and standard error files is unbuffered (this provides better
10823 behavior when output statements are used for debugging, or if the
10824 progress of a program is observed by tracking the output, e.g. by
10825 using the Unix @command{tail -f} command to watch redirected output.
10827 If you are generating large volumes of output with @code{Text_IO} and
10828 performance is an important factor, use a designated file instead
10829 of the standard output file, or change the standard output file to
10830 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10833 @ifclear FSFEDITION
10834 @node Reducing Size of Ada Executables with gnatelim
10835 @section Reducing Size of Ada Executables with @code{gnatelim}
10836 @findex gnatelim
10838 @noindent
10839 This section describes @command{gnatelim}, a tool which detects unused
10840 subprograms and helps the compiler to create a smaller executable for your
10841 program.
10843 @menu
10844 * About gnatelim::
10845 * Running gnatelim::
10846 * Processing Precompiled Libraries::
10847 * Correcting the List of Eliminate Pragmas::
10848 * Making Your Executables Smaller::
10849 * Summary of the gnatelim Usage Cycle::
10850 @end menu
10852 @node About gnatelim
10853 @subsection About @code{gnatelim}
10855 @noindent
10856 When a program shares a set of Ada
10857 packages with other programs, it may happen that this program uses
10858 only a fraction of the subprograms defined in these packages. The code
10859 created for these unused subprograms increases the size of the executable.
10861 @code{gnatelim} tracks unused subprograms in an Ada program and
10862 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10863 subprograms that are declared but never called. By placing the list of
10864 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10865 recompiling your program, you may decrease the size of its executable,
10866 because the compiler will not generate the code for 'eliminated' subprograms.
10867 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10868 information about this pragma.
10870 @code{gnatelim} needs as its input data the name of the main subprogram.
10872 If a set of source files is specified as @code{gnatelim} arguments, it
10873 treats these files as a complete set of sources making up a program to
10874 analyse, and analyses only these sources.
10876 After a full successful build of the main subprogram @code{gnatelim} can be
10877 called without  specifying sources to analyse, in this case it computes
10878 the source closure of the main unit from the @file{ALI} files.
10880 If the set of sources to be processed by @code{gnatelim} contains sources with
10881 preprocessing directives
10882 then the needed options should be provided to run preprocessor as a part of
10883 the @command{gnatelim} call, and the generated set of pragmas @code{Eliminate}
10884 will correspond to preprocessed sources.
10886 The following command will create the set of @file{ALI} files needed for
10887 @code{gnatelim}:
10889 @smallexample
10890 $ gnatmake -c Main_Prog
10891 @end smallexample
10893 Note that @code{gnatelim} does not need object files.
10895 @node Running gnatelim
10896 @subsection Running @code{gnatelim}
10898 @noindent
10899 @code{gnatelim} has the following command-line interface:
10901 @smallexample
10902 $ gnatelim [@var{switches}] -main=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10903 @end smallexample
10905 @noindent
10906 @var{main_unit_name} should be a name of a source file that contains the main
10907 subprogram of a program (partition).
10909 Each @var{filename} is the name (including the extension) of a source
10910 file to process. ``Wildcards'' are allowed, and
10911 the file name may contain path information.
10913 @samp{@var{gcc_switches}} is a list of switches for
10914 @command{gcc}. They will be passed on to all compiler invocations made by
10915 @command{gnatelim} to generate the ASIS trees. Here you can provide
10916 @option{-I} switches to form the source search path,
10917 use the @option{-gnatec} switch to set the configuration file,
10918 use the @option{-gnat05} switch if sources should be compiled in
10919 Ada 2005 mode etc.
10921 @code{gnatelim} has the following switches:
10923 @table @option
10924 @c !sort!
10925 @item --version
10926 @cindex @option{--version} @command{gnatelim}
10927 Display Copyright and version, then exit disregarding all other options.
10929 @item --help
10930 @cindex @option{--help} @command{gnatelim}
10931 Display usage, then exit disregarding all other options.
10933 @item -P @var{file}
10934 @cindex @option{-P} @command{gnatelim}
10935 Indicates the name of the project file that describes the set of sources
10936 to be processed.
10938 @item -X@var{name}=@var{value}
10939 @cindex @option{-X} @command{gnatelim}
10940 Indicates that external variable @var{name} in the argument project
10941 has the value @var{value}. Has no effect if no project is specified as
10942 tool argument.
10944 @item -files=@var{filename}
10945 @cindex @option{-files} (@code{gnatelim})
10946 Take the argument source files from the specified file. This file should be an
10947 ordinary text file containing file names separated by spaces or
10948 line breaks. You can use this switch more than once in the same call to
10949 @command{gnatelim}. You also can combine this switch with
10950 an explicit list of files.
10952 @item -log
10953 @cindex @option{-log} (@command{gnatelim})
10954 Duplicate all the output sent to @file{stderr} into a log file. The log file
10955 is named @file{gnatelim.log} and is located in the current directory.
10957 @ignore
10958 @item -log=@var{filename}
10959 @cindex @option{-log} (@command{gnatelim})
10960 Duplicate all the output sent to @file{stderr} into a specified log file.
10961 @end ignore
10963 @cindex @option{--no-elim-dispatch} (@command{gnatelim})
10964 @item --no-elim-dispatch
10965 Do not generate pragmas for dispatching operations.
10967 @item --ignore=@var{filename}
10968 @cindex @option{--ignore} (@command{gnatelim})
10969 Do not generate pragmas for subprograms declared in the sources
10970 listed in a specified file
10972 @cindex @option{-o} (@command{gnatelim})
10973 @item -o=@var{report_file}
10974 Put @command{gnatelim} output into a specified file. If this file already exists,
10975 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10976 into @file{stderr}
10978 @item -j@var{n}
10979 @cindex @option{-j} (@command{gnatelim})
10980 Use @var{n} processes to carry out the tree creations (internal representations
10981 of the argument sources). On a multiprocessor machine this speeds up processing
10982 of big sets of argument sources. If @var{n} is 0, then the maximum number of
10983 parallel tree creations is the number of core processors on the platform.
10985 @item -q
10986 @cindex @option{-q} (@command{gnatelim})
10987 Quiet mode: by default @code{gnatelim} outputs to the standard error
10988 stream the number of program units left to be processed. This option turns
10989 this trace off.
10991 @cindex @option{-t} (@command{gnatelim})
10992 @item -t
10993 Print out execution time.
10995 @item -v
10996 @cindex @option{-v} (@command{gnatelim})
10997 Verbose mode: @code{gnatelim} version information is printed as Ada
10998 comments to the standard output stream. Also, in addition to the number of
10999 program units left @code{gnatelim} will output the name of the current unit
11000 being processed.
11002 @item -wq
11003 @cindex @option{-wq} (@command{gnatelim})
11004 Quiet warning mode - some warnings are suppressed. In particular warnings that
11005 indicate that the analysed set of sources is incomplete to make up a
11006 partition and that some subprogram bodies are missing are not generated.
11007 @end table
11009 @noindent
11010 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11011 driver (see @ref{The GNAT Driver and Project Files}).
11013 @node Processing Precompiled Libraries
11014 @subsection Processing Precompiled Libraries
11016 @noindent
11017 If some program uses a precompiled Ada library, it can be processed by
11018 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11019 Eliminate pragma for a subprogram if the body of this subprogram has not
11020 been analysed, this is a typical case for subprograms from precompiled
11021 libraries. Switch @option{-wq} may be used to suppress
11022 warnings about missing source files and non-analyzed subprogram bodies
11023 that can be generated when processing precompiled Ada libraries.
11025 @node Correcting the List of Eliminate Pragmas
11026 @subsection Correcting the List of Eliminate Pragmas
11028 @noindent
11029 In some rare cases @code{gnatelim} may try to eliminate
11030 subprograms that are actually called in the program. In this case, the
11031 compiler will generate an error message of the form:
11033 @smallexample
11034 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11035 @end smallexample
11037 @noindent
11038 You will need to manually remove the wrong @code{Eliminate} pragmas from
11039 the configuration file indicated in the error message. You should recompile
11040 your program from scratch after that, because you need a consistent
11041 configuration file(s) during the entire compilation.
11043 @node Making Your Executables Smaller
11044 @subsection Making Your Executables Smaller
11046 @noindent
11047 In order to get a smaller executable for your program you now have to
11048 recompile the program completely with the configuration file containing
11049 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11050 @file{gnat.adc} file located in your current directory, just do:
11052 @smallexample
11053 $ gnatmake -f main_prog
11054 @end smallexample
11056 @noindent
11057 (Use the @option{-f} option for @command{gnatmake} to
11058 recompile everything
11059 with the set of pragmas @code{Eliminate} that you have obtained with
11060 @command{gnatelim}).
11062 Be aware that the set of @code{Eliminate} pragmas is specific to each
11063 program. It is not recommended to merge sets of @code{Eliminate}
11064 pragmas created for different programs in one configuration file.
11066 @node Summary of the gnatelim Usage Cycle
11067 @subsection Summary of the @code{gnatelim} Usage Cycle
11069 @noindent
11070 Here is a quick summary of the steps to be taken in order to reduce
11071 the size of your executables with @code{gnatelim}. You may use
11072 other GNAT options to control the optimization level,
11073 to produce the debugging information, to set search path, etc.
11075 @enumerate
11076 @item
11077 Create a complete set of @file{ALI} files (if the program has not been
11078 built already)
11080 @smallexample
11081 $ gnatmake -c main_prog
11082 @end smallexample
11084 @item
11085 Generate a list of @code{Eliminate} pragmas in default configuration file
11086 @file{gnat.adc} in the current directory
11087 @smallexample
11088 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11089 @end smallexample
11091 @item
11092 Recompile the application
11094 @smallexample
11095 $ gnatmake -f main_prog
11096 @end smallexample
11098 @end enumerate
11099 @end ifclear
11101 @node Reducing Size of Executables with unused subprogram/data elimination
11102 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11103 @findex unused subprogram/data elimination
11105 @noindent
11106 This section describes how you can eliminate unused subprograms and data from
11107 your executable just by setting options at compilation time.
11109 @menu
11110 * About unused subprogram/data elimination::
11111 * Compilation options::
11112 * Example of unused subprogram/data elimination::
11113 @end menu
11115 @node About unused subprogram/data elimination
11116 @subsection About unused subprogram/data elimination
11118 @noindent
11119 By default, an executable contains all code and data of its composing objects
11120 (directly linked or coming from statically linked libraries), even data or code
11121 never used by this executable.
11123 This feature will allow you to eliminate such unused code from your
11124 executable, making it smaller (in disk and in memory).
11126 This functionality is available on all Linux platforms except for the IA-64
11127 architecture and on all cross platforms using the ELF binary file format.
11128 In both cases GNU binutils version 2.16 or later are required to enable it.
11130 @node Compilation options
11131 @subsection Compilation options
11133 @noindent
11134 The operation of eliminating the unused code and data from the final executable
11135 is directly performed by the linker.
11137 In order to do this, it has to work with objects compiled with the
11138 following options:
11139 @option{-ffunction-sections} @option{-fdata-sections}.
11140 @cindex @option{-ffunction-sections} (@command{gcc})
11141 @cindex @option{-fdata-sections} (@command{gcc})
11142 These options are usable with C and Ada files.
11143 They will place respectively each
11144 function or data in a separate section in the resulting object file.
11146 Once the objects and static libraries are created with these options, the
11147 linker can perform the dead code elimination. You can do this by setting
11148 the @option{-Wl,--gc-sections} option to gcc command or in the
11149 @option{-largs} section of @command{gnatmake}. This will perform a
11150 garbage collection of code and data never referenced.
11152 If the linker performs a partial link (@option{-r} linker option), then you
11153 will need to provide the entry point using the @option{-e} / @option{--entry}
11154 linker option.
11156 Note that objects compiled without the @option{-ffunction-sections} and
11157 @option{-fdata-sections} options can still be linked with the executable.
11158 However, no dead code elimination will be performed on those objects (they will
11159 be linked as is).
11161 The GNAT static library is now compiled with -ffunction-sections and
11162 -fdata-sections on some platforms. This allows you to eliminate the unused code
11163 and data of the GNAT library from your executable.
11165 @node Example of unused subprogram/data elimination
11166 @subsection Example of unused subprogram/data elimination
11168 @noindent
11169 Here is a simple example:
11171 @smallexample @c ada
11172 @b{with} Aux;
11174 @b{procedure} Test @b{is}
11175 @b{begin}
11176    Aux.Used (10);
11177 @b{end} Test;
11179 @b{package} Aux @b{is}
11180    Used_Data   : Integer;
11181    Unused_Data : Integer;
11183    @b{procedure} Used   (Data : Integer);
11184    @b{procedure} Unused (Data : Integer);
11185 @b{end} Aux;
11187 @b{package} @b{body} Aux @b{is}
11188    @b{procedure} Used (Data : Integer) @b{is}
11189    @b{begin}
11190       Used_Data := Data;
11191    @b{end} Used;
11193    @b{procedure} Unused (Data : Integer) @b{is}
11194    @b{begin}
11195       Unused_Data := Data;
11196    @b{end} Unused;
11197 @b{end} Aux;
11198 @end smallexample
11200 @noindent
11201 @code{Unused} and @code{Unused_Data} are never referenced in this code
11202 excerpt, and hence they may be safely removed from the final executable.
11204 @smallexample
11205 $ gnatmake test
11207 $ nm test | grep used
11208 020015f0 T aux__unused
11209 02005d88 B aux__unused_data
11210 020015cc T aux__used
11211 02005d84 B aux__used_data
11213 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11214      -largs -Wl,--gc-sections
11216 $ nm test | grep used
11217 02005350 T aux__used
11218 0201ffe0 B aux__used_data
11219 @end smallexample
11221 @noindent
11222 It can be observed that the procedure @code{Unused} and the object
11223 @code{Unused_Data} are removed by the linker when using the
11224 appropriate options.
11226 @c ********************************
11227 @node Renaming Files with gnatchop
11228 @chapter Renaming Files with @code{gnatchop}
11229 @findex gnatchop
11231 @noindent
11232 This chapter discusses how to handle files with multiple units by using
11233 the @code{gnatchop} utility. This utility is also useful in renaming
11234 files to meet the standard GNAT default file naming conventions.
11236 @menu
11237 * Handling Files with Multiple Units::
11238 * Operating gnatchop in Compilation Mode::
11239 * Command Line for gnatchop::
11240 * Switches for gnatchop::
11241 * Examples of gnatchop Usage::
11242 @end menu
11244 @node Handling Files with Multiple Units
11245 @section Handling Files with Multiple Units
11247 @noindent
11248 The basic compilation model of GNAT requires that a file submitted to the
11249 compiler have only one unit and there be a strict correspondence
11250 between the file name and the unit name.
11252 The @code{gnatchop} utility allows both of these rules to be relaxed,
11253 allowing GNAT to process files which contain multiple compilation units
11254 and files with arbitrary file names. @code{gnatchop}
11255 reads the specified file and generates one or more output files,
11256 containing one unit per file. The unit and the file name correspond,
11257 as required by GNAT.
11259 If you want to permanently restructure a set of ``foreign'' files so that
11260 they match the GNAT rules, and do the remaining development using the
11261 GNAT structure, you can simply use @command{gnatchop} once, generate the
11262 new set of files and work with them from that point on.
11264 Alternatively, if you want to keep your files in the ``foreign'' format,
11265 perhaps to maintain compatibility with some other Ada compilation
11266 system, you can set up a procedure where you use @command{gnatchop} each
11267 time you compile, regarding the source files that it writes as temporary
11268 files that you throw away.
11270 Note that if your file containing multiple units starts with a byte order
11271 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11272 will each start with a copy of this BOM, meaning that they can be compiled
11273 automatically in UTF-8 mode without needing to specify an explicit encoding.
11275 @node Operating gnatchop in Compilation Mode
11276 @section Operating gnatchop in Compilation Mode
11278 @noindent
11279 The basic function of @code{gnatchop} is to take a file with multiple units
11280 and split it into separate files. The boundary between files is reasonably
11281 clear, except for the issue of comments and pragmas. In default mode, the
11282 rule is that any pragmas between units belong to the previous unit, except
11283 that configuration pragmas always belong to the following unit. Any comments
11284 belong to the following unit. These rules
11285 almost always result in the right choice of
11286 the split point without needing to mark it explicitly and most users will
11287 find this default to be what they want. In this default mode it is incorrect to
11288 submit a file containing only configuration pragmas, or one that ends in
11289 configuration pragmas, to @code{gnatchop}.
11291 However, using a special option to activate ``compilation mode'',
11292 @code{gnatchop}
11293 can perform another function, which is to provide exactly the semantics
11294 required by the RM for handling of configuration pragmas in a compilation.
11295 In the absence of configuration pragmas (at the main file level), this
11296 option has no effect, but it causes such configuration pragmas to be handled
11297 in a quite different manner.
11299 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11300 only configuration pragmas, then this file is appended to the
11301 @file{gnat.adc} file in the current directory. This behavior provides
11302 the required behavior described in the RM for the actions to be taken
11303 on submitting such a file to the compiler, namely that these pragmas
11304 should apply to all subsequent compilations in the same compilation
11305 environment. Using GNAT, the current directory, possibly containing a
11306 @file{gnat.adc} file is the representation
11307 of a compilation environment. For more information on the
11308 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11310 Second, in compilation mode, if @code{gnatchop}
11311 is given a file that starts with
11312 configuration pragmas, and contains one or more units, then these
11313 configuration pragmas are prepended to each of the chopped files. This
11314 behavior provides the required behavior described in the RM for the
11315 actions to be taken on compiling such a file, namely that the pragmas
11316 apply to all units in the compilation, but not to subsequently compiled
11317 units.
11319 Finally, if configuration pragmas appear between units, they are appended
11320 to the previous unit. This results in the previous unit being illegal,
11321 since the compiler does not accept configuration pragmas that follow
11322 a unit. This provides the required RM behavior that forbids configuration
11323 pragmas other than those preceding the first compilation unit of a
11324 compilation.
11326 For most purposes, @code{gnatchop} will be used in default mode. The
11327 compilation mode described above is used only if you need exactly
11328 accurate behavior with respect to compilations, and you have files
11329 that contain multiple units and configuration pragmas. In this
11330 circumstance the use of @code{gnatchop} with the compilation mode
11331 switch provides the required behavior, and is for example the mode
11332 in which GNAT processes the ACVC tests.
11334 @node Command Line for gnatchop
11335 @section Command Line for @code{gnatchop}
11337 @noindent
11338 The @code{gnatchop} command has the form:
11340 @smallexample
11341 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11342 @c      @ovar{directory}
11343 @c Expanding @ovar macro inline (explanation in macro def comments)
11344 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11345       @r{[}@var{directory}@r{]}
11346 @end smallexample
11348 @noindent
11349 The only required argument is the file name of the file to be chopped.
11350 There are no restrictions on the form of this file name. The file itself
11351 contains one or more Ada units, in normal GNAT format, concatenated
11352 together. As shown, more than one file may be presented to be chopped.
11354 When run in default mode, @code{gnatchop} generates one output file in
11355 the current directory for each unit in each of the files.
11357 @var{directory}, if specified, gives the name of the directory to which
11358 the output files will be written. If it is not specified, all files are
11359 written to the current directory.
11361 For example, given a
11362 file called @file{hellofiles} containing
11364 @smallexample @c ada
11365 @group
11366 @cartouche
11367 @b{procedure} hello;
11369 @b{with} Text_IO; @b{use} Text_IO;
11370 @b{procedure} hello @b{is}
11371 @b{begin}
11372    Put_Line ("Hello");
11373 @b{end} hello;
11374 @end cartouche
11375 @end group
11376 @end smallexample
11378 @noindent
11379 the command
11381 @smallexample
11382 $ gnatchop hellofiles
11383 @end smallexample
11385 @noindent
11386 generates two files in the current directory, one called
11387 @file{hello.ads} containing the single line that is the procedure spec,
11388 and the other called @file{hello.adb} containing the remaining text. The
11389 original file is not affected. The generated files can be compiled in
11390 the normal manner.
11392 @noindent
11393 When gnatchop is invoked on a file that is empty or that contains only empty
11394 lines and/or comments, gnatchop will not fail, but will not produce any
11395 new sources.
11397 For example, given a
11398 file called @file{toto.txt} containing
11400 @smallexample @c ada
11401 @group
11402 @cartouche
11403 --@i{  Just a comment}
11404 @end cartouche
11405 @end group
11406 @end smallexample
11408 @noindent
11409 the command
11411 @smallexample
11412 $ gnatchop toto.txt
11413 @end smallexample
11415 @noindent
11416 will not produce any new file and will result in the following warnings:
11418 @smallexample
11419 toto.txt:1:01: warning: empty file, contains no compilation units
11420 no compilation units found
11421 no source files written
11422 @end smallexample
11424 @node Switches for gnatchop
11425 @section Switches for @code{gnatchop}
11427 @noindent
11428 @command{gnatchop} recognizes the following switches:
11430 @table @option
11431 @c !sort!
11433 @item --version
11434 @cindex @option{--version} @command{gnatchop}
11435 Display Copyright and version, then exit disregarding all other options.
11437 @item --help
11438 @cindex @option{--help} @command{gnatchop}
11439 If @option{--version} was not used, display usage, then exit disregarding
11440 all other options.
11442 @item -c
11443 @cindex @option{-c} (@code{gnatchop})
11444 Causes @code{gnatchop} to operate in compilation mode, in which
11445 configuration pragmas are handled according to strict RM rules. See
11446 previous section for a full description of this mode.
11448 @item -gnat@var{xxx}
11449 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11450 used to parse the given file. Not all @var{xxx} options make sense,
11451 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11452 process a source file that uses Latin-2 coding for identifiers.
11454 @item -h
11455 Causes @code{gnatchop} to generate a brief help summary to the standard
11456 output file showing usage information.
11458 @item -k@var{mm}
11459 @cindex @option{-k} (@code{gnatchop})
11460 Limit generated file names to the specified number @code{mm}
11461 of characters.
11462 This is useful if the
11463 resulting set of files is required to be interoperable with systems
11464 which limit the length of file names.
11465 No space is allowed between the @option{-k} and the numeric value. The numeric
11466 value may be omitted in which case a default of @option{-k8},
11467 suitable for use
11468 with DOS-like file systems, is used. If no @option{-k} switch
11469 is present then
11470 there is no limit on the length of file names.
11472 @item -p
11473 @cindex @option{-p} (@code{gnatchop})
11474 Causes the file modification time stamp of the input file to be
11475 preserved and used for the time stamp of the output file(s). This may be
11476 useful for preserving coherency of time stamps in an environment where
11477 @code{gnatchop} is used as part of a standard build process.
11479 @item -q
11480 @cindex @option{-q} (@code{gnatchop})
11481 Causes output of informational messages indicating the set of generated
11482 files to be suppressed. Warnings and error messages are unaffected.
11484 @item -r
11485 @cindex @option{-r} (@code{gnatchop})
11486 @findex Source_Reference
11487 Generate @code{Source_Reference} pragmas. Use this switch if the output
11488 files are regarded as temporary and development is to be done in terms
11489 of the original unchopped file. This switch causes
11490 @code{Source_Reference} pragmas to be inserted into each of the
11491 generated files to refers back to the original file name and line number.
11492 The result is that all error messages refer back to the original
11493 unchopped file.
11494 In addition, the debugging information placed into the object file (when
11495 the @option{-g} switch of @command{gcc} or @command{gnatmake} is
11496 specified)
11497 also refers back to this original file so that tools like profilers and
11498 debuggers will give information in terms of the original unchopped file.
11500 If the original file to be chopped itself contains
11501 a @code{Source_Reference}
11502 pragma referencing a third file, then gnatchop respects
11503 this pragma, and the generated @code{Source_Reference} pragmas
11504 in the chopped file refer to the original file, with appropriate
11505 line numbers. This is particularly useful when @code{gnatchop}
11506 is used in conjunction with @code{gnatprep} to compile files that
11507 contain preprocessing statements and multiple units.
11509 @item -v
11510 @cindex @option{-v} (@code{gnatchop})
11511 Causes @code{gnatchop} to operate in verbose mode. The version
11512 number and copyright notice are output, as well as exact copies of
11513 the gnat1 commands spawned to obtain the chop control information.
11515 @item -w
11516 @cindex @option{-w} (@code{gnatchop})
11517 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11518 fatal error if there is already a file with the same name as a
11519 file it would otherwise output, in other words if the files to be
11520 chopped contain duplicated units. This switch bypasses this
11521 check, and causes all but the last instance of such duplicated
11522 units to be skipped.
11524 @item --GCC=@var{xxxx}
11525 @cindex @option{--GCC=} (@code{gnatchop})
11526 Specify the path of the GNAT parser to be used. When this switch is used,
11527 no attempt is made to add the prefix to the GNAT parser executable.
11528 @end table
11530 @node Examples of gnatchop Usage
11531 @section Examples of @code{gnatchop} Usage
11533 @table @code
11534 @item gnatchop -w hello_s.ada prerelease/files
11536 Chops the source file @file{hello_s.ada}. The output files will be
11537 placed in the directory @file{prerelease/files},
11538 overwriting any
11539 files with matching names in that directory (no files in the current
11540 directory are modified).
11542 @item gnatchop archive
11543 Chops the source file @file{archive}
11544 into the current directory. One
11545 useful application of @code{gnatchop} is in sending sets of sources
11546 around, for example in email messages. The required sources are simply
11547 concatenated (for example, using a Unix @code{cat}
11548 command), and then
11549 @command{gnatchop} is used at the other end to reconstitute the original
11550 file names.
11552 @item gnatchop file1 file2 file3 direc
11553 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11554 the resulting files in the directory @file{direc}. Note that if any units
11555 occur more than once anywhere within this set of files, an error message
11556 is generated, and no files are written. To override this check, use the
11557 @option{-w} switch,
11558 in which case the last occurrence in the last file will
11559 be the one that is output, and earlier duplicate occurrences for a given
11560 unit will be skipped.
11561 @end table
11563 @node Configuration Pragmas
11564 @chapter Configuration Pragmas
11565 @cindex Configuration pragmas
11566 @cindex Pragmas, configuration
11568 @menu
11569 * Handling of Configuration Pragmas::
11570 * The Configuration Pragmas Files::
11571 @end menu
11573 @noindent
11574 Configuration pragmas include those pragmas described as
11575 such in the Ada Reference Manual, as well as
11576 implementation-dependent pragmas that are configuration pragmas.
11577 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11578 for details on these additional GNAT-specific configuration pragmas.
11579 Most notably, the pragma @code{Source_File_Name}, which allows
11580 specifying non-default names for source files, is a configuration
11581 pragma. The following is a complete list of configuration pragmas
11582 recognized by GNAT:
11584 @smallexample
11585    Ada_83
11586    Ada_95
11587    Ada_05
11588    Ada_2005
11589    Ada_12
11590    Ada_2012
11591    Allow_Integer_Address
11592    Annotate
11593    Assertion_Policy
11594    Assume_No_Invalid_Values
11595    C_Pass_By_Copy
11596    Check_Name
11597    Check_Policy
11598    Compile_Time_Error
11599    Compile_Time_Warning
11600    Compiler_Unit
11601    Component_Alignment
11602    Convention_Identifier
11603    Debug_Policy
11604    Detect_Blocking
11605    Default_Storage_Pool
11606    Discard_Names
11607    Elaboration_Checks
11608    Eliminate
11609    Extend_System
11610    Extensions_Allowed
11611    External_Name_Casing
11612    Fast_Math
11613    Favor_Top_Level
11614    Float_Representation
11615    Implicit_Packing
11616    Initialize_Scalars
11617    Interrupt_State
11618    License
11619    Locking_Policy
11620    Long_Float
11621    No_Run_Time
11622    No_Strict_Aliasing
11623    Normalize_Scalars
11624    Optimize_Alignment
11625    Persistent_BSS
11626    Polling
11627    Priority_Specific_Dispatching
11628    Profile
11629    Profile_Warnings
11630    Propagate_Exceptions
11631    Queuing_Policy
11632    Ravenscar
11633    Restricted_Run_Time
11634    Restrictions
11635    Restrictions_Warnings
11636    Reviewable
11637    Short_Circuit_And_Or
11638    Source_File_Name
11639    Source_File_Name_Project
11640    SPARK_Mode
11641    Style_Checks
11642    Suppress
11643    Suppress_Exception_Locations
11644    Task_Dispatching_Policy
11645    Universal_Data
11646    Unsuppress
11647    Use_VADS_Size
11648    Validity_Checks
11649    Warnings
11650    Wide_Character_Encoding
11651 @end smallexample
11653 @node Handling of Configuration Pragmas
11654 @section Handling of Configuration Pragmas
11656 Configuration pragmas may either appear at the start of a compilation
11657 unit, or they can appear in a configuration pragma file to apply to
11658 all compilations performed in a given compilation environment.
11660 GNAT also provides the @code{gnatchop} utility to provide an automatic
11661 way to handle configuration pragmas following the semantics for
11662 compilations (that is, files with multiple units), described in the RM.
11663 See @ref{Operating gnatchop in Compilation Mode} for details.
11664 However, for most purposes, it will be more convenient to edit the
11665 @file{gnat.adc} file that contains configuration pragmas directly,
11666 as described in the following section.
11668 In the case of @code{Restrictions} pragmas appearing as configuration
11669 pragmas in individual compilation units, the exact handling depends on
11670 the type of restriction.
11672 Restrictions that require partition-wide consistency (like
11673 @code{No_Tasking}) are
11674 recognized wherever they appear
11675 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11676 unit. This makes sense since the binder will in any case insist on seeing
11677 consistent use, so any unit not conforming to any restrictions that are
11678 anywhere in the partition will be rejected, and you might as well find
11679 that out at compile time rather than at bind time.
11681 For restrictions that do not require partition-wide consistency, e.g.
11682 SPARK or No_Implementation_Attributes, in general the restriction applies
11683 only to the unit in which the pragma appears, and not to any other units.
11685 The exception is No_Elaboration_Code which always applies to the entire
11686 object file from a compilation, i.e. to the body, spec, and all subunits.
11687 This restriction can be specified in a configuration pragma file, or it
11688 can be on the body and/or the spec (in eithe case it applies to all the
11689 relevant units). It can appear on a subunit only if it has previously
11690 appeared in the body of spec.
11692 @node The Configuration Pragmas Files
11693 @section The Configuration Pragmas Files
11694 @cindex @file{gnat.adc}
11696 @noindent
11697 In GNAT a compilation environment is defined by the current
11698 directory at the time that a compile command is given. This current
11699 directory is searched for a file whose name is @file{gnat.adc}. If
11700 this file is present, it is expected to contain one or more
11701 configuration pragmas that will be applied to the current compilation.
11702 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11703 considered. When taken into account, @file{gnat.adc} is added to the
11704 dependencies, so that if @file{gnat.adc} is modified later, an invocation of
11705 @command{gnatmake} will recompile the source.
11707 Configuration pragmas may be entered into the @file{gnat.adc} file
11708 either by running @code{gnatchop} on a source file that consists only of
11709 configuration pragmas, or more conveniently by direct editing of the
11710 @file{gnat.adc} file, which is a standard format source file.
11712 In addition to @file{gnat.adc}, additional files containing configuration
11713 pragmas may be applied to the current compilation using the switch
11714 @option{-gnatec=}@var{path}. @var{path} must designate an existing file that
11715 contains only configuration pragmas. These configuration pragmas are
11716 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11717 is present and switch @option{-gnatA} is not used).
11719 It is allowable to specify several switches @option{-gnatec=}, all of which
11720 will be taken into account.
11722 Files containing configuration pragmas specified with switches
11723 @option{-gnatec=} are added to the dependencies, unless they are
11724 temporary files. A file is considered temporary if its name ends in
11725 @file{.tmp} or @file{.TMP}. Certain tools follow this naming
11726 convention because they pass information to @command{gcc} via
11727 temporary files that are immediately deleted; it doesn't make sense to
11728 depend on a file that no longer exists. Such tools include
11729 @command{gprbuild}, @command{gnatmake}, and @command{gnatcheck}.
11731 If you are using project file, a separate mechanism is provided using
11732 project attributes, see @ref{Specifying Configuration Pragmas} for more
11733 details.
11736 @node Handling Arbitrary File Naming Conventions with gnatname
11737 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
11738 @cindex Arbitrary File Naming Conventions
11740 @menu
11741 * Arbitrary File Naming Conventions::
11742 * Running gnatname::
11743 * Switches for gnatname::
11744 * Examples of gnatname Usage::
11745 @end menu
11747 @node Arbitrary File Naming Conventions
11748 @section Arbitrary File Naming Conventions
11750 @noindent
11751 The GNAT compiler must be able to know the source file name of a compilation
11752 unit.  When using the standard GNAT default file naming conventions
11753 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11754 does not need additional information.
11756 @noindent
11757 When the source file names do not follow the standard GNAT default file naming
11758 conventions, the GNAT compiler must be given additional information through
11759 a configuration pragmas file (@pxref{Configuration Pragmas})
11760 or a project file.
11761 When the non-standard file naming conventions are well-defined,
11762 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11763 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11764 if the file naming conventions are irregular or arbitrary, a number
11765 of pragma @code{Source_File_Name} for individual compilation units
11766 must be defined.
11767 To help maintain the correspondence between compilation unit names and
11768 source file names within the compiler,
11769 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11770 set of files.
11772 @node Running gnatname
11773 @section Running @code{gnatname}
11775 @noindent
11776 The usual form of the @code{gnatname} command is
11778 @smallexample
11779 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11780 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11781 @c Expanding @ovar macro inline (explanation in macro def comments)
11782 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11783       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11784 @end smallexample
11786 @noindent
11787 All of the arguments are optional. If invoked without any argument,
11788 @code{gnatname} will display its usage.
11790 @noindent
11791 When used with at least one naming pattern, @code{gnatname} will attempt to
11792 find all the compilation units in files that follow at least one of the
11793 naming patterns. To find these compilation units,
11794 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11795 regular files.
11797 @noindent
11798 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11799 Each Naming Pattern is enclosed between double quotes (or single
11800 quotes on Windows).
11801 A Naming Pattern is a regular expression similar to the wildcard patterns
11802 used in file names by the Unix shells or the DOS prompt.
11804 @noindent
11805 @code{gnatname} may be called with several sections of directories/patterns.
11806 Sections are separated by switch @code{--and}. In each section, there must be
11807 at least one pattern. If no directory is specified in a section, the current
11808 directory (or the project directory is @code{-P} is used) is implied.
11809 The options other that the directory switches and the patterns apply globally
11810 even if they are in different sections.
11812 @noindent
11813 Examples of Naming Patterns are
11815 @smallexample
11816    "*.[12].ada"
11817    "*.ad[sb]*"
11818    "body_*"    "spec_*"
11819 @end smallexample
11821 @noindent
11822 For a more complete description of the syntax of Naming Patterns,
11823 see the second kind of regular expressions described in @file{g-regexp.ads}
11824 (the ``Glob'' regular expressions).
11826 @noindent
11827 When invoked with no switch @code{-P}, @code{gnatname} will create a
11828 configuration pragmas file @file{gnat.adc} in the current working directory,
11829 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11830 unit.
11832 @node Switches for gnatname
11833 @section Switches for @code{gnatname}
11835 @noindent
11836 Switches for @code{gnatname} must precede any specified Naming Pattern.
11838 @noindent
11839 You may specify any of the following switches to @code{gnatname}:
11841 @table @option
11842 @c !sort!
11844 @item --version
11845 @cindex @option{--version} @command{gnatname}
11846 Display Copyright and version, then exit disregarding all other options.
11848 @item --help
11849 @cindex @option{--help} @command{gnatname}
11850 If @option{--version} was not used, display usage, then exit disregarding
11851 all other options.
11853 @item --subdirs=<dir>
11854 Real object, library or exec directories are subdirectories <dir> of the
11855 specified ones.
11857 @item --no-backup
11858 Do not create a backup copy of an existing project file.
11860 @item --and
11861 Start another section of directories/patterns.
11863 @item -c@file{file}
11864 @cindex @option{-c} (@code{gnatname})
11865 Create a configuration pragmas file @file{file} (instead of the default
11866 @file{gnat.adc}).
11867 There may be zero, one or more space between @option{-c} and
11868 @file{file}.
11869 @file{file} may include directory information. @file{file} must be
11870 writable. There may be only one switch @option{-c}.
11871 When a switch @option{-c} is
11872 specified, no switch @option{-P} may be specified (see below).
11874 @item -d@file{dir}
11875 @cindex @option{-d} (@code{gnatname})
11876 Look for source files in directory @file{dir}. There may be zero, one or more
11877 spaces between @option{-d} and @file{dir}.
11878 @file{dir} may end with @code{/**}, that is it may be of the form
11879 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
11880 subdirectories, recursively, have to be searched for sources.
11881 When a switch @option{-d}
11882 is specified, the current working directory will not be searched for source
11883 files, unless it is explicitly specified with a @option{-d}
11884 or @option{-D} switch.
11885 Several switches @option{-d} may be specified.
11886 If @file{dir} is a relative path, it is relative to the directory of
11887 the configuration pragmas file specified with switch
11888 @option{-c},
11889 or to the directory of the project file specified with switch
11890 @option{-P} or,
11891 if neither switch @option{-c}
11892 nor switch @option{-P} are specified, it is relative to the
11893 current working directory. The directory
11894 specified with switch @option{-d} must exist and be readable.
11896 @item -D@file{file}
11897 @cindex @option{-D} (@code{gnatname})
11898 Look for source files in all directories listed in text file @file{file}.
11899 There may be zero, one or more spaces between @option{-D}
11900 and @file{file}.
11901 @file{file} must be an existing, readable text file.
11902 Each nonempty line in @file{file} must be a directory.
11903 Specifying switch @option{-D} is equivalent to specifying as many
11904 switches @option{-d} as there are nonempty lines in
11905 @file{file}.
11907 @item -eL
11908 Follow symbolic links when processing project files.
11910 @item -f@file{pattern}
11911 @cindex @option{-f} (@code{gnatname})
11912 Foreign patterns. Using this switch, it is possible to add sources of languages
11913 other than Ada to the list of sources of a project file.
11914 It is only useful if a -P switch is used.
11915 For example,
11916 @smallexample
11917 gnatname -Pprj -f"*.c" "*.ada"
11918 @end smallexample
11919 @noindent
11920 will look for Ada units in all files with the @file{.ada} extension,
11921 and will add to the list of file for project @file{prj.gpr} the C files
11922 with extension @file{.c}.
11924 @item -h
11925 @cindex @option{-h} (@code{gnatname})
11926 Output usage (help) information. The output is written to @file{stdout}.
11928 @item -P@file{proj}
11929 @cindex @option{-P} (@code{gnatname})
11930 Create or update project file @file{proj}. There may be zero, one or more space
11931 between @option{-P} and @file{proj}. @file{proj} may include directory
11932 information. @file{proj} must be writable.
11933 There may be only one switch @option{-P}.
11934 When a switch @option{-P} is specified,
11935 no switch @option{-c} may be specified.
11936 On all platforms, except on VMS, when @code{gnatname} is invoked for an
11937 existing project file <proj>.gpr, a backup copy of the project file is created
11938 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
11939 non negative number that makes this backup copy a new file.
11941 @item -v
11942 @cindex @option{-v} (@code{gnatname})
11943 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11944 This includes name of the file written, the name of the directories to search
11945 and, for each file in those directories whose name matches at least one of
11946 the Naming Patterns, an indication of whether the file contains a unit,
11947 and if so the name of the unit.
11949 @item -v -v
11950 @cindex @option{-v -v} (@code{gnatname})
11951 Very Verbose mode. In addition to the output produced in verbose mode,
11952 for each file in the searched directories whose name matches none of
11953 the Naming Patterns, an indication is given that there is no match.
11955 @item -x@file{pattern}
11956 @cindex @option{-x} (@code{gnatname})
11957 Excluded patterns. Using this switch, it is possible to exclude some files
11958 that would match the name patterns. For example,
11959 @smallexample
11960 gnatname -x "*_nt.ada" "*.ada"
11961 @end smallexample
11962 @noindent
11963 will look for Ada units in all files with the @file{.ada} extension,
11964 except those whose names end with @file{_nt.ada}.
11966 @end table
11968 @node Examples of gnatname Usage
11969 @section Examples of @code{gnatname} Usage
11972 @smallexample
11973 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11974 @end smallexample
11976 @noindent
11977 In this example, the directory @file{/home/me} must already exist
11978 and be writable. In addition, the directory
11979 @file{/home/me/sources} (specified by
11980 @option{-d sources}) must exist and be readable.
11982 Note the optional spaces after @option{-c} and @option{-d}.
11984 @smallexample
11985 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11986   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11987 @end smallexample
11989 Note that several switches @option{-d} may be used,
11990 even in conjunction with one or several switches
11991 @option{-D}. Several Naming Patterns and one excluded pattern
11992 are used in this example.
11994 @c *****************************************
11995 @c * G N A T  P r o j e c t  M a n a g e r *
11996 @c *****************************************
11998 @c ------ macros for projects.texi
11999 @c These macros are needed when building the gprbuild documentation, but
12000 @c should have no effect in the gnat user's guide
12002 @macro CODESAMPLE{TXT}
12003 @smallexample
12004 @group
12005 \TXT\
12006 @end group
12007 @end smallexample
12008 @end macro
12010 @macro PROJECTFILE{TXT}
12011 @CODESAMPLE{\TXT\}
12012 @end macro
12014 @c simulates a newline when in a @CODESAMPLE
12015 @macro NL{}
12016 @end macro
12018 @macro TIP{TXT}
12019 @quotation
12020 @noindent
12021 \TXT\
12022 @end quotation
12023 @end macro
12025 @macro TIPHTML{TXT}
12026 \TXT\
12027 @end macro
12029 @macro IMPORTANT{TXT}
12030 @quotation
12031 @noindent
12032 \TXT\
12033 @end quotation
12035 @end macro
12037 @macro NOTE{TXT}
12038 @quotation
12039 @noindent
12040 \TXT\
12041 @end quotation
12042 @end macro
12044 @include projects.texi
12046 @c ---------------------------------------------
12047 @c Tools Supporting Project Files
12048 @c ---------------------------------------------
12050 @node Tools Supporting Project Files
12051 @chapter Tools Supporting Project Files
12053 @noindent
12055 @menu
12056 * gnatmake and Project Files::
12057 * The GNAT Driver and Project Files::
12058 @end menu
12060 @c ---------------------------------------------
12061 @node gnatmake and Project Files
12062 @section gnatmake and Project Files
12063 @c ---------------------------------------------
12065 @noindent
12066 This section covers several topics related to @command{gnatmake} and
12067 project files: defining switches for @command{gnatmake}
12068 and for the tools that it invokes; specifying configuration pragmas;
12069 the use of the @code{Main} attribute; building and rebuilding library project
12070 files.
12072 @menu
12073 * Switches Related to Project Files::
12074 * Switches and Project Files::
12075 * Specifying Configuration Pragmas::
12076 * Project Files and Main Subprograms::
12077 * Library Project Files::
12078 @end menu
12080 @c ---------------------------------------------
12081 @node Switches Related to Project Files
12082 @subsection Switches Related to Project Files
12083 @c ---------------------------------------------
12085 @noindent
12086 The following switches are used by GNAT tools that support project files:
12088 @table @option
12090 @item -P@var{project}
12091 @cindex @option{-P} (any project-aware tool)
12092 Indicates the name of a project file. This project file will be parsed with
12093 the verbosity indicated by @option{-vP@emph{x}},
12094 if any, and using the external references indicated
12095 by @option{-X} switches, if any.
12096 There may zero, one or more spaces between @option{-P} and @var{project}.
12098 There must be only one @option{-P} switch on the command line.
12100 Since the Project Manager parses the project file only after all the switches
12101 on the command line are checked, the order of the switches
12102 @option{-P},
12103 @option{-vP@emph{x}}
12104 or @option{-X} is not significant.
12106 @item -X@var{name=value}
12107 @cindex @option{-X} (any project-aware tool)
12108 Indicates that external variable @var{name} has the value @var{value}.
12109 The Project Manager will use this value for occurrences of
12110 @code{external(name)} when parsing the project file.
12112 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12113 put between quotes.
12114 @smallexample
12115   -XOS=NT
12116   -X"user=John Doe"
12117 @end smallexample
12119 Several @option{-X} switches can be used simultaneously.
12120 If several @option{-X} switches specify the same
12121 @var{name}, only the last one is used.
12123 An external variable specified with a @option{-X} switch
12124 takes precedence over the value of the same name in the environment.
12126 @item -vP@emph{x}
12127 @cindex @option{-vP} (any project-aware tool)
12128 Indicates the verbosity of the parsing of GNAT project files.
12130 @option{-vP0} means Default;
12131 @option{-vP1} means Medium;
12132 @option{-vP2} means High.
12135 The default is Default: no output for syntactically correct
12136 project files.
12137 If several @option{-vP@emph{x}} switches are present,
12138 only the last one is used.
12140 @item -aP<dir>
12141 @cindex @option{-aP} (any project-aware tool)
12142 Add directory <dir> at the beginning of the project search path, in order,
12143 after the current working directory.
12145 @item -eL
12146 @cindex @option{-eL} (any project-aware tool)
12147 Follow all symbolic links when processing project files.
12149 @item --subdirs=<subdir>
12150 @cindex @option{--subdirs=} (gnatmake and gnatclean)
12151 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12152 indicate that the real directories (except the source directories) are the
12153 subdirectories <subdir> of the directories specified in the project files.
12154 This applies in particular to object directories, library directories and
12155 exec directories. If the subdirectories do not exist, they are created
12156 automatically.
12158 @end table
12160 @c ---------------------------------------------
12161 @node Switches and Project Files
12162 @subsection Switches and Project Files
12163 @c ---------------------------------------------
12165 @noindent
12167 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12168 @code{Linker}, you can specify a @code{Default_Switches}
12169 attribute, a @code{Switches} attribute, or both;
12170 as their names imply, these switch-related
12171 attributes affect the switches that are used for each of these GNAT
12172 components when
12173 @command{gnatmake} is invoked.  As will be explained below, these
12174 component-specific switches precede
12175 the switches provided on the @command{gnatmake} command line.
12177 The @code{Default_Switches} attribute is an attribute
12178 indexed by language name (case insensitive) whose value is a string list.
12179 For example:
12181 @smallexample @c projectfile
12182 @group
12183 @b{package} Compiler @b{is}
12184   @b{for} Default_Switches ("Ada")
12185       @b{use} ("-gnaty",
12186            "-v");
12187 @b{end} Compiler;
12188 @end group
12189 @end smallexample
12191 @noindent
12192 The @code{Switches} attribute is indexed on a file name (which may or may
12193 not be case sensitive, depending
12194 on the operating system) whose value is a string list.  For example:
12196 @smallexample @c projectfile
12197 @group
12198 @b{package} Builder @b{is}
12199    @b{for} Switches ("main1.adb")
12200        @b{use} ("-O2");
12201    @b{for} Switches ("main2.adb")
12202        @b{use} ("-g");
12203 @b{end} Builder;
12204 @end group
12205 @end smallexample
12207 @noindent
12208 For the @code{Builder} package, the file names must designate source files
12209 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12210 file names must designate @file{ALI} or source files for main subprograms.
12211 In each case just the file name without an explicit extension is acceptable.
12213 For each tool used in a program build (@command{gnatmake}, the compiler, the
12214 binder, and the linker), the corresponding package @dfn{contributes} a set of
12215 switches for each file on which the tool is invoked, based on the
12216 switch-related attributes defined in the package.
12217 In particular, the switches
12218 that each of these packages contributes for a given file @var{f} comprise:
12220 @itemize @bullet
12221 @item the value of attribute @code{Switches (@var{f})},
12222   if it is specified in the package for the given file,
12223 @item otherwise, the value of @code{Default_Switches ("Ada")},
12224   if it is specified in the package.
12226 @end itemize
12228 @noindent
12229 If neither of these attributes is defined in the package, then the package does
12230 not contribute any switches for the given file.
12232 When @command{gnatmake} is invoked on a file, the switches comprise
12233 two sets, in the following order: those contributed for the file
12234 by the @code{Builder} package;
12235 and the switches passed on the command line.
12237 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12238 the switches passed to the tool comprise three sets,
12239 in the following order:
12241 @enumerate
12242 @item
12243 the applicable switches contributed for the file
12244 by the @code{Builder} package in the project file supplied on the command line;
12246 @item
12247 those contributed for the file by the package (in the relevant project file --
12248 see below) corresponding to the tool; and
12250 @item
12251 the applicable switches passed on the command line.
12252 @end enumerate
12254 The term @emph{applicable switches} reflects the fact that
12255 @command{gnatmake} switches may or may not be passed to individual
12256 tools, depending on the individual switch.
12258 @command{gnatmake} may invoke the compiler on source files from different
12259 projects. The Project Manager will use the appropriate project file to
12260 determine the @code{Compiler} package for each source file being compiled.
12261 Likewise for the @code{Binder} and @code{Linker} packages.
12263 As an example, consider the following package in a project file:
12265 @smallexample @c projectfile
12266 @group
12267 @b{project} Proj1 @b{is}
12268    @b{package} Compiler @b{is}
12269       @b{for} Default_Switches ("Ada")
12270           @b{use} ("-g");
12271       @b{for} Switches ("a.adb")
12272           @b{use} ("-O1");
12273       @b{for} Switches ("b.adb")
12274           @b{use} ("-O2",
12275                "-gnaty");
12276    @b{end} Compiler;
12277 @b{end} Proj1;
12278 @end group
12279 @end smallexample
12281 @noindent
12282 If @command{gnatmake} is invoked with this project file, and it needs to
12283 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12284 @file{a.adb} will be compiled with the switch
12285 @option{-O1},
12286 @file{b.adb} with switches
12287 @option{-O2}
12288 and @option{-gnaty},
12289 and @file{c.adb} with @option{-g}.
12291 The following example illustrates the ordering of the switches
12292 contributed by different packages:
12294 @smallexample @c projectfile
12295 @group
12296 @b{project} Proj2 @b{is}
12297    @b{package} Builder @b{is}
12298       @b{for} Switches ("main.adb")
12299           @b{use} ("-g",
12300                "-O1",
12301                "-f");
12302    @b{end} Builder;
12303 @end group
12305 @group
12306    @b{package} Compiler @b{is}
12307       @b{for} Switches ("main.adb")
12308           @b{use} ("-O2");
12309    @b{end} Compiler;
12310 @b{end} Proj2;
12311 @end group
12312 @end smallexample
12314 @noindent
12315 If you issue the command:
12317 @smallexample
12318     gnatmake -Pproj2 -O0 main
12319 @end smallexample
12321 @noindent
12322 then the compiler will be invoked on @file{main.adb} with the following
12323 sequence of switches
12325 @smallexample
12326    -g -O1 -O2 -O0
12327 @end smallexample
12329 @noindent
12330 with the last @option{-O}
12331 switch having precedence over the earlier ones;
12332 several other switches
12333 (such as @option{-c}) are added implicitly.
12335 The switches
12336 @option{-g}
12337 and @option{-O1} are contributed by package
12338 @code{Builder},  @option{-O2} is contributed
12339 by the package @code{Compiler}
12340 and @option{-O0} comes from the command line.
12342 The @option{-g}
12343 switch will also be passed in the invocation of
12344 @command{Gnatlink.}
12346 A final example illustrates switch contributions from packages in different
12347 project files:
12349 @smallexample @c projectfile
12350 @group
12351 @b{project} Proj3 @b{is}
12352    @b{for} Source_Files @b{use} ("pack.ads", "pack.adb");
12353    @b{package} Compiler @b{is}
12354       @b{for} Default_Switches ("Ada")
12355           @b{use} ("-gnata");
12356    @b{end} Compiler;
12357 @b{end} Proj3;
12358 @end group
12360 @group
12361 @b{with} "Proj3";
12362 @b{project} Proj4 @b{is}
12363    @b{for} Source_Files @b{use} ("foo_main.adb", "bar_main.adb");
12364    @b{package} Builder @b{is}
12365       @b{for} Switches ("foo_main.adb")
12366           @b{use} ("-s",
12367                "-g");
12368    @b{end} Builder;
12369 @b{end} Proj4;
12370 @end group
12372 @group
12373 --@i{ Ada source file:}
12374 @b{with} Pack;
12375 @b{procedure} Foo_Main @b{is}
12376    @dots{}
12377 @b{end} Foo_Main;
12378 @end group
12379 @end smallexample
12381 @noindent
12382 If the command is
12383 @smallexample
12384 gnatmake -PProj4 foo_main.adb -cargs -gnato
12385 @end smallexample
12387 @noindent
12388 then the switches passed to the compiler for @file{foo_main.adb} are
12389 @option{-g} (contributed by the package @code{Proj4.Builder}) and
12390 @option{-gnato} (passed on the command line).
12391 When the imported package @code{Pack} is compiled, the switches used
12392 are @option{-g} from @code{Proj4.Builder},
12393 @option{-gnata} (contributed from package @code{Proj3.Compiler},
12394 and @option{-gnato} from the command line.
12396 When using @command{gnatmake} with project files, some switches or
12397 arguments may be expressed as relative paths. As the working directory where
12398 compilation occurs may change, these relative paths are converted to absolute
12399 paths. For the switches found in a project file, the relative paths
12400 are relative to the project file directory, for the switches on the command
12401 line, they are relative to the directory where @command{gnatmake} is invoked.
12402 The switches for which this occurs are:
12406 -aO,
12407 -aL,
12408 -aI, as well as all arguments that are not switches (arguments to
12409 switch
12410 -o, object files specified in package @code{Linker} or after
12411 -largs on the command line). The exception to this rule is the switch
12412 --RTS= for which a relative path argument is never converted.
12414 @c ---------------------------------------------
12415 @node Specifying Configuration Pragmas
12416 @subsection Specifying Configuration Pragmas
12417 @c ---------------------------------------------
12419 @noindent
12420 When using @command{gnatmake} with project files, if there exists a file
12421 @file{gnat.adc} that contains configuration pragmas, this file will be
12422 ignored.
12424 Configuration pragmas can be defined by means of the following attributes in
12425 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12426 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12428 Both these attributes are single string attributes. Their values is the path
12429 name of a file containing configuration pragmas. If a path name is relative,
12430 then it is relative to the project directory of the project file where the
12431 attribute is defined.
12433 When compiling a source, the configuration pragmas used are, in order,
12434 those listed in the file designated by attribute
12435 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12436 project file, if it is specified, and those listed in the file designated by
12437 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12438 the project file of the source, if it exists.
12440 @c ---------------------------------------------
12441 @node Project Files and Main Subprograms
12442 @subsection Project Files and Main Subprograms
12443 @c ---------------------------------------------
12445 @noindent
12446 When using a project file, you can invoke @command{gnatmake}
12447 with one or several main subprograms, by specifying their source files on the
12448 command line.
12450 @smallexample
12451     gnatmake -Pprj main1.adb main2.adb main3.adb
12452 @end smallexample
12454 @noindent
12455 Each of these needs to be a source file of the same project, except
12456 when the switch -u is used.
12458 When -u is not used, all the mains need to be sources of the
12459 same project, one of the project in the tree rooted at the project specified
12460 on the command line. The package @code{Builder} of this common project, the
12461 "main project" is the one that is considered by @command{gnatmake}.
12463 When -u is used, the specified source files may be in projects
12464 imported directly or indirectly by the project specified on the command line.
12465 Note that if such a source file is not part of the project specified on the
12466 command line, the switches found in package @code{Builder} of the
12467 project specified on the command line, if any, that are transmitted
12468 to the compiler will still be used, not those found in the project file of
12469 the source file.
12471 When using a project file, you can also invoke @command{gnatmake} without
12472 explicitly specifying any main, and the effect depends on whether you have
12473 defined the @code{Main} attribute.  This attribute has a string list value,
12474 where each element in the list is the name of a source file (the file
12475 extension is optional) that contains a unit that can be a main subprogram.
12477 If the @code{Main} attribute is defined in a project file as a non-empty
12478 string list and the switch @option{-u} is not used on the command
12479 line, then invoking @command{gnatmake} with this project file but without any
12480 main on the command line is equivalent to invoking @command{gnatmake} with all
12481 the file names in the @code{Main} attribute on the command line.
12483 Example:
12484 @smallexample @c projectfile
12485 @group
12486    @b{project} Prj @b{is}
12487       @b{for} Main @b{use} ("main1.adb", "main2.adb", "main3.adb");
12488    @b{end} Prj;
12489 @end group
12490 @end smallexample
12492 @noindent
12493 With this project file, @code{"gnatmake -Pprj"}
12494 is equivalent to
12495 @code{"gnatmake -Pprj main1.adb main2.adb main3.adb"}.
12497 When the project attribute @code{Main} is not specified, or is specified
12498 as an empty string list, or when the switch @option{-u} is used on the command
12499 line, then invoking @command{gnatmake} with no main on the command line will
12500 result in all immediate sources of the project file being checked, and
12501 potentially recompiled. Depending on the presence of the switch @option{-u},
12502 sources from other project files on which the immediate sources of the main
12503 project file depend are also checked and potentially recompiled. In other
12504 words, the @option{-u} switch is applied to all of the immediate sources of the
12505 main project file.
12507 When no main is specified on the command line and attribute @code{Main} exists
12508 and includes several mains, or when several mains are specified on the
12509 command line, the default switches in package @code{Builder} will
12510 be used for all mains, even if there are specific switches
12511 specified for one or several mains.
12513 But the switches from package @code{Binder} or @code{Linker} will be
12514 the specific switches for each main, if they are specified.
12516 @c ---------------------------------------------
12517 @node Library Project Files
12518 @subsection Library Project Files
12519 @c ---------------------------------------------
12521 @noindent
12522 When @command{gnatmake} is invoked with a main project file that is a library
12523 project file, it is not allowed to specify one or more mains on the command
12524 line.
12526 When a library project file is specified, switches -b and
12527 -l have special meanings.
12529 @itemize @bullet
12530 @item -b is only allowed for stand-alone libraries. It indicates
12531   to @command{gnatmake} that @command{gnatbind} should be invoked for the
12532   library.
12534 @item -l may be used for all library projects. It indicates
12535   to @command{gnatmake} that the binder generated file should be compiled
12536   (in the case of a stand-alone library) and that the library should be built.
12537 @end itemize
12539 @c ---------------------------------------------
12540 @node The GNAT Driver and Project Files
12541 @section The GNAT Driver and Project Files
12542 @c ---------------------------------------------
12544 @noindent
12545 A number of GNAT tools, other than @command{gnatmake}
12546 can benefit from project files:
12547 (@command{gnatbind},
12548 @ifclear FSFEDITION
12549 @command{gnatcheck},
12550 @end ifclear
12551 @command{gnatclean},
12552 @ifclear FSFEDITION
12553 @command{gnatelim},
12554 @end ifclear
12555 @command{gnatfind},
12556 @command{gnatlink},
12557 @command{gnatls},
12558 @ifclear FSFEDITION
12559 @command{gnatmetric},
12560 @command{gnatpp},
12561 @command{gnatstub},
12562 @end ifclear
12563 and @command{gnatxref}). However, none of these tools can be invoked
12564 directly with a project file switch (@option{-P}).
12565 They must be invoked through the @command{gnat} driver.
12567 The @command{gnat} driver is a wrapper that accepts a number of commands and
12568 calls the corresponding tool. It was designed initially for VMS platforms (to
12569 convert VMS qualifiers to Unix-style switches), but it is now available on all
12570 GNAT platforms.
12572 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12573 (case insensitive):
12575 @itemize @bullet
12576 @item BIND to invoke @command{gnatbind}
12577 @item CHOP to invoke @command{gnatchop}
12578 @item CLEAN to invoke @command{gnatclean}
12579 @item COMP or COMPILE to invoke the compiler
12580 @ifclear FSFEDITION
12581 @item ELIM to invoke @command{gnatelim}
12582 @end ifclear
12583 @item FIND to invoke @command{gnatfind}
12584 @item KR or KRUNCH to invoke @command{gnatkr}
12585 @item LINK to invoke @command{gnatlink}
12586 @item LS or LIST to invoke @command{gnatls}
12587 @item MAKE to invoke @command{gnatmake}
12588 @item NAME to invoke @command{gnatname}
12589 @item PREP or PREPROCESS to invoke @command{gnatprep}
12590 @ifclear FSFEDITION
12591 @item PP or PRETTY to invoke @command{gnatpp}
12592 @item METRIC to invoke @command{gnatmetric}
12593 @item STUB to invoke @command{gnatstub}
12594 @end ifclear
12595 @item XREF to invoke @command{gnatxref}
12597 @end itemize
12599 @noindent
12600 (note that the compiler is invoked using the command
12601 @command{gnatmake -f -u -c}).
12603 On non-VMS platforms, between @command{gnat} and the command, two
12604 special switches may be used:
12606 @itemize @bullet
12607 @item @command{-v} to display the invocation of the tool.
12608 @item @command{-dn} to prevent the @command{gnat} driver from removing
12609   the temporary files it has created. These temporary files are
12610   configuration files and temporary file list files.
12612 @end itemize
12614 @noindent
12615 The command may be followed by switches and arguments for the invoked
12616 tool.
12618 @smallexample
12619   gnat bind -C main.ali
12620   gnat ls -a main
12621   gnat chop foo.txt
12622 @end smallexample
12624 @noindent
12625 Switches may also be put in text files, one switch per line, and the text
12626 files may be specified with their path name preceded by '@@'.
12628 @smallexample
12629    gnat bind @@args.txt main.ali
12630 @end smallexample
12632 @noindent
12633 In addition, for commands BIND, COMP or COMPILE, FIND,
12634 @ifclear FSFEDITION
12635 ELIM,
12636 @end ifclear
12637 LS or LIST, LINK,
12638 @ifclear FSFEDITION
12639 METRIC,
12640 PP or PRETTY,
12641 STUB,
12642 @end ifclear
12643 and XREF, the project file related switches
12644 (@option{-P},
12645 @option{-X} and
12646 @option{-vPx}) may be used in addition to
12647 the switches of the invoking tool.
12649 @ifclear FSFEDITION
12650 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12651 specified on the command line, it invokes @command{gnatpp} with all
12652 the immediate sources of the specified project file.
12653 @end ifclear
12655 @ifclear FSFEDITION
12656 When GNAT METRIC is used with a project file, but with no source
12657 specified on the command line, it invokes @command{gnatmetric}
12658 with all the immediate sources of the specified project file and with
12659 @option{-d} with the parameter pointing to the object directory
12660 of the project.
12661 @end ifclear
12663 @ifclear FSFEDITION
12664 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12665 a project file, no source is specified on the command line and
12666 switch -U is specified on the command line, then
12667 the underlying tool (gnatpp or
12668 gnatmetric) is invoked for all sources of all projects,
12669 not only for the immediate sources of the main project.
12670 (-U stands for Universal or Union of the project files of the project tree)
12671 @end ifclear
12673 For each of the following commands, there is optionally a corresponding
12674 package in the main project.
12676 @itemize @bullet
12677 @item package @code{Binder} for command BIND (invoking @code{gnatbind})
12679 @ifclear FSFEDITION
12680 @item package @code{Check} for command CHECK (invoking
12681   @code{gnatcheck})
12682 @end ifclear
12684 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12686 @item package @code{Cross_Reference} for command XREF (invoking
12687   @code{gnatxref})
12689 @ifclear FSFEDITION
12690 @item package @code{Eliminate} for command ELIM (invoking
12691   @code{gnatelim})
12692 @end ifclear
12694 @item package @code{Finder} for command FIND (invoking @code{gnatfind})
12696 @item package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
12698 @ifclear FSFEDITION
12699 @item package @code{Gnatstub} for command STUB
12700   (invoking @code{gnatstub})
12701 @end ifclear
12703 @item package @code{Linker} for command LINK (invoking @code{gnatlink})
12705 @ifclear FSFEDITION
12706 @item package @code{Check} for command CHECK
12707   (invoking @code{gnatcheck})
12708 @end ifclear
12710 @ifclear FSFEDITION
12711 @item package @code{Metrics} for command METRIC
12712   (invoking @code{gnatmetric})
12713 @end ifclear
12715 @ifclear FSFEDITION
12716 @item package @code{Pretty_Printer} for command PP or PRETTY
12717   (invoking @code{gnatpp})
12718 @end ifclear
12720 @end itemize
12722 @noindent
12723 Package @code{Gnatls} has a unique attribute @code{Switches},
12724 a simple variable with a string list value. It contains switches
12725 for the invocation of @code{gnatls}.
12727 @smallexample @c projectfile
12728 @group
12729 @b{project} Proj1 @b{is}
12730    @b{package} gnatls @b{is}
12731       @b{for} Switches
12732           @b{use} ("-a",
12733                "-v");
12734    @b{end} gnatls;
12735 @b{end} Proj1;
12736 @end group
12737 @end smallexample
12739 @noindent
12740 All other packages have two attribute @code{Switches} and
12741 @code{Default_Switches}.
12743 @code{Switches} is an indexed attribute, indexed by the
12744 source file name, that has a string list value: the switches to be
12745 used when the tool corresponding to the package is invoked for the specific
12746 source file.
12748 @code{Default_Switches} is an attribute,
12749 indexed by  the programming language that has a string list value.
12750 @code{Default_Switches ("Ada")} contains the
12751 switches for the invocation of the tool corresponding
12752 to the package, except if a specific @code{Switches} attribute
12753 is specified for the source file.
12755 @smallexample @c projectfile
12756 @group
12757 @b{project} Proj @b{is}
12759    @b{for} Source_Dirs @b{use} ("**");
12761    @b{package} gnatls @b{is}
12762       @b{for} Switches @b{use}
12763           ("-a",
12764            "-v");
12765    @b{end} gnatls;
12766 @end group
12767 @group
12769    @b{package} Compiler @b{is}
12770       @b{for} Default_Switches ("Ada")
12771           @b{use} ("-gnatv",
12772                "-gnatwa");
12773    @b{end} Binder;
12774 @end group
12775 @group
12777    @b{package} Binder @b{is}
12778       @b{for} Default_Switches ("Ada")
12779           @b{use} ("-C",
12780                "-e");
12781    @b{end} Binder;
12782 @end group
12783 @group
12785    @b{package} Linker @b{is}
12786       @b{for} Default_Switches ("Ada")
12787           @b{use} ("-C");
12788       @b{for} Switches ("main.adb")
12789           @b{use} ("-C",
12790                "-v",
12791                "-v");
12792    @b{end} Linker;
12793 @end group
12794 @group
12796    @b{package} Finder @b{is}
12797       @b{for} Default_Switches ("Ada")
12798            @b{use} ("-a",
12799                 "-f");
12800    @b{end} Finder;
12801 @end group
12802 @group
12804    @b{package} Cross_Reference @b{is}
12805       @b{for} Default_Switches ("Ada")
12806           @b{use} ("-a",
12807                "-f",
12808                "-d",
12809                "-u");
12810    @b{end} Cross_Reference;
12811 @b{end} Proj;
12812 @end group
12813 @end smallexample
12815 @noindent
12816 With the above project file, commands such as
12818 @smallexample
12819    gnat comp -Pproj main
12820    gnat ls -Pproj main
12821    gnat xref -Pproj main
12822    gnat bind -Pproj main.ali
12823    gnat link -Pproj main.ali
12824 @end smallexample
12826 @noindent
12827 will set up the environment properly and invoke the tool with the switches
12828 found in the package corresponding to the tool:
12829 @code{Default_Switches ("Ada")} for all tools,
12830 except @code{Switches ("main.adb")}
12831 for @code{gnatlink}.
12832 @ifclear FSFEDITION
12833 It is also possible to invoke some of the tools,
12834 (@code{gnatcheck},
12835 @code{gnatmetric},
12836 and @code{gnatpp})
12837 on a set of project units thanks to the combination of the switches
12838 @option{-P}, @option{-U} and possibly the main unit when one is interested
12839 in its closure. For instance,
12840 @smallexample
12841 gnat metric -Pproj
12842 @end smallexample
12844 @noindent
12845 will compute the metrics for all the immediate units of project
12846 @code{proj}.
12847 @smallexample
12848 gnat metric -Pproj -U
12849 @end smallexample
12851 @noindent
12852 will compute the metrics for all the units of the closure of projects
12853 rooted at @code{proj}.
12854 @smallexample
12855 gnat metric -Pproj -U main_unit
12856 @end smallexample
12858 @noindent
12859 will compute the metrics for the closure of units rooted at
12860 @code{main_unit}. This last possibility relies implicitly
12861 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
12862 tool invoked by the @command{gnat} driver are explicitly  specified
12863 either directly or through the tool @option{-files} option, then the tool
12864 is called only for these explicitly specified files.
12865 @end ifclear
12867 @c *****************************************
12868 @c * Cross-referencing tools
12869 @c *****************************************
12871 @node The Cross-Referencing Tools gnatxref and gnatfind
12872 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12873 @findex gnatxref
12874 @findex gnatfind
12876 @noindent
12877 The compiler generates cross-referencing information (unless
12878 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12879 This information indicates where in the source each entity is declared and
12880 referenced. Note that entities in package Standard are not included, but
12881 entities in all other predefined units are included in the output.
12883 Before using any of these two tools, you need to compile successfully your
12884 application, so that GNAT gets a chance to generate the cross-referencing
12885 information.
12887 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12888 information to provide the user with the capability to easily locate the
12889 declaration and references to an entity. These tools are quite similar,
12890 the difference being that @code{gnatfind} is intended for locating
12891 definitions and/or references to a specified entity or entities, whereas
12892 @code{gnatxref} is oriented to generating a full report of all
12893 cross-references.
12895 To use these tools, you must not compile your application using the
12896 @option{-gnatx} switch on the @command{gnatmake} command line
12897 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12898 information will not be generated.
12900 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12901 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12903 @menu
12904 * Switches for gnatxref::
12905 * Switches for gnatfind::
12906 * Project Files for gnatxref and gnatfind::
12907 * Regular Expressions in gnatfind and gnatxref::
12908 * Examples of gnatxref Usage::
12909 * Examples of gnatfind Usage::
12910 @end menu
12912 @node Switches for gnatxref
12913 @section @code{gnatxref} Switches
12915 @noindent
12916 The command invocation for @code{gnatxref} is:
12917 @smallexample
12918 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12919 @c Expanding @ovar macro inline (explanation in macro def comments)
12920 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12921 @end smallexample
12923 @noindent
12924 where
12926 @table @var
12927 @item sourcefile1
12928 @itemx sourcefile2
12929 identifies the source files for which a report is to be generated. The
12930 ``with''ed units will be processed too. You must provide at least one file.
12932 These file names are considered to be regular expressions, so for instance
12933 specifying @file{source*.adb} is the same as giving every file in the current
12934 directory whose name starts with @file{source} and whose extension is
12935 @file{adb}.
12937 You shouldn't specify any directory name, just base names. @command{gnatxref}
12938 and @command{gnatfind} will be able to locate these files by themselves using
12939 the source path. If you specify directories, no result is produced.
12941 @end table
12943 @noindent
12944 The switches can be:
12945 @table @option
12946 @c !sort!
12947 @item --version
12948 @cindex @option{--version} @command{gnatxref}
12949 Display Copyright and version, then exit disregarding all other options.
12951 @item --help
12952 @cindex @option{--help} @command{gnatxref}
12953 If @option{--version} was not used, display usage, then exit disregarding
12954 all other options.
12956 @item -a
12957 @cindex @option{-a} (@command{gnatxref})
12958 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12959 the read-only files found in the library search path. Otherwise, these files
12960 will be ignored. This option can be used to protect Gnat sources or your own
12961 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12962 much faster, and their output much smaller. Read-only here refers to access
12963 or permissions status in the file system for the current user.
12965 @item -aIDIR
12966 @cindex @option{-aIDIR} (@command{gnatxref})
12967 When looking for source files also look in directory DIR. The order in which
12968 source file search is undertaken is the same as for @command{gnatmake}.
12970 @item -aODIR
12971 @cindex @option{-aODIR} (@command{gnatxref})
12972 When searching for library and object files, look in directory
12973 DIR. The order in which library files are searched is the same as for
12974 @command{gnatmake}.
12976 @item -nostdinc
12977 @cindex @option{-nostdinc} (@command{gnatxref})
12978 Do not look for sources in the system default directory.
12980 @item -nostdlib
12981 @cindex @option{-nostdlib} (@command{gnatxref})
12982 Do not look for library files in the system default directory.
12984 @item --ext=@var{extension}
12985 @cindex @option{--ext} (@command{gnatxref})
12986 Specify an alternate ali file extension. The default is @code{ali} and other
12987 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
12988 may be specified via this switch. Note that if this switch overrides the
12989 default, which means that only the new extension will be considered.
12991 @item --RTS=@var{rts-path}
12992 @cindex @option{--RTS} (@command{gnatxref})
12993 Specifies the default location of the runtime library. Same meaning as the
12994 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12996 @item -d
12997 @cindex @option{-d} (@command{gnatxref})
12998 If this switch is set @code{gnatxref} will output the parent type
12999 reference for each matching derived types.
13001 @item -f
13002 @cindex @option{-f} (@command{gnatxref})
13003 If this switch is set, the output file names will be preceded by their
13004 directory (if the file was found in the search path). If this switch is
13005 not set, the directory will not be printed.
13007 @item -g
13008 @cindex @option{-g} (@command{gnatxref})
13009 If this switch is set, information is output only for library-level
13010 entities, ignoring local entities. The use of this switch may accelerate
13011 @code{gnatfind} and @code{gnatxref}.
13013 @item -IDIR
13014 @cindex @option{-IDIR} (@command{gnatxref})
13015 Equivalent to @samp{-aODIR -aIDIR}.
13017 @item -pFILE
13018 @cindex @option{-pFILE} (@command{gnatxref})
13019 Specify a project file to use @xref{GNAT Project Manager}.
13020 If you need to use the @file{.gpr}
13021 project files, you should use gnatxref through the GNAT driver
13022 (@command{gnat xref -Pproject}).
13024 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13025 project file in the current directory.
13027 If a project file is either specified or found by the tools, then the content
13028 of the source directory and object directory lines are added as if they
13029 had been specified respectively by @samp{-aI}
13030 and @samp{-aO}.
13031 @item -u
13032 Output only unused symbols. This may be really useful if you give your
13033 main compilation unit on the command line, as @code{gnatxref} will then
13034 display every unused entity and 'with'ed package.
13036 @item -v
13037 Instead of producing the default output, @code{gnatxref} will generate a
13038 @file{tags} file that can be used by vi. For examples how to use this
13039 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13040 to the standard output, thus you will have to redirect it to a file.
13042 @end table
13044 @noindent
13045 All these switches may be in any order on the command line, and may even
13046 appear after the file names. They need not be separated by spaces, thus
13047 you can say @samp{gnatxref -ag} instead of
13048 @samp{gnatxref -a -g}.
13050 @node Switches for gnatfind
13051 @section @code{gnatfind} Switches
13053 @noindent
13054 The command line for @code{gnatfind} is:
13056 @smallexample
13057 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13058 @c       @r{[}@var{file1} @var{file2} @dots{}]
13059 @c Expanding @ovar macro inline (explanation in macro def comments)
13060 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13061       @r{[}@var{file1} @var{file2} @dots{}@r{]}
13062 @end smallexample
13064 @noindent
13065 where
13067 @table @var
13068 @item pattern
13069 An entity will be output only if it matches the regular expression found
13070 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13072 Omitting the pattern is equivalent to specifying @samp{*}, which
13073 will match any entity. Note that if you do not provide a pattern, you
13074 have to provide both a sourcefile and a line.
13076 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13077 for matching purposes. At the current time there is no support for
13078 8-bit codes other than Latin-1, or for wide characters in identifiers.
13080 @item sourcefile
13081 @code{gnatfind} will look for references, bodies or declarations
13082 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13083 and column @var{column}. See @ref{Examples of gnatfind Usage}
13084 for syntax examples.
13086 @item line
13087 is a decimal integer identifying the line number containing
13088 the reference to the entity (or entities) to be located.
13090 @item column
13091 is a decimal integer identifying the exact location on the
13092 line of the first character of the identifier for the
13093 entity reference. Columns are numbered from 1.
13095 @item file1 file2 @dots{}
13096 The search will be restricted to these source files. If none are given, then
13097 the search will be done for every library file in the search path.
13098 These file must appear only after the pattern or sourcefile.
13100 These file names are considered to be regular expressions, so for instance
13101 specifying @file{source*.adb} is the same as giving every file in the current
13102 directory whose name starts with @file{source} and whose extension is
13103 @file{adb}.
13105 The location of the spec of the entity will always be displayed, even if it
13106 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
13107 occurrences of the entity in the separate units of the ones given on the
13108 command line will also be displayed.
13110 Note that if you specify at least one file in this part, @code{gnatfind} may
13111 sometimes not be able to find the body of the subprograms.
13113 @end table
13115 @noindent
13116 At least one of 'sourcefile' or 'pattern' has to be present on
13117 the command line.
13119 The following switches are available:
13120 @table @option
13121 @c !sort!
13123 @cindex @option{--version} @command{gnatfind}
13124 Display Copyright and version, then exit disregarding all other options.
13126 @item --help
13127 @cindex @option{--help} @command{gnatfind}
13128 If @option{--version} was not used, display usage, then exit disregarding
13129 all other options.
13131 @item -a
13132 @cindex @option{-a} (@command{gnatfind})
13133 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13134 the read-only files found in the library search path. Otherwise, these files
13135 will be ignored. This option can be used to protect Gnat sources or your own
13136 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13137 much faster, and their output much smaller. Read-only here refers to access
13138 or permission status in the file system for the current user.
13140 @item -aIDIR
13141 @cindex @option{-aIDIR} (@command{gnatfind})
13142 When looking for source files also look in directory DIR. The order in which
13143 source file search is undertaken is the same as for @command{gnatmake}.
13145 @item -aODIR
13146 @cindex @option{-aODIR} (@command{gnatfind})
13147 When searching for library and object files, look in directory
13148 DIR. The order in which library files are searched is the same as for
13149 @command{gnatmake}.
13151 @item -nostdinc
13152 @cindex @option{-nostdinc} (@command{gnatfind})
13153 Do not look for sources in the system default directory.
13155 @item -nostdlib
13156 @cindex @option{-nostdlib} (@command{gnatfind})
13157 Do not look for library files in the system default directory.
13159 @item --ext=@var{extension}
13160 @cindex @option{--ext} (@command{gnatfind})
13161 Specify an alternate ali file extension. The default is @code{ali} and other
13162 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13163 may be specified via this switch. Note that if this switch overrides the
13164 default, which means that only the new extension will be considered.
13166 @item --RTS=@var{rts-path}
13167 @cindex @option{--RTS} (@command{gnatfind})
13168 Specifies the default location of the runtime library. Same meaning as the
13169 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13171 @item -d
13172 @cindex @option{-d} (@code{gnatfind})
13173 If this switch is set, then @code{gnatfind} will output the parent type
13174 reference for each matching derived types.
13176 @item -e
13177 @cindex @option{-e} (@command{gnatfind})
13178 By default, @code{gnatfind} accept the simple regular expression set for
13179 @samp{pattern}. If this switch is set, then the pattern will be
13180 considered as full Unix-style regular expression.
13182 @item -f
13183 @cindex @option{-f} (@command{gnatfind})
13184 If this switch is set, the output file names will be preceded by their
13185 directory (if the file was found in the search path). If this switch is
13186 not set, the directory will not be printed.
13188 @item -g
13189 @cindex @option{-g} (@command{gnatfind})
13190 If this switch is set, information is output only for library-level
13191 entities, ignoring local entities. The use of this switch may accelerate
13192 @code{gnatfind} and @code{gnatxref}.
13194 @item -IDIR
13195 @cindex @option{-IDIR} (@command{gnatfind})
13196 Equivalent to @samp{-aODIR -aIDIR}.
13198 @item -pFILE
13199 @cindex @option{-pFILE} (@command{gnatfind})
13200 Specify a project file (@pxref{GNAT Project Manager}) to use.
13201 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13202 project file in the current directory.
13204 If a project file is either specified or found by the tools, then the content
13205 of the source directory and object directory lines are added as if they
13206 had been specified respectively by @samp{-aI} and
13207 @samp{-aO}.
13209 @item -r
13210 @cindex @option{-r} (@command{gnatfind})
13211 By default, @code{gnatfind} will output only the information about the
13212 declaration, body or type completion of the entities. If this switch is
13213 set, the @code{gnatfind} will locate every reference to the entities in
13214 the files specified on the command line (or in every file in the search
13215 path if no file is given on the command line).
13217 @item -s
13218 @cindex @option{-s} (@command{gnatfind})
13219 If this switch is set, then @code{gnatfind} will output the content
13220 of the Ada source file lines were the entity was found.
13222 @item -t
13223 @cindex @option{-t} (@command{gnatfind})
13224 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13225 the specified type. It act like -d option but recursively from parent
13226 type to parent type. When this switch is set it is not possible to
13227 specify more than one file.
13229 @end table
13231 @noindent
13232 All these switches may be in any order on the command line, and may even
13233 appear after the file names. They need not be separated by spaces, thus
13234 you can say @samp{gnatxref -ag} instead of
13235 @samp{gnatxref -a -g}.
13237 As stated previously, gnatfind will search in every directory in the
13238 search path. You can force it to look only in the current directory if
13239 you specify @code{*} at the end of the command line.
13241 @node Project Files for gnatxref and gnatfind
13242 @section Project Files for @command{gnatxref} and @command{gnatfind}
13244 @noindent
13245 Project files allow a programmer to specify how to compile its
13246 application, where to find sources, etc.  These files are used
13247 primarily by GPS, but they can also be used
13248 by the two tools
13249 @code{gnatxref} and @code{gnatfind}.
13251 A project file name must end with @file{.gpr}. If a single one is
13252 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13253 extract the information from it. If multiple project files are found, none of
13254 them is read, and you have to use the @samp{-p} switch to specify the one
13255 you want to use.
13257 The following lines can be included, even though most of them have default
13258 values which can be used in most cases.
13259 The lines can be entered in any order in the file.
13260 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13261 each line. If you have multiple instances, only the last one is taken into
13262 account.
13264 @table @code
13265 @item src_dir=DIR
13266 [default: @code{"./"}]
13267 specifies a directory where to look for source files. Multiple @code{src_dir}
13268 lines can be specified and they will be searched in the order they
13269 are specified.
13271 @item obj_dir=DIR
13272 [default: @code{"./"}]
13273 specifies a directory where to look for object and library files. Multiple
13274 @code{obj_dir} lines can be specified, and they will be searched in the order
13275 they are specified
13277 @item comp_opt=SWITCHES
13278 [default: @code{""}]
13279 creates a variable which can be referred to subsequently by using
13280 the @code{$@{comp_opt@}} notation. This is intended to store the default
13281 switches given to @command{gnatmake} and @command{gcc}.
13283 @item bind_opt=SWITCHES
13284 [default: @code{""}]
13285 creates a variable which can be referred to subsequently by using
13286 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13287 switches given to @command{gnatbind}.
13289 @item link_opt=SWITCHES
13290 [default: @code{""}]
13291 creates a variable which can be referred to subsequently by using
13292 the @samp{$@{link_opt@}} notation. This is intended to store the default
13293 switches given to @command{gnatlink}.
13295 @item main=EXECUTABLE
13296 [default: @code{""}]
13297 specifies the name of the executable for the application. This variable can
13298 be referred to in the following lines by using the @samp{$@{main@}} notation.
13300 @item comp_cmd=COMMAND
13301 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13302 specifies the command used to compile a single file in the application.
13304 @item make_cmd=COMMAND
13305 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13306 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13307 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13308 specifies the command used to recompile the whole application.
13310 @item run_cmd=COMMAND
13311 [default: @code{"$@{main@}"}]
13312 specifies the command used to run the application.
13314 @item debug_cmd=COMMAND
13315 [default: @code{"gdb $@{main@}"}]
13316 specifies the command used to debug the application
13318 @end table
13320 @noindent
13321 @command{gnatxref} and @command{gnatfind} only take into account the
13322 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13324 @node Regular Expressions in gnatfind and gnatxref
13325 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13327 @noindent
13328 As specified in the section about @command{gnatfind}, the pattern can be a
13329 regular expression. Actually, there are to set of regular expressions
13330 which are recognized by the program:
13332 @table @code
13333 @item globbing patterns
13334 These are the most usual regular expression. They are the same that you
13335 generally used in a Unix shell command line, or in a DOS session.
13337 Here is a more formal grammar:
13338 @smallexample
13339 @group
13340 @iftex
13341 @leftskip=.5cm
13342 @end iftex
13343 regexp ::= term
13344 term   ::= elmt            -- matches elmt
13345 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13346 term   ::= *               -- any string of 0 or more characters
13347 term   ::= ?               -- matches any character
13348 term   ::= [char @{char@}]   -- matches any character listed
13349 term   ::= [char - char]   -- matches any character in range
13350 @end group
13351 @end smallexample
13353 @item full regular expression
13354 The second set of regular expressions is much more powerful. This is the
13355 type of regular expressions recognized by utilities such a @file{grep}.
13357 The following is the form of a regular expression, expressed in Ada
13358 reference manual style BNF is as follows
13360 @smallexample
13361 @iftex
13362 @leftskip=.5cm
13363 @end iftex
13364 @group
13365 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
13367 term ::= item @{item@}       -- concatenation (item then item)
13369 item ::= elmt              -- match elmt
13370 item ::= elmt *            -- zero or more elmt's
13371 item ::= elmt +            -- one or more elmt's
13372 item ::= elmt ?            -- matches elmt or nothing
13373 @end group
13374 @group
13375 elmt ::= nschar            -- matches given character
13376 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13377 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
13378 elmt ::= [char - char]     -- matches chars in given range
13379 elmt ::= \ char            -- matches given character
13380 elmt ::= .                 -- matches any single character
13381 elmt ::= ( regexp )        -- parens used for grouping
13383 char ::= any character, including special characters
13384 nschar ::= any character except ()[].*+?^
13385 @end group
13386 @end smallexample
13388 Following are a few examples:
13390 @table @samp
13391 @item abcde|fghi
13392 will match any of the two strings @samp{abcde} and @samp{fghi},
13394 @item abc*d
13395 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13396 @samp{abcccd}, and so on,
13398 @item [a-z]+
13399 will match any string which has only lowercase characters in it (and at
13400 least one character.
13402 @end table
13403 @end table
13405 @node Examples of gnatxref Usage
13406 @section Examples of @code{gnatxref} Usage
13408 @subsection General Usage
13410 @noindent
13411 For the following examples, we will consider the following units:
13413 @smallexample @c ada
13414 @group
13415 @cartouche
13416 main.ads:
13417 1: @b{with} Bar;
13418 2: @b{package} Main @b{is}
13419 3:     @b{procedure} Foo (B : @b{in} Integer);
13420 4:     C : Integer;
13421 5: @b{private}
13422 6:     D : Integer;
13423 7: @b{end} Main;
13425 main.adb:
13426 1: @b{package} @b{body} Main @b{is}
13427 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13428 3:     @b{begin}
13429 4:        C := B;
13430 5:        D := B;
13431 6:        Bar.Print (B);
13432 7:        Bar.Print (C);
13433 8:     @b{end} Foo;
13434 9: @b{end} Main;
13436 bar.ads:
13437 1: @b{package} Bar @b{is}
13438 2:     @b{procedure} Print (B : Integer);
13439 3: @b{end} bar;
13440 @end cartouche
13441 @end group
13442 @end smallexample
13444 @table @code
13446 @noindent
13447 The first thing to do is to recompile your application (for instance, in
13448 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13449 the cross-referencing information.
13450 You can then issue any of the following commands:
13452 @item gnatxref main.adb
13453 @code{gnatxref} generates cross-reference information for main.adb
13454 and every unit 'with'ed by main.adb.
13456 The output would be:
13457 @smallexample
13458 @iftex
13459 @leftskip=0cm
13460 @end iftex
13461 B                                                      Type: Integer
13462   Decl: bar.ads           2:22
13463 B                                                      Type: Integer
13464   Decl: main.ads          3:20
13465   Body: main.adb          2:20
13466   Ref:  main.adb          4:13     5:13     6:19
13467 Bar                                                    Type: Unit
13468   Decl: bar.ads           1:9
13469   Ref:  main.adb          6:8      7:8
13470        main.ads           1:6
13471 C                                                      Type: Integer
13472   Decl: main.ads          4:5
13473   Modi: main.adb          4:8
13474   Ref:  main.adb          7:19
13475 D                                                      Type: Integer
13476   Decl: main.ads          6:5
13477   Modi: main.adb          5:8
13478 Foo                                                    Type: Unit
13479   Decl: main.ads          3:15
13480   Body: main.adb          2:15
13481 Main                                                    Type: Unit
13482   Decl: main.ads          2:9
13483   Body: main.adb          1:14
13484 Print                                                   Type: Unit
13485   Decl: bar.ads           2:15
13486   Ref:  main.adb          6:12     7:12
13487 @end smallexample
13489 @noindent
13490 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13491 its body is in main.adb, line 1, column 14 and is not referenced any where.
13493 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13494 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13496 @item gnatxref package1.adb package2.ads
13497 @code{gnatxref} will generates cross-reference information for
13498 package1.adb, package2.ads and any other package 'with'ed by any
13499 of these.
13501 @end table
13503 @subsection Using gnatxref with vi
13505 @code{gnatxref} can generate a tags file output, which can be used
13506 directly from @command{vi}. Note that the standard version of @command{vi}
13507 will not work properly with overloaded symbols. Consider using another
13508 free implementation of @command{vi}, such as @command{vim}.
13510 @smallexample
13511 $ gnatxref -v gnatfind.adb > tags
13512 @end smallexample
13514 @noindent
13515 will generate the tags file for @code{gnatfind} itself (if the sources
13516 are in the search path!).
13518 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13519 (replacing @var{entity} by whatever you are looking for), and vi will
13520 display a new file with the corresponding declaration of entity.
13522 @node Examples of gnatfind Usage
13523 @section Examples of @code{gnatfind} Usage
13525 @table @code
13527 @item gnatfind -f xyz:main.adb
13528 Find declarations for all entities xyz referenced at least once in
13529 main.adb. The references are search in every library file in the search
13530 path.
13532 The directories will be printed as well (as the @samp{-f}
13533 switch is set)
13535 The output will look like:
13536 @smallexample
13537 directory/main.ads:106:14: xyz <= declaration
13538 directory/main.adb:24:10: xyz <= body
13539 directory/foo.ads:45:23: xyz <= declaration
13540 @end smallexample
13542 @noindent
13543 that is to say, one of the entities xyz found in main.adb is declared at
13544 line 12 of main.ads (and its body is in main.adb), and another one is
13545 declared at line 45 of foo.ads
13547 @item gnatfind -fs xyz:main.adb
13548 This is the same command as the previous one, instead @code{gnatfind} will
13549 display the content of the Ada source file lines.
13551 The output will look like:
13553 @smallexample
13554 directory/main.ads:106:14: xyz <= declaration
13555    procedure xyz;
13556 directory/main.adb:24:10: xyz <= body
13557    procedure xyz is
13558 directory/foo.ads:45:23: xyz <= declaration
13559    xyz : Integer;
13560 @end smallexample
13562 @noindent
13563 This can make it easier to find exactly the location your are looking
13564 for.
13566 @item gnatfind -r "*x*":main.ads:123 foo.adb
13567 Find references to all entities containing an x that are
13568 referenced on line 123 of main.ads.
13569 The references will be searched only in main.ads and foo.adb.
13571 @item gnatfind main.ads:123
13572 Find declarations and bodies for all entities that are referenced on
13573 line 123 of main.ads.
13575 This is the same as @code{gnatfind "*":main.adb:123}.
13577 @item gnatfind mydir/main.adb:123:45
13578 Find the declaration for the entity referenced at column 45 in
13579 line 123 of file main.adb in directory mydir. Note that it
13580 is usual to omit the identifier name when the column is given,
13581 since the column position identifies a unique reference.
13583 The column has to be the beginning of the identifier, and should not
13584 point to any character in the middle of the identifier.
13586 @end table
13588 @ifclear FSFEDITION
13589 @c *********************************
13590 @node The GNAT Pretty-Printer gnatpp
13591 @chapter The GNAT Pretty-Printer @command{gnatpp}
13592 @findex gnatpp
13593 @cindex Pretty-Printer
13595 @menu
13596 * Switches for gnatpp::
13597 * Formatting Rules::
13598 @end menu
13600 @noindent
13601 The @command{gnatpp} tool is an ASIS-based utility
13602 for source reformatting / pretty-printing.
13603 It takes an Ada source file as input and generates a reformatted
13604 version as output.
13605 You can specify various style directives via switches; e.g.,
13606 identifier case conventions, rules of indentation, and comment layout.
13608 Note: A newly-redesigned set of formatting algorithms used by gnatpp
13609 is now available.
13610 To invoke the old formatting algorithms, use the @option{--pp-old} switch.
13611 Support for @option{--pp-old} will be removed in some future version.
13613 To produce a reformatted file, @command{gnatpp} invokes the Ada
13614 compiler and generates and uses the ASIS tree for the input source;
13615 thus the input must be legal Ada code, and the tool should have all the
13616 information needed to compile the input source. To provide this information,
13617 you may specify as a tool parameter the project file the input source belongs to
13618 (or you may call @command{gnatpp}
13619 through the @command{gnat} driver (see @ref{The GNAT Driver and
13620 Project Files}). Another possibility is to specify the source search
13621 path and needed configuration files in @option{-cargs} section of @command{gnatpp}
13622 call, see the description of the @command{gnatpp} switches below.
13624 @command{gnatpp} cannot process sources that contain
13625 preprocessing directives.
13627 The @command{gnatpp} command has the form
13629 @smallexample
13630 @c $ gnatpp @ovar{switches} @var{filename}
13631 @c Expanding @ovar macro inline (explanation in macro def comments)
13632 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13633 @end smallexample
13635 @noindent
13636 where
13637 @itemize @bullet
13638 @item
13639 @var{switches} is an optional sequence of switches defining such properties as
13640 the formatting rules, the source search path, and the destination for the
13641 output source file
13643 @item
13644 @var{filename} is the name (including the extension) of the source file to
13645 reformat; wildcards or several file names on the same gnatpp command are
13646 allowed. The file name may contain path information; it does not have to
13647 follow the GNAT file naming rules
13649 @item
13650 @samp{@var{gcc_switches}} is a list of switches for
13651 @command{gcc}. They will be passed on to all compiler invocations made by
13652 @command{gnatpp} to generate the ASIS trees. Here you can provide
13653 @option{-I} switches to form the source search path,
13654 use the @option{-gnatec} switch to set the configuration file, etc.
13655 @end itemize
13657 @node Switches for gnatpp
13658 @section Switches for @command{gnatpp}
13660 @noindent
13661 The following subsections describe the various switches accepted by
13662 @command{gnatpp}, organized by category.
13664 You specify a switch by supplying a name and generally also a value.
13665 In many cases the values for a switch with a given name are incompatible with
13666 each other
13667 (for example the switch that controls the casing of a reserved word may have
13668 exactly one value: upper case, lower case, or
13669 mixed case) and thus exactly one such switch can be in effect for an
13670 invocation of @command{gnatpp}.
13671 If more than one is supplied, the last one is used.
13672 However, some values for the same switch are mutually compatible.
13673 You may supply several such switches to @command{gnatpp}, but then
13674 each must be specified in full, with both the name and the value.
13675 Abbreviated forms (the name appearing once, followed by each value) are
13676 not permitted.
13679 @menu
13680 * Alignment Control::
13681 * Casing Control::
13682 * General Text Layout Control::
13683 * Other Formatting Options::
13684 * Setting the Source Search Path::
13685 * Output File Control::
13686 * Other gnatpp Switches::
13687 @end menu
13689 @node Alignment Control
13690 @subsection Alignment Control
13691 @cindex Alignment control in @command{gnatpp}
13693 @noindent
13694 Programs can be easier to read if certain constructs are vertically aligned.
13695 By default alignment of the following constructs is set ON:
13696 @code{:} in declarations, @code{:=} in initializations in declarations
13697 @code{:=} in assignment statements, @code{=>} in associations, and
13698 @code{at} keywords in the component clauses in record
13699 representation clauses.
13701 @table @option
13702 @cindex @option{-A@var{n}} (@command{gnatpp})
13704 @item -A0
13705 Set alignment to OFF
13707 @item -A1
13708 Set alignment to ON
13709 @end table
13711 @node Casing Control
13712 @subsection Casing Control
13713 @cindex Casing control in @command{gnatpp}
13715 @noindent
13716 @command{gnatpp} allows you to specify the casing for reserved words,
13717 pragma names, attribute designators and identifiers.
13718 For identifiers you may define a
13719 general rule for name casing but also override this rule
13720 via a set of dictionary files.
13722 Three types of casing are supported: lower case, upper case, and mixed case.
13723 ``Mixed case'' means that the first letter, and also each letter immediately
13724 following an underscore, are converted to their uppercase forms;
13725 all the other letters are converted to their lowercase forms.
13727 @table @option
13728 @cindex @option{-a@var{x}} (@command{gnatpp})
13729 @item -aL
13730 Attribute designators are lower case
13732 @item -aU
13733 Attribute designators are upper case
13735 @item -aM
13736 Attribute designators are mixed case (this is the default)
13738 @cindex @option{-k@var{x}} (@command{gnatpp})
13739 @item -kL
13740 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13741 lower case (this is the default)
13743 @item -kU
13744 Keywords are upper case
13746 @cindex @option{-n@var{x}} (@command{gnatpp})
13747 @item -nD
13748 Name casing for defining occurrences are as they appear in the source file
13749 (this is the default)
13751 @item -nU
13752 Names are in upper case
13754 @item -nL
13755 Names are in lower case
13757 @item -nM
13758 Names are in mixed case
13760 @cindex @option{-ne@var{x}} (@command{gnatpp})
13761 @item -neD
13762 Enumeration literal casing for defining occurrences are as they appear in the
13763 source file. Overrides -n casing setting.
13765 @item -neU
13766 Enumeration literals are in upper case.  Overrides -n casing
13767 setting.
13769 @item -neL
13770 Enumeration literals are in lower case. Overrides -n casing
13771 setting.
13773 @item -neM
13774 Enumeration literals are in mixed case. Overrides -n casing
13775 setting.
13777 @cindex @option{-nt@var{x}} (@command{gnatpp})
13778 @item -neD
13779 Names introduced by type and subtype declarations are always
13780 cased as they appear in the declaration in the source file.
13781 Overrides -n casing setting.
13783 @item -ntU
13784 Names introduced by type and subtype declarations are always in
13785 upper case. Overrides -n casing setting.
13787 @item -ntL
13788 Names introduced by type and subtype declarations are always in
13789 lower case. Overrides -n casing setting.
13791 @item -ntM
13792 Names introduced by type and subtype declarations are always in
13793 mixed case. Overrides -n casing setting.
13795 @item -nnU
13796 Names introduced by number declarations are always in
13797 upper case. Overrides -n casing setting.
13799 @item -nnL
13800 Names introduced by number declarations are always in
13801 lower case. Overrides -n casing setting.
13803 @item -nnM
13804 Names introduced by number declarations are always in
13805 mixed case. Overrides -n casing setting.
13807 @cindex @option{-p@var{x}} (@command{gnatpp})
13808 @item -pL
13809 Pragma names are lower case
13811 @item -pU
13812 Pragma names are upper case
13814 @item -pM
13815 Pragma names are mixed case (this is the default)
13817 @item -D@var{file}
13818 @cindex @option{-D} (@command{gnatpp})
13819 Use @var{file} as a @emph{dictionary file} that defines
13820 the casing for a set of specified names,
13821 thereby overriding the effect on these names by
13822 any explicit or implicit
13823 -n switch.
13824 To supply more than one dictionary file,
13825 use several @option{-D} switches.
13827 @noindent
13828 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13829 to define the casing for the Ada predefined names and
13830 the names declared in the GNAT libraries.
13832 @item -D-
13833 @cindex @option{-D-} (@command{gnatpp})
13834 Do not use the default dictionary file;
13835 instead, use the casing
13836 defined by a @option{-n} switch and any explicit
13837 dictionary file(s)
13838 @end table
13840 @noindent
13841 The structure of a dictionary file, and details on the conventions
13842 used in the default dictionary file, are defined in @ref{Name Casing}.
13844 The @option{-D-} and
13845 @option{-D@var{file}} switches are mutually
13846 compatible.
13848 @noindent
13849 This group of @command{gnatpp} switches controls the layout of comments and
13850 complex syntactic constructs.  See @ref{Formatting Comments} for details
13851 on their effect.
13853 @table @option
13854 @cindex @option{-c@var{n}} (@command{gnatpp})
13855 @item -c0
13856 All comments remain unchanged.
13858 @item -c1
13859 GNAT-style comment line indentation.
13860 This is the default.
13862 @item -c3
13863 GNAT-style comment beginning.
13865 @item -c4
13866 Fill comment blocks.
13868 @item -c5
13869 Keep unchanged special form comments.
13870 This is the default.
13872 @item --comments-only
13873 @cindex @option{--comments-only} @command{gnatpp}
13874 Format just the comments.
13876 @cindex @option{--no-separate-is} (@command{gnatpp})
13877 @item --no-separate-is
13878 Do not place the keyword @code{is} on a separate line in a subprogram body in
13879 case if the spec occupies more than one line.
13881 @cindex @option{--separate-loop-then} (@command{gnatpp})
13882 @item --separate-loop-then
13883 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13884 keyword @code{then} in IF statements on a separate line.
13886 @cindex @option{--no-separate-loop-then} (@command{gnatpp})
13887 @item --no-separate-loop-then
13888 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13889 keyword @code{then} in IF statements on a separate line. This option is
13890 incompatible with @option{--separate-loop-then} option.
13892 @cindex @option{--use-on-new-line} (@command{gnatpp})
13893 @item --use-on-new-line
13894 Start each USE clause in a context clause from a separate line.
13896 @cindex @option{--insert-blank-lines} (@command{gnatpp})
13897 @item --insert-blank-lines
13898 Insert blank lines where appropriate (between bodies and other large
13899 constructs).
13901 @cindex @option{--preserve-blank-lines} (@command{gnatpp})
13902 @item --preserve-blank-lines
13903 Preserve blank lines in the input. By default, gnatpp will squeeze
13904 multiple blank lines down to one.
13906 @end table
13908 @noindent
13909 The @option{-c} switches are compatible with one another, except that
13910 the @option{-c0} switch disables all other comment formatting
13911 switches.
13914 @node General Text Layout Control
13915 @subsection General Text Layout Control
13917 @noindent
13918 These switches allow control over line length and indentation.
13920 @table @option
13921 @item -M@var{nnn}
13922 @cindex @option{-M} (@command{gnatpp})
13923 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13925 @item -i@var{nnn}
13926 @cindex @option{-i} (@command{gnatpp})
13927 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13929 @item -cl@var{nnn}
13930 @cindex @option{-cl} (@command{gnatpp})
13931 Indentation level for continuation lines (relative to the line being
13932 continued), @var{nnn} from 1@dots{}9.
13933 The default
13934 value is one less than the (normal) indentation level, unless the
13935 indentation is set to 1 (in which case the default value for continuation
13936 line indentation is also 1)
13937 @end table
13939 @node Other Formatting Options
13940 @subsection Other Formatting Options
13942 @noindent
13943 These switches control other formatting not listed above.
13945 @table @option
13946 @item --decimal-grouping=@var{n}
13947 @cindex @option{--decimal-grouping} @command{gnatpp}
13948 Put underscores in decimal literals (numeric literals without a base)
13949 every @var{n} characters. If a literal already has one or more
13950 underscores, it is not modified. For example, with
13951 @code{--decimal-grouping=3}, @code{1000000} will be changed to
13952 @code{1_000_000}.
13954 @item --based-grouping=@var{n}
13955 @cindex @option{--based-grouping} @command{gnatpp}
13956 Same as @code{--decimal-grouping}, but for based literals. For
13957 example, with @code{--based-grouping=4}, @code{16#0001FFFE#} will be
13958 changed to @code{16#0001_FFFE#}.
13960 @item --RM-style-spacing
13961 @cindex @option{--RM-style-spacing} (@command{gnatpp})
13962 Do not insert an extra blank before various occurrences of
13963 `(' and `:'. This also turns off alignment.
13965 @item -ff
13966 @cindex @option{-ff} (@command{gnatpp})
13967 Insert a Form Feed character after a pragma Page.
13969 @item --call_threshold=@var{nnn}
13970 @cindex @option{--call_threshold} (@command{gnatpp})
13971 If the number of parameter associations is greater than @var{nnn} and if at
13972 least one association uses named notation, start each association from
13973 a new line. If @var{nnn} is 0, no check for the number of associations
13974 is made; this is the default.
13976 @item --par_threshold=@var{nnn}
13977 @cindex @option{--par_threshold} (@command{gnatpp})
13978 If the number of parameter specifications is greater than @var{nnn}
13979 (or equal to @var{nnn} in case of a function), start each specification from
13980 a new line. This feature is disabled by default.
13981 @end table
13983 @node Setting the Source Search Path
13984 @subsection Setting the Source Search Path
13986 @noindent
13987 To define the search path for the input source file, @command{gnatpp}
13988 uses the same switches as the GNAT compiler, with the same effects:
13990 @table @option
13991 @item -I@var{dir}
13992 @cindex @option{-I} (@command{gnatpp})
13994 @item -I-
13995 @cindex @option{-I-} (@command{gnatpp})
13997 @item -gnatec=@var{path}
13998 @cindex @option{-gnatec} (@command{gnatpp})
14000 @item --RTS=@var{path}
14001 @cindex @option{--RTS} (@command{gnatpp})
14003 @end table
14005 @node Output File Control
14006 @subsection Output File Control
14008 @noindent
14009 By default the output is sent to a file whose name is obtained by appending
14010 the @file{.pp} suffix to the name of the input file.
14011 If the file with this name already exists, it is overwritten.
14012 Thus if the input file is @file{my_ada_proc.adb} then
14013 @command{gnatpp} will produce @file{my_ada_proc.adb.pp}
14014 as output file.
14015 The output may be redirected by the following switches:
14017 @table @option
14018 @item --output-dir=@var{dir}
14019 @cindex @option{--output-dir} (@command{gnatpp})
14020 Generate output file in directory @file{dir} with the same name as the input
14021 file. If @file{dir} is the same as the directory containing the input file,
14022 the input file is not processed; use @option{-rnb}
14023 if you want to update the input file in place.
14025 @item -pipe
14026 @cindex @option{-pipe} (@command{gnatpp})
14027 Send the output to @code{Standard_Output}
14029 @item -o @var{output_file}
14030 @cindex @option{-o} (@code{gnatpp})
14031 Write the output into @var{output_file}.
14032 If @var{output_file} already exists, @command{gnatpp} terminates without
14033 reading or processing the input file.
14035 @item -of @var{output_file}
14036 @cindex @option{-of} (@command{gnatpp})
14037 Write the output into @var{output_file}, overwriting the existing file
14038 (if one is present).
14040 @item -r
14041 @cindex @option{-r} (@command{gnatpp})
14042 Replace the input source file with the reformatted output, and copy the
14043 original input source into the file whose name is obtained by appending the
14044 @file{.npp} suffix to the name of the input file.
14045 If a file with this name already exists, @command{gnatpp} terminates without
14046 reading or processing the input file.
14048 @item -rf
14049 @cindex @option{-rf} (@code{gnatpp})
14050 Like @option{-r} except that if the file with the specified name
14051 already exists, it is overwritten.
14053 @item -rnb
14054 @cindex @option{-rnb} (@command{gnatpp})
14055 Replace the input source file with the reformatted output without
14056 creating any backup copy of the input source.
14058 @item --eol=@var{xxx}
14059 @cindex @option{--eol} (@code{gnatpp})
14060 Specifies the line-ending style of the reformatted output file. The @var{xxx}
14061 string specified with the switch may be:
14062 @itemize @bullet
14063 @item ``@option{dos}'' MS DOS style, lines end with CR LF characters
14064 @item ``@option{crlf}''
14065 the same as @option{dos}
14066 @item ``@option{unix}'' UNIX style, lines end with LF character
14067 @item ``@option{lf}''
14068 the same as @option{unix}
14069 @end itemize
14071 @item -W@var{e}
14072 @cindex @option{-W} (@command{gnatpp})
14073 Specify the wide character encoding method for the input and output files.
14074 @var{e} is one of the following:
14076 @itemize @bullet
14078 @item h
14079 Hex encoding
14081 @item u
14082 Upper half encoding
14084 @item s
14085 Shift/JIS encoding
14087 @item e
14088 EUC encoding
14090 @item 8
14091 UTF-8 encoding
14093 @item b
14094 Brackets encoding (default value)
14095 @end itemize
14097 @end table
14099 @noindent
14100 Options @option{-o} and
14101 @option{-of} are allowed only if the call to gnatpp
14102 contains only one file to reformat.
14103 Option
14104 @option{--eol}
14106 @option{-W}
14107 cannot be used together
14108 with @option{-pipe} option.
14110 @node Other gnatpp Switches
14111 @subsection Other @code{gnatpp} Switches
14113 @noindent
14114 The additional @command{gnatpp} switches are defined in this subsection.
14116 @table @option
14117 @item --version
14118 @cindex @option{--version} @command{gnatpp}
14119 Display copyright and version, then exit disregarding all other options.
14121 @item --help
14122 @cindex @option{--help} @command{gnatpp}
14123 Display usage, then exit disregarding all other options.
14125 @item -P @var{file}
14126 @cindex @option{-P} @command{gnatpp}
14127 Indicates the name of the project file that describes the set of sources
14128 to be processed. The exact set of argument sources depends on other options
14129 specified; see below.
14131 @item -U
14132 @cindex @option{-U} @command{gnatpp}
14133 If a project file is specified and no argument source is explicitly
14134 specified (either directly or by means of @option{-files} option), process
14135 all the units of the closure of the argument project. Otherwise this option
14136 has no effect.
14138 @item -U @var{main_unit}
14139 If a project file is specified and no argument source is explicitly
14140 specified (either directly or by means of @option{-files} option), process
14141 the closure of units rooted at @var{main_unit}. Otherwise this option
14142 has no effect.
14144 @item -X@var{name}=@var{value}
14145 @cindex @option{-X} @command{gnatpp}
14146 Indicates that external variable @var{name} in the argument project
14147 has the value @var{value}. Has no effect if no project is specified as
14148 tool argument.
14150 @item --incremental
14151 @cindex @option{--incremental} @command{gnatpp}
14152 Incremental processing on a per-file basis. Source files are only
14153 processed if they have been modified, or if files they depend on have
14154 been modified. This is similar to the way gnatmake/gprbuild only
14155 compiles files that need to be recompiled. A project file is required
14156 in this mode, and the gnat driver (as in @command{gnat pretty}) is not
14157 supported.
14159 @item --pp-off=@var{xxx}
14160 @cindex @option{--pp-off} @command{gnatpp}
14161 Use @code{--xxx} as the command to turn off pretty printing, instead
14162 of the default @code{--!pp off}.
14164 @item --pp-on=@var{xxx}
14165 @cindex @option{--pp-on} @command{gnatpp}
14166 Use @code{--xxx} as the command to turn pretty printing back on, instead
14167 of the default @code{--!pp on}.
14169 @item --pp-old
14170 @cindex @option{--pp-old} @command{gnatpp}
14171 Use the old formatting algorithms.
14173 @item -files @var{filename}
14174 @cindex @option{-files} (@code{gnatpp})
14175 Take the argument source files from the specified file. This file should be an
14176 ordinary text file containing file names separated by spaces or
14177 line breaks. You can use this switch more than once in the same call to
14178 @command{gnatpp}. You also can combine this switch with an explicit list of
14179 files.
14181 @item -j@var{n}
14182 @cindex @option{-j} (@command{gnatpp})
14183 Without @option{--incremental}, use @var{n} processes to carry out the
14184 tree creations (internal representations of the argument sources). On
14185 a multiprocessor machine this speeds up processing of big sets of
14186 argument sources. If @var{n} is 0, then the maximum number of parallel
14187 tree creations is the number of core processors on the platform. This
14188 option cannot be used together with @option{-r},
14189 @option{-rf} or
14190 @option{-rnb} option.
14192 With @option{--incremental}, use @var{n} @command{gnatpp} processes to
14193 perform pretty-printing in parallel. @var{n} = 0 means the same as
14194 above. In this case, @option{-r},
14195 @option{-rf} or
14196 @option{-rnb} options are allowed.
14198 @cindex @option{-t} (@command{gnatpp})
14199 @item -t
14200 Print out execution time.
14202 @item -v
14203 @cindex @option{-v} (@command{gnatpp})
14204 Verbose mode
14206 @item -q
14207 @cindex @option{-q} (@command{gnatpp})
14208 Quiet mode
14209 @end table
14211 @noindent
14212 If a project file is specified and no argument source is explicitly
14213 specified (either directly or by means of @option{-files} option), and no
14214 @option{-U} is specified, then the set of processed sources is
14215 all the immediate units of the argument project.
14218 @node Formatting Rules
14219 @section Formatting Rules
14221 @noindent
14222 The following subsections show how @command{gnatpp} treats white space,
14223 comments, program layout, and name casing.
14224 They provide detailed descriptions of the switches shown above.
14226 @menu
14227 * Disabling Pretty Printing::
14228 * White Space and Empty Lines::
14229 * Formatting Comments::
14230 * Name Casing::
14231 @end menu
14233 @node Disabling Pretty Printing
14234 @subsection Disabling Pretty Printing
14236 @noindent
14237 Pretty printing is highly heuristic in nature, and sometimes doesn't
14238 do exactly what you want. If you wish to format a certain region of
14239 code by hand, you can turn off pretty printing in that region by
14240 surrounding it with special comments that start with @code{--!pp off}
14241 and @code{--!pp on}. The text in that region will then be reproduced
14242 verbatim in the output with no formatting.
14244 To disable pretty printing for the whole file, put @code{--!pp off} at
14245 the top, with no following @code{--!pp on}.
14247 The comments must appear on a line by themselves, with nothing
14248 preceding except spaces. The initial text of the comment must be
14249 exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14250 be followed by arbitrary additional text. For example:
14252 @smallexample @c ada
14253 @cartouche
14254 @b{package} Interrupts @b{is}
14255    --@i{!pp off -- turn off pretty printing so "Interrupt_Kind" lines up}
14256    @b{type}            Interrupt_Kind @b{is}
14257      (Asynchronous_Interrupt_Kind,
14258        Synchronous_Interrupt_Kind,
14259              Green_Interrupt_Kind);
14260    --@i{!pp on -- reenable pretty printing}
14262    ...
14263 @end cartouche
14264 @end smallexample
14266 You can specify different comment strings using the @code{--pp-off}
14267 and @code{--pp-on} switches. For example, if you say @code{gnatpp
14268 --pp-off=' pp-' *.ad?} then gnatpp will recognize comments of the form
14269 @code{-- pp-} instead of @code{--!pp off} for disabling pretty
14270 printing. Note that the leading @code{--} of the comment is not
14271 included in the argument to these switches.
14273 @node White Space and Empty Lines
14274 @subsection White Space and Empty Lines
14276 @noindent
14277 @command{gnatpp} does not have an option to control space characters.
14278 It will add or remove spaces according to the style illustrated by the
14279 examples in the @cite{Ada Reference Manual}.
14280 The output file will contain no lines with trailing white space.
14282 By default, a sequence of one or more blank lines in the input is
14283 converted to a single blank line in the output; multiple blank lines
14284 are squeezed down to one.
14285 The @option{--preserve-blank-lines} option
14286 turns off the squeezing; each blank line in the input is copied
14287 to the output.
14288 The @option{--insert-blank-lines} option
14289 causes additional blank lines to be inserted if not already
14290 present in the input (e.g. between bodies).
14292 @node Formatting Comments
14293 @subsection Formatting Comments
14295 @noindent
14296 Comments in Ada code are of two kinds:
14297 @itemize @bullet
14298 @item
14299 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14300 white space) on a line
14302 @item
14303 an @emph{end-of-line comment}, which follows some other Ada code on
14304 the same line.
14305 @end itemize
14307 @noindent
14308 A whole-line comment is indented according to the surrounding code,
14309 with some exceptions.
14310 Comments that start in column 1 are kept there.
14311 If possible, comments are not moved so far to the right that the maximum
14312 line length is exceeded.
14313 The @option{-c0} option
14314 turns off comment formatting.
14315 Special-form comments such as SPARK-style @code{--#...} are left alone.
14317 For an end-of-line comment, @command{gnatpp} tries to leave the same
14318 number of spaces between the end of the preceding Ada code and the
14319 beginning of the comment as appear in the original source.
14321 @noindent
14322 The @option{-c3} switch
14323 (GNAT style comment beginning) has the following
14324 effect:
14326 @itemize @bullet
14327 @item
14328 For each whole-line comment that does not end with two hyphens,
14329 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14330 to ensure that there are at least two spaces between these hyphens and the
14331 first non-blank character of the comment.
14332 @end itemize
14334 @noindent
14335 The @option{-c4} switch specifies that
14336 whole-line comments that form a paragraph will be filled in typical
14337 word processor style (that is, moving words between lines to make the
14338 lines other than the last similar in length ).
14340 @noindent
14341 The @option{--comments-only} switch specifies that only the comments
14342 are formatted; the rest of the program text is left alone. The
14343 comments are formatted according to the -c3 and -c4 switches; other
14344 formatting switches are ignored. For example, @option{--comments-only
14345 -c4} means to fill comment paragraphs, and do nothing else. Likewise,
14346 @option{--comments-only -c3} ensures comments start with at least two
14347 spaces after @code{--}, and @option{--comments-only -c3 -c4} does
14348 both. If @option{--comments-only} is given without @option{-c3} or
14349 @option{-c4}, then gnatpp doesn't format anything.
14351 @node Name Casing
14352 @subsection Name Casing
14354 @noindent
14355 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14356 the same casing as the corresponding defining identifier.
14358 You control the casing for defining occurrences via the
14359 @option{-n} switch.
14360 With @option{-nD} (``as declared'', which is the default),
14361 defining occurrences appear exactly as in the source file
14362 where they are declared.
14363 The other values for this switch ---
14364 @option{-nU},
14365 @option{-nL},
14366 @option{-nM} ---
14367 result in
14368 upper, lower, or mixed case, respectively.
14369 If @command{gnatpp} changes the casing of a defining
14370 occurrence, it analogously changes the casing of all the
14371 usage occurrences of this name.
14373 If the defining occurrence of a name is not in the source compilation unit
14374 currently being processed by @command{gnatpp}, the casing of each reference to
14375 this name is changed according to the value of the @option{-n}
14376 switch (subject to the dictionary file mechanism described below).
14377 Thus @command{gnatpp} acts as though the @option{-n} switch
14378 had affected the
14379 casing for the defining occurrence of the name.
14381 The options
14382 @option{-a@var{x}},
14383 @option{-k@var{x}},
14384 @option{-ne@var{x}},
14385 @option{-nt@var{x}},
14386 @option{-nn@var{x}}, and
14387 @option{-p@var{x}}
14388 allow finer-grained control over casing for
14389 attributes, keywords, enumeration literals,
14390 types, named numbers and pragmas, respectively.
14391 @option{-nt@var{x}} covers subtypes and
14392 task and protected bodies as well.
14394 Some names may need to be spelled with casing conventions that are not
14395 covered by the upper-, lower-, and mixed-case transformations.
14396 You can arrange correct casing by placing such names in a
14397 @emph{dictionary file},
14398 and then supplying a @option{-D} switch.
14399 The casing of names from dictionary files overrides
14400 any @option{-n} switch.
14402 To handle the casing of Ada predefined names and the names from GNAT libraries,
14403 @command{gnatpp} assumes a default dictionary file.
14404 The name of each predefined entity is spelled with the same casing as is used
14405 for the entity in the @cite{Ada Reference Manual} (usually mixed case).
14406 The name of each entity in the GNAT libraries is spelled with the same casing
14407 as is used in the declaration of that entity.
14409 The @w{@option{-D-}} switch suppresses the use of
14410 the default dictionary file. Instead, the casing for predefined and
14411 GNAT-defined names will be established by the
14412 @option{-n} switch or explicit dictionary files. For
14413 example, by default the names @code{Ada.Text_IO} and
14414 @code{GNAT.OS_Lib} will appear as just shown, even in the presence of
14415 a @option{-nU} switch.  To ensure that even
14416 such names are rendered in uppercase, additionally supply the
14417 @w{@option{-D-}} switch (or else place these names
14418 in upper case in a dictionary file).
14420 A dictionary file is a plain text file; each line in this file can be
14421 either a blank line (containing only space characters), an Ada comment
14422 line, or the specification of exactly one @emph{casing schema}.
14424 A casing schema is a string that has the following syntax:
14426 @smallexample
14427 @cartouche
14428   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14430   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14431 @end cartouche
14432 @end smallexample
14434 @noindent
14435 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14436 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14438 The casing schema string can be followed by white space and/or an Ada-style
14439 comment; any amount of white space is allowed before the string.
14441 If a dictionary file is passed as
14442 the value of a @option{-D@var{file}} switch
14443 then for every
14444 simple name and every identifier, @command{gnatpp} checks if the dictionary
14445 defines the casing for the name or for some of its parts (the term ``subword''
14446 is used below to denote the part of a name which is delimited by ``_'' or by
14447 the beginning or end of the word and which does not contain any ``_'' inside):
14449 @itemize @bullet
14450 @item
14451 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14452 the casing defined by the dictionary; no subwords are checked for this word
14454 @item
14455 for every subword @command{gnatpp} checks if the dictionary contains the
14456 corresponding string of the form @code{*@var{simple_identifier}*},
14457 and if it does, the casing of this @var{simple_identifier} is used
14458 for this subword
14460 @item
14461 if the whole name does not contain any ``_'' inside, and if for this name
14462 the dictionary contains two entries - one of the form @var{identifier},
14463 and another - of the form *@var{simple_identifier}*, then the first one
14464 is applied to define the casing of this name
14466 @item
14467 if more than one dictionary file is passed as @command{gnatpp} switches, each
14468 dictionary adds new casing exceptions and overrides all the existing casing
14469 exceptions set by the previous dictionaries
14471 @item
14472 when @command{gnatpp} checks if the word or subword is in the dictionary,
14473 this check is not case sensitive
14474 @end itemize
14476 @noindent
14477 For example, suppose we have the following source to reformat:
14479 @smallexample @c ada
14480 @cartouche
14481 @b{procedure} test @b{is}
14482    name1 : integer := 1;
14483    name4_name3_name2 : integer := 2;
14484    name2_name3_name4 : Boolean;
14485    name1_var : Float;
14486 @b{begin}
14487    name2_name3_name4 := name4_name3_name2 > name1;
14488 @b{end};
14489 @end cartouche
14490 @end smallexample
14492 @noindent
14493 And suppose we have two dictionaries:
14495 @smallexample
14496 @cartouche
14497 @i{dict1:}
14498    NAME1
14499    *NaMe3*
14500    *Name1*
14501 @end cartouche
14503 @cartouche
14504 @i{dict2:}
14505   *NAME3*
14506 @end cartouche
14507 @end smallexample
14509 @noindent
14510 If @command{gnatpp} is called with the following switches:
14512 @smallexample
14513 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14514 @end smallexample
14516 @noindent
14517 then we will get the following name casing in the @command{gnatpp} output:
14519 @smallexample @c ada
14520 @cartouche
14521 @b{procedure} Test @b{is}
14522    NAME1             : Integer := 1;
14523    Name4_NAME3_Name2 : Integer := 2;
14524    Name2_NAME3_Name4 : Boolean;
14525    Name1_Var         : Float;
14526 @b{begin}
14527    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14528 @b{end} Test;
14529 @end cartouche
14530 @end smallexample
14531 @end ifclear
14533 @ifclear FSFEDITION
14534 @c *********************************
14535 @node The Ada-to-XML converter gnat2xml
14536 @chapter The Ada-to-XML converter @command{gnat2xml}
14537 @findex gnat2xml
14538 @cindex XML generation
14540 @noindent
14541 The @command{gnat2xml} tool is an ASIS-based utility that converts
14542 Ada source code into XML.
14544 @menu
14545 * Switches for gnat2xml::
14546 * Other Programs::
14547 * Structure of the XML::
14548 * Generating Representation Clauses::
14549 @end menu
14551 @node Switches for gnat2xml
14552 @section Switches for @command{gnat2xml}
14554 @noindent
14555 @command{gnat2xml} takes Ada source code as input, and produces XML
14556 that conforms to the schema.
14558 Usage:
14560 @smallexample
14561 gnat2xml [options] filenames [-files filename] [-cargs gcc_switches]
14562 @end smallexample
14564 @noindent
14565 options:
14566 @smallexample
14568 --help -- generate usage information and quit, ignoring all other options
14569 --version -- print version and quit, ignoring all other options
14571 -P @file{file} -- indicates the name of the project file that describes
14572       the set of sources to be processed. The exact set of argument
14573       sources depends on other options specified, see below.
14575 -U -- if a project file is specified and no argument source is explicitly
14576       specified, process all the units of the closure of the argument project.
14577       Otherwise this option has no effect.
14579 -U @var{main_unit} -- if a project file is specified and no argument source
14580       is explicitly specified (either directly or by means of @option{-files}
14581       option), process the closure of units rooted at @var{main_unit}.
14582       Otherwise this option has no effect.
14584 -X@var{name}=@var{value} -- indicates that external variable @var{name} in
14585       the argument project has the value @var{value}. Has no effect if no
14586       project is specified as tool argument.
14588 --incremental -- incremental processing on a per-file basis. Source files are
14589       only processed if they have been modified, or if files they depend
14590       on have been modified. This is similar to the way gnatmake/gprbuild
14591       only compiles files that need to be recompiled. A project file
14592       is required in this mode.
14594 -j@var{n} -- In @option{--incremental} mode, use @var{n} @command{gnat2xml}
14595       processes to perform XML generation in parallel. If @var{n} is 0, then
14596       the maximum number of parallel tree creations is the number of core
14597       processors on the platform.
14599 --output-dir=@var{dir} -- generate one .xml file for each Ada source file, in
14600       directory @file{dir}. (Default is to generate the XML to standard
14601       output.)
14603 -I <include-dir>
14604       directories to search for dependencies
14605       You can also set the ADA_INCLUDE_PATH environment variable for this.
14607 --compact -- debugging version, with interspersed source, and a more
14608       compact representation of "sloc". This version does not conform
14609       to any schema.
14611 --rep-clauses -- generate representation clauses (see ``Generating
14612       Representation Clauses'' below).
14614 -files=filename - the name of a text file containing a list
14615                   of Ada source files to process
14617 -q -- quiet
14618 -v -- verbose
14620 -cargs ... -- options to pass to gcc
14621 @end smallexample
14623 @noindent
14624 If a project file is specified and no argument source is explicitly
14625 specified, and no @option{-U} is specified, then the set of processed
14626 sources is all the immediate units of the argument project.
14628 Example:
14630 @smallexample
14631 gnat2xml -v -output-dir=xml-files *.ad[sb]
14632 @end smallexample
14634 @noindent
14635 The above will create *.xml files in the @file{xml-files} subdirectory.
14636 For example, if there is an Ada package Mumble.Dumble, whose spec and
14637 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
14638 the above will produce xml-files/mumble-dumble.ads.xml and
14639 xml-files/mumble-dumble.adb.xml.
14641 @node Other Programs
14642 @section Other Programs
14644 @noindent
14645 The distribution includes two other programs that are related to
14646 @command{gnat2xml}:
14648 @command{gnat2xsd} is the schema generator, which generates the schema
14649 to standard output, based on the structure of Ada as encoded by
14650 ASIS. You don't need to run @command{gnat2xsd} in order to use
14651 @command{gnat2xml}. To generate the schema, type:
14653 @smallexample
14654 gnat2xsd > ada-schema.xsd
14655 @end smallexample
14657 @noindent
14658 @command{gnat2xml} generates XML files that will validate against
14659 @file{ada-schema.xsd}.
14661 @command{xml2gnat} is a back-translator that translates the XML back
14662 into Ada source code. The Ada generated by @command{xml2gnat} has
14663 identical semantics to the original Ada code passed to
14664 @command{gnat2xml}. It is not textually identical, however --- for
14665 example, no attempt is made to preserve the original indentation.
14667 @node Structure of the XML
14668 @section Structure of the XML
14670 @noindent
14671 The primary documentation for the structure of the XML generated by
14672 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
14673 following documentation gives additional details needed to understand
14674 the schema and therefore the XML.
14676 The elements listed under Defining Occurrences, Usage Occurrences, and
14677 Other Elements represent the syntactic structure of the Ada program.
14678 Element names are given in lower case, with the corresponding element
14679 type Capitalized_Like_This. The element and element type names are
14680 derived directly from the ASIS enumeration type Flat_Element_Kinds,
14681 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
14682 removed. For example, the ASIS enumeration literal
14683 An_Assignment_Statement corresponds to the XML element
14684 assignment_statement of XML type Assignment_Statement.
14686 To understand the details of the schema and the corresponding XML, it is
14687 necessary to understand the ASIS standard, as well as the GNAT-specific
14688 extension to ASIS.
14690 A defining occurrence is an identifier (or character literal or operator
14691 symbol) declared by a declaration. A usage occurrence is an identifier
14692 (or ...) that references such a declared entity. For example, in:
14694 @smallexample
14695 type T is range 1..10;
14696 X, Y : constant T := 1;
14697 @end smallexample
14699 @noindent
14700 The first ``T'' is the defining occurrence of a type. The ``X'' is the
14701 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
14702 a usage occurrence referring to the defining occurrence of T.
14704 Each element has a 'sloc' (source location), and subelements for each
14705 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
14706 The types of subelements are as defined in the ASIS standard. For
14707 example, for the right-hand side of an assignment_statement we have
14708 the following comment in asis-statements.ads:
14710 @smallexample
14711 ------------------------------------------------------------------------------
14712 --  18.3  function Assignment_Expression
14713 ------------------------------------------------------------------------------
14715    function Assignment_Expression
14716      (Statement : Asis.Statement)
14717       return      Asis.Expression;
14719 ------------------------------------------------------------------------------
14721 --  Returns the expression from the right hand side of the assignment.
14723 --  Returns Element_Kinds:
14724 --       An_Expression
14725 @end smallexample
14727 @noindent
14728 The corresponding sub-element of type Assignment_Statement is:
14730 @smallexample
14731 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
14732 @end smallexample
14734 @noindent
14735 where Expression_Class is defined by an xsd:choice of all the
14736 various kinds of expression.
14738 The 'sloc' of each element indicates the starting and ending line and
14739 column numbers. Column numbers are character counts; that is, a tab
14740 counts as 1, not as however many spaces it might expand to.
14742 Subelements of type Element have names ending in ``_q'' (for ASIS
14743 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
14744 List'').
14746 Some subelements are ``Boolean''. For example, Private_Type_Definition
14747 has has_abstract_q and has_limited_q, to indicate whether those
14748 keywords are present, as in @code{type T is abstract limited
14749 private;}. False is represented by a Nil_Element. True is represented
14750 by an element type specific to that query (for example, Abstract and
14751 Limited).
14753 The root of the tree is a Compilation_Unit, with attributes:
14755 @itemize @bullet
14756 @item
14757 unit_kind, unit_class, and unit_origin. These are strings that match the
14758 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
14759 in package Asis.
14761 @item
14762 unit_full_name is the full expanded name of the unit, starting from a
14763 root library unit. So for @code{package P.Q.R is ...},
14764 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
14766 @item
14767 def_name is the same as unit_full_name for library units; for subunits,
14768 it is just the simple name.
14770 @item
14771 source_file is the name of the Ada source file. For example, for
14772 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
14773 interpret the source locations --- the ``sloc'' of all elements
14774 within this Compilation_Unit refers to line and column numbers
14775 within the named file.
14776 @end itemize
14778 @noindent
14779 Defining occurrences have these attributes:
14781 @itemize @bullet
14782 @item
14783 def_name is the simple name of the declared entity, as written in the Ada
14784 source code.
14786 @item
14787 def is a unique URI of the form:
14789  ada://kind/fully/qualified/name
14791 where:
14793  kind indicates the kind of Ada entity being declared (see below), and
14795  fully/qualified/name, is the fully qualified name of the Ada
14796  entity, with each of ``fully'', ``qualified'', and ``name'' being
14797  mangled for uniqueness. We do not document the mangling
14798  algorithm, which is subject to change; we just guarantee that the
14799  names are unique in the face of overloading.
14801 @item
14802 type is the type of the declared object, or @code{null} for
14803 declarations of things other than objects.
14804 @end itemize
14806 @noindent
14807 Usage occurrences have these attributes:
14809 @itemize @bullet
14810 @item
14811 ref_name is the same as the def_name of the corresponding defining
14812 occurrence. This attribute is not of much use, because of
14813 overloading; use ref for lookups, instead.
14815 @item
14816 ref is the same as the def of the corresponding defining
14817 occurrence.
14818 @end itemize
14820 @noindent
14821 In summary, @code{def_name} and @code{ref_name} are as in the source
14822 code of the declaration, possibly overloaded, whereas @code{def} and
14823 @code{ref} are unique-ified.
14825 Literal elements have this attribute:
14827 @itemize @bullet
14828 @item
14829 lit_val is the value of the literal as written in the source text,
14830 appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
14831 only to numeric and string literals. Enumeration literals in Ada are
14832 not really "literals" in the usual sense; they are usage occurrences,
14833 and have ref_name and ref as described above. Note also that string
14834 literals used as operator symbols are treated as defining or usage
14835 occurrences, not as literals.
14836 @end itemize
14838 @noindent
14839 Elements that can syntactically represent names and expressions (which
14840 includes usage occurrences, plus function calls and so forth) have this
14841 attribute:
14843 @itemize @bullet
14844 @item
14845 type. If the element represents an expression or the name of an object,
14846 'type' is the 'def' for the defining occurrence of the type of that
14847 expression or name. Names of other kinds of entities, such as package
14848 names and type names, do not have a type in Ada; these have type="null"
14849 in the XML.
14850 @end itemize
14852 @noindent
14853 Pragma elements have this attribute:
14855 @itemize @bullet
14856 @item
14857 pragma_name is the name of the pragma. For language-defined pragmas, the
14858 pragma name is redundant with the element kind (for example, an
14859 assert_pragma element necessarily has pragma_name="Assert"). However, all
14860 implementation-defined pragmas are lumped together in ASIS as a single
14861 element kind (for example, the GNAT-specific pragma Unreferenced is
14862 represented by an implementation_defined_pragma element with
14863 pragma_name="Unreferenced").
14864 @end itemize
14866 @noindent
14867 Defining occurrences of formal parameters and generic formal objects have this
14868 attribute:
14870 @itemize @bullet
14871 @item
14872 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
14873 @end itemize
14875 @noindent
14876 All elements other than Not_An_Element have this attribute:
14878 @itemize @bullet
14879 @item
14880 checks is a comma-separated list of run-time checks that are needed
14881 for that element. The possible checks are: do_accessibility_check,
14882 do_discriminant_check,do_division_check,do_length_check,
14883 do_overflow_check,do_range_check,do_storage_check,do_tag_check.
14884 @end itemize
14886 @noindent
14887 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
14888 enumeration type Flat_Declaration_Kinds, declared in
14889 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
14890 any trailing "_Declaration" or "_Specification" removed. Thus, the
14891 possible kinds are as follows:
14893 @smallexample
14894 ordinary_type
14895 task_type
14896 protected_type
14897 incomplete_type
14898 tagged_incomplete_type
14899 private_type
14900 private_extension
14901 subtype
14902 variable
14903 constant
14904 deferred_constant
14905 single_task
14906 single_protected
14907 integer_number
14908 real_number
14909 enumeration_literal
14910 discriminant
14911 component
14912 loop_parameter
14913 generalized_iterator
14914 element_iterator
14915 procedure
14916 function
14917 parameter
14918 procedure_body
14919 function_body
14920 return_variable
14921 return_constant
14922 null_procedure
14923 expression_function
14924 package
14925 package_body
14926 object_renaming
14927 exception_renaming
14928 package_renaming
14929 procedure_renaming
14930 function_renaming
14931 generic_package_renaming
14932 generic_procedure_renaming
14933 generic_function_renaming
14934 task_body
14935 protected_body
14936 entry
14937 entry_body
14938 entry_index
14939 procedure_body_stub
14940 function_body_stub
14941 package_body_stub
14942 task_body_stub
14943 protected_body_stub
14944 exception
14945 choice_parameter
14946 generic_procedure
14947 generic_function
14948 generic_package
14949 package_instantiation
14950 procedure_instantiation
14951 function_instantiation
14952 formal_object
14953 formal_type
14954 formal_incomplete_type
14955 formal_procedure
14956 formal_function
14957 formal_package
14958 formal_package_declaration_with_box
14959 @end smallexample
14961 @node Generating Representation Clauses
14962 @section Generating Representation Clauses
14964 @noindent
14965 If the @option{--rep-clauses} switch is given, @command{gnat2xml} will
14966 generate representation clauses for certain types showing the
14967 representation chosen by the compiler. The information is produced by
14968 the ASIS ``Data Decomposition'' facility --- see the
14969 @code{Asis.Data_Decomposition} package for details.
14971 Not all types are supported. For example, @code{Type_Model_Kind} must
14972 be @code{A_Simple_Static_Model}. Types declared within generic units
14973 have no representation. The clauses that are generated include
14974 @code{attribute_definition_clauses} for @code{Size} and
14975 @code{Component_Size}, as well as
14976 @code{record_representation_clauses}.
14978 There is no guarantee that the generated representation clauses could
14979 have actually come from legal Ada code; Ada has some restrictions that
14980 are not necessarily obeyed by the generated clauses.
14982 The representation clauses are surrounded by comment elements to
14983 indicate that they are automatically generated, something like this:
14985 @smallexample
14986 <comment text="--gen+">
14988 <attribute_definition_clause>
14990 <comment text="--gen-">
14992 @end smallexample
14994 @end ifclear
14996 @ifclear FSFEDITION
14997 @c *********************************
14998 @node The GNAT Metrics Tool gnatmetric
14999 @chapter The GNAT Metrics Tool @command{gnatmetric}
15000 @findex gnatmetric
15001 @cindex Metric tool
15003 @noindent
15004 The @command{gnatmetric} tool is an ASIS-based utility
15005 for computing various program metrics.
15006 It takes an Ada source file as input and generates a file containing the
15007 metrics data as output. Various switches control which
15008 metrics are computed and output.
15010 @menu
15011 * Switches for gnatmetric::
15012 @end menu
15014 To compute program metrics, @command{gnatmetric} invokes the Ada
15015 compiler and generates and uses the ASIS tree for the input source;
15016 thus the input must be legal Ada code, and the tool should have all the
15017 information needed to compile the input source. To provide this information,
15018 you may specify as a tool parameter the project file the input source belongs to
15019 (or you may call @command{gnatmetric}
15020 through the @command{gnat} driver (see @ref{The GNAT Driver and
15021 Project Files}). Another possibility is to specify the source search
15022 path and needed configuration files in @option{-cargs} section of @command{gnatmetric}
15023 call, see the description of the @command{gnatmetric} switches below.
15025 If the set of sources to be processed by @code{gnatmetric} contains sources with
15026 preprocessing directives
15027 then the needed options should be provided to run preprocessor as a part of
15028 the @command{gnatmetric} call, and the computed metrics
15029 will correspond to preprocessed sources.
15032 The @command{gnatmetric} command has the form
15034 @smallexample
15035 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15036 @c Expanding @ovar macro inline (explanation in macro def comments)
15037 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15038 @end smallexample
15040 @noindent
15041 where
15042 @itemize @bullet
15043 @item
15044 @var{switches} specify the metrics to compute and define the destination for
15045 the output
15047 @item
15048 Each @var{filename} is the name (including the extension) of a source
15049 file to process. ``Wildcards'' are allowed, and
15050 the file name may contain path information.
15051 If no @var{filename} is supplied, then the @var{switches} list must contain
15052 at least one
15053 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15054 Including both a @option{-files} switch and one or more
15055 @var{filename} arguments is permitted.
15057 @item
15058 @samp{@var{gcc_switches}} is a list of switches for
15059 @command{gcc}. They will be passed on to all compiler invocations made by
15060 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15061 @option{-I} switches to form the source search path,
15062 and use the @option{-gnatec} switch to set the configuration file,
15063 use the @option{-gnat05} switch if sources should be compiled in
15064 Ada 2005 mode etc.
15065 @end itemize
15067 @node Switches for gnatmetric
15068 @section Switches for @command{gnatmetric}
15070 @noindent
15071 The following subsections describe the various switches accepted by
15072 @command{gnatmetric}, organized by category.
15074 @menu
15075 * Output Files Control::
15076 * Disable Metrics For Local Units::
15077 * Specifying a set of metrics to compute::
15078 * Other gnatmetric Switches::
15079 @ignore
15080 * Generate project-wide metrics::
15081 @end ignore
15082 @end menu
15084 @node Output Files Control
15085 @subsection Output File Control
15086 @cindex Output file control in @command{gnatmetric}
15088 @noindent
15089 @command{gnatmetric} has two output formats. It can generate a
15090 textual (human-readable) form, and also XML. By default only textual
15091 output is generated.
15093 When generating the output in textual form, @command{gnatmetric} creates
15094 for each Ada source file a corresponding text file
15095 containing the computed metrics, except for the case when the set of metrics
15096 specified by gnatmetric parameters consists only of metrics that are computed
15097 for the whole set of analyzed sources, but not for each Ada source.
15098 By default, the name of the file containing metric information for a source
15099 is obtained by appending the @file{.metrix} suffix to the
15100 name of the input source file. If not otherwise specified and no project file
15101 is specified as @command{gnatmetric} option this file is placed in the same
15102 directory as where the source file is located. If @command{gnatmetric} has a
15103 project  file as its parameter, it places all the generated files in the
15104 object directory of the project (or in the project source directory if the
15105 project does not define an objects directory), if @option{--subdirs} option
15106 is specified, the files are placed in the subrirectory of this directory
15107 specified by this option.
15109 All the output information generated in XML format is placed in a single
15110 file. By default the name of this file is @file{metrix.xml}.
15111 If not otherwise specified and if no project file is specified
15112 as @command{gnatmetric} option  this file is placed in the
15113 current directory.
15115 Some of the computed metrics are summed over the units passed to
15116 @command{gnatmetric}; for example, the total number of lines of code.
15117 By default this information is sent to @file{stdout}, but a file
15118 can be specified with the @option{-og} switch.
15120 The following switches control the @command{gnatmetric} output:
15122 @table @option
15123 @cindex @option{-x} (@command{gnatmetric})
15124 @item -x
15125 Generate the XML output
15127 @cindex @option{-xs} (@command{gnatmetric})
15128 @item -xs
15129 Generate the XML output and the XML schema file that describes the structure
15130 of the XML metric report, this schema is assigned to the XML file. The schema
15131 file has the same name as the XML output file with @file{.xml} suffix replaced
15132 with @file{.xsd}
15134 @cindex @option{-nt} (@command{gnatmetric})
15135 @item -nt
15136 Do not generate the output in text form (implies @option{-x})
15138 @cindex @option{-d} (@command{gnatmetric})
15139 @item -d @var{output_dir}
15140 Put text files with detailed metrics into @var{output_dir}
15142 @cindex @option{-o} (@command{gnatmetric})
15143 @item -o @var{file_suffix}
15144 Use @var{file_suffix}, instead of @file{.metrix}
15145 in the name of the output file.
15147 @cindex @option{-og} (@command{gnatmetric})
15148 @item -og @var{file_name}
15149 Put global metrics into @var{file_name}
15151 @cindex @option{-ox} (@command{gnatmetric})
15152 @item -ox @var{file_name}
15153 Put the XML output into @var{file_name} (also implies @option{-x})
15155 @cindex @option{-sfn} (@command{gnatmetric})
15156 @item -sfn
15157 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15158 output includes the name(s) of the Ada source file(s) from which the metrics
15159 are computed.  By default each name includes the absolute path. The
15160 @option{-sfn} switch causes @command{gnatmetric}
15161 to exclude all directory information from the file names that are output.)
15163 @end table
15165 @node Disable Metrics For Local Units
15166 @subsection Disable Metrics For Local Units
15167 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15169 @noindent
15170 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15171 one compilation
15172 unit per one source file. It computes line metrics for the whole source
15173 file, and it also computes syntax
15174 and complexity metrics for the file's outermost unit.
15176 By default, @command{gnatmetric} will also compute all metrics for certain
15177 kinds of locally declared program units:
15179 @itemize @bullet
15180 @item
15181 subprogram (and generic subprogram) bodies;
15183 @item
15184 package (and generic package) specs and bodies;
15186 @item
15187 task object and type specifications and bodies;
15189 @item
15190 protected object and type specifications and bodies.
15191 @end itemize
15193 @noindent
15194 These kinds of entities will be referred to as
15195 @emph{eligible local program units}, or simply @emph{eligible local units},
15196 @cindex Eligible local unit (for @command{gnatmetric})
15197 in the discussion below.
15199 Note that a subprogram declaration, generic instantiation,
15200 or renaming declaration only receives metrics
15201 computation when it appear as the outermost entity
15202 in a source file.
15204 Suppression of metrics computation for eligible local units can be
15205 obtained via the following switch:
15207 @table @option
15208 @cindex @option{-nolocal} (@command{gnatmetric})
15209 @item -nolocal
15210 Do not compute detailed metrics for eligible local program units
15212 @end table
15214 @node Specifying a set of metrics to compute
15215 @subsection Specifying a set of metrics to compute
15217 @noindent
15218 By default all the metrics are computed and reported. The switches
15219 described in this subsection allow you to control, on an individual
15220 basis, whether metrics are computed and
15221 reported. If at least one positive metric
15222 switch is specified (that is, a switch that defines that a given
15223 metric or set of metrics is to be computed), then only
15224 explicitly specified metrics are reported.
15226 @menu
15227 * Line Metrics Control::
15228 * Syntax Metrics Control::
15229 * Complexity Metrics Control::
15230 * Coupling Metrics Control::
15231 @end menu
15233 @node Line Metrics Control
15234 @subsubsection Line Metrics Control
15235 @cindex Line metrics control in @command{gnatmetric}
15237 @noindent
15238 For any (legal) source file, and for each of its
15239 eligible local program units, @command{gnatmetric} computes the following
15240 metrics:
15242 @itemize @bullet
15243 @item
15244 the total number of lines;
15246 @item
15247 the total number of code lines (i.e., non-blank lines that are not comments)
15249 @item
15250 the number of comment lines
15252 @item
15253 the number of code lines containing end-of-line comments;
15255 @item
15256 the comment percentage: the ratio between the number of lines that contain
15257 comments and the number of all non-blank lines, expressed as a percentage;
15259 @item
15260 the number of empty lines and lines containing only space characters and/or
15261 format effectors (blank lines)
15263 @item
15264 the average number of code lines in subprogram bodies, task bodies, entry
15265 bodies and statement sequences in package bodies (this metric is only computed
15266 across the whole set of the analyzed units)
15268 @end itemize
15270 @noindent
15271 @command{gnatmetric} sums the values of the line metrics for all the
15272 files being processed and then generates the cumulative results. The tool
15273 also computes for all the files being processed the average number of code
15274 lines in bodies.
15276 You can use the following switches to select the specific line metrics
15277 to be computed and reported.
15279 @table @option
15280 @cindex @option{--lines@var{x}} (@command{gnatmetric})
15282 @cindex @option{--no-lines@var{x}}
15284 @item --lines-all
15285 Report all the line metrics
15287 @item --no-lines-all
15288 Do not report any of line metrics
15290 @item --lines
15291 Report the number of all lines
15293 @item --no-lines
15294 Do not report the number of all lines
15296 @item --lines-code
15297 Report the number of code lines
15299 @item --no-lines-code
15300 Do not report the number of code lines
15302 @item --lines-comment
15303 Report the number of comment lines
15305 @item --no-lines-comment
15306 Do not report the number of comment lines
15308 @item --lines-eol-comment
15309 Report the number of code lines containing
15310 end-of-line comments
15312 @item --no-lines-eol-comment
15313 Do not report the number of code lines containing
15314 end-of-line comments
15316 @item --lines-ratio
15317 Report the comment percentage in the program text
15319 @item --no-lines-ratio
15320 Do not report the comment percentage in the program text
15322 @item --lines-blank
15323 Report the number of blank lines
15325 @item --no-lines-blank
15326 Do not report the number of blank lines
15328 @item --lines-average
15329 Report the average number of code lines in subprogram bodies, task bodies,
15330 entry bodies and statement sequences in package bodies. The metric is computed
15331 and reported for the whole set of processed Ada sources only.
15333 @item --no-lines-average
15334 Do not report the average number of code lines in subprogram bodies,
15335 task bodies, entry bodies and statement sequences in package bodies.
15337 @end table
15339 @node Syntax Metrics Control
15340 @subsubsection Syntax Metrics Control
15341 @cindex Syntax metrics control in @command{gnatmetric}
15343 @noindent
15344 @command{gnatmetric} computes various syntactic metrics for the
15345 outermost unit and for each eligible local unit:
15347 @table @emph
15348 @item LSLOC (``Logical Source Lines Of Code'')
15349 The total number of declarations and the total number of statements. Note
15350 that the definition of declarations is the one given in the reference
15351 manual:
15353 @noindent
15354 ``Each of the following is defined to be a declaration: any basic_declaration;
15355 an enumeration_literal_specification; a discriminant_specification;
15356 a component_declaration; a loop_parameter_specification; a
15357 parameter_specification; a subprogram_body; an entry_declaration;
15358 an entry_index_specification; a choice_parameter_specification;
15359 a generic_formal_parameter_declaration.''
15361 This means for example that each enumeration literal adds one to the count,
15362 as well as each subprogram parameter.
15364 Thus the results from this metric will be significantly greater than might
15365 be expected from a naive view of counting semicolons.
15367 @item Maximal static nesting level of inner program units
15368 According to
15369 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15370 package, a task unit, a protected unit, a
15371 protected entry, a generic unit, or an explicitly declared subprogram other
15372 than an enumeration literal.''
15374 @item Maximal nesting level of composite syntactic constructs
15375 This corresponds to the notion of the
15376 maximum nesting level in the GNAT built-in style checks
15377 (@pxref{Style Checking})
15378 @end table
15380 @noindent
15381 For the outermost unit in the file, @command{gnatmetric} additionally computes
15382 the following metrics:
15384 @table @emph
15385 @item Public subprograms
15386 This metric is computed for package specs. It is the
15387 number of subprograms and generic subprograms declared in the visible
15388 part (including the visible part of nested packages, protected objects, and
15389 protected types).
15391 @item All subprograms
15392 This metric is computed for bodies and subunits. The
15393 metric is equal to a total number of subprogram bodies in the compilation
15394 unit.
15395 Neither generic instantiations nor renamings-as-a-body nor body stubs
15396 are counted. Any subprogram body is counted, independently of its nesting
15397 level and enclosing constructs. Generic bodies and bodies of protected
15398 subprograms are counted in the same way as ``usual'' subprogram bodies.
15400 @item Public types
15401 This metric is computed for package specs and
15402 generic package declarations. It is the total number of types
15403 that can be referenced from outside this compilation unit, plus the
15404 number of types from all the visible parts of all the visible generic
15405 packages. Generic formal types are not counted.  Only types, not subtypes,
15406 are included.
15408 @noindent
15409 Along with the total number of public types, the following
15410 types are counted and reported separately:
15412 @itemize @bullet
15413 @item
15414 Abstract types
15416 @item
15417 Root tagged types (abstract, non-abstract, private, non-private). Type
15418 extensions are @emph{not} counted
15420 @item
15421 Private types (including private extensions)
15423 @item
15424 Task types
15426 @item
15427 Protected types
15429 @end itemize
15431 @item All types
15432 This metric is computed for any compilation unit. It is equal to the total
15433 number of the declarations of different types given in the compilation unit.
15434 The private and the corresponding full type declaration are counted as one
15435 type declaration. Incomplete type declarations and generic formal types
15436 are not counted.
15437 No distinction is made among different kinds of types (abstract,
15438 private etc.); the total number of types is computed and reported.
15440 @end table
15442 @noindent
15443 By default, all the syntax metrics are computed and reported. You can use the
15444 following switches to select specific syntax metrics.
15446 @table @option
15448 @cindex @option{--syntax@var{x}} (@command{gnatmetric})
15450 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15452 @item --syntax-all
15453 Report all the syntax metrics
15455 @item --no-syntax-all
15456 Do not report any of syntax metrics
15458 @item --declarations
15459 Report the total number of declarations
15461 @item --no-declarations
15462 Do not report the total number of declarations
15464 @item --statements
15465 Report the total number of statements
15467 @item --no-statements
15468 Do not report the total number of statements
15470 @item --public-subprograms
15471 Report the number of public subprograms in a compilation unit
15473 @item --no-public-subprograms
15474 Do not report the number of public subprograms in a compilation unit
15476 @item --all-subprograms
15477 Report the number of all the subprograms in a compilation unit
15479 @item --no-all-subprograms
15480 Do not report the number of all the subprograms in a compilation unit
15482 @item --public-types
15483 Report the number of public types in a compilation unit
15485 @item --no-public-types
15486 Do not report the number of public types in a compilation unit
15488 @item --all-types
15489 Report the number of all the types in a compilation unit
15491 @item --no-all-types
15492 Do not report the number of all the types in a compilation unit
15494 @item --unit-nesting
15495 Report the maximal program unit nesting level
15497 @item --no-unit-nesting
15498 Do not report the maximal program unit nesting level
15500 @item --construct-nesting
15501 Report the maximal construct nesting level
15503 @item --no-construct-nesting
15504 Do not report the maximal construct nesting level
15506 @end table
15508 @node Complexity Metrics Control
15509 @subsubsection Complexity Metrics Control
15510 @cindex Complexity metrics control in @command{gnatmetric}
15512 @noindent
15513 For a program unit that is an executable body (a subprogram body (including
15514 generic bodies), task body, entry body or a package body containing
15515 its own statement sequence) @command{gnatmetric} computes the following
15516 complexity metrics:
15518 @itemize @bullet
15519 @item
15520 McCabe cyclomatic complexity;
15522 @item
15523 McCabe essential complexity;
15525 @item
15526 maximal loop nesting level;
15528 @item
15529 extra exit points (for subprograms);
15530 @end itemize
15532 @noindent
15533 The McCabe cyclomatic complexity metric is defined
15534 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15536 According to McCabe, both control statements and short-circuit control forms
15537 should be taken into account when computing cyclomatic complexity.
15538 For Ada 2012 we have also take into account conditional expressions
15539 and quantified expressions. For each body, we compute three metric values:
15541 @itemize @bullet
15542 @item
15543 the complexity introduced by control
15544 statements only, without taking into account short-circuit forms
15545 (referred as @code{statement complexity} in @command{gnatmetric} output),
15547 @item
15548 the complexity introduced by short-circuit control forms only
15549 (referred as @code{expression complexity} in @command{gnatmetric} output), and
15551 @item
15552 the total
15553 cyclomatic complexity, which is the sum of these two values
15554 (referred as @code{cyclomatic complexity} in @command{gnatmetric} output).
15555 @end itemize
15557 @noindent
15559 The cyclomatic complexity is also computed for Ada 2012 expression functions.
15560 An expression function cannot have statements as its components, so only one
15561 metric value is computed as a cyclomatic complexity of an expression function.
15563 The origin of cyclomatic complexity metric is the need to estimate the number
15564 of independent paths in the control flow graph that in turn gives the number
15565 of tests needed to satisfy paths coverage testing completeness criterion.
15566 Considered from the testing point of view, a static Ada @code{loop} (that is,
15567 the @code{loop} statement having static subtype in loop parameter
15568 specification) does not add to cyclomatic complexity. By providing
15569 @option{--no-static-loop} option a user
15570 may specify that such loops should not be counted when computing the
15571 cyclomatic complexity metric
15573 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
15574 counted for the code that is reduced by excluding all the pure structural Ada
15575 control statements. An compound statement is considered as a non-structural
15576 if it contains a @code{raise} or @code{return} statement as it subcomponent,
15577 or if it contains a @code{goto} statement that transfers the control outside
15578 the operator. A selective accept statement with @code{terminate} alternative
15579 is considered as non-structural statement. When computing this metric,
15580 @code{exit} statements are treated in the same way as @code{goto}
15581 statements unless @option{-ne} option is specified.
15583 The Ada essential complexity metric defined here is intended to quantify
15584 the extent to which the software is unstructured. It is adapted from
15585 the McCabe essential complexity metric defined in
15586 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
15587 suitable for typical Ada usage. For example, short circuit forms
15588 are not penalized as unstructured in the Ada essential complexity metric.
15590 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15591 the code in the exception handlers and in all the nested program units. The
15592 code of assertions and predicates (that is, subprogram preconditions and
15593 postconditions, subtype predicates and type invariants) is also skipped.
15595 By default, all the complexity metrics are computed and reported.
15596 For more fine-grained control you can use
15597 the following switches:
15599 @table @option
15600 @cindex @option{-complexity@var{x}} (@command{gnatmetric})
15602 @cindex @option{--no-complexity@var{x}}
15604 @item --complexity-all
15605 Report all the complexity metrics
15607 @item --no-complexity-all
15608 Do not report any of complexity metrics
15610 @item --complexity-cyclomatic
15611 Report the McCabe Cyclomatic Complexity
15613 @item --no-complexity-cyclomatic
15614 Do not report the McCabe Cyclomatic Complexity
15616 @item --complexity-essential
15617 Report the Essential Complexity
15619 @item --no-complexity-essential
15620 Do not report the Essential Complexity
15622 @item --loop-nesting
15623 Report maximal loop nesting level
15625 @item --no-loop-nesting
15626 Do not report maximal loop nesting level
15628 @item --complexity-average
15629 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15630 task bodies, entry bodies and statement sequences in package bodies.
15631 The metric is computed and reported for whole set of processed Ada sources
15632 only.
15634 @item --no-complexity-average
15635 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15636 bodies, task bodies, entry bodies and statement sequences in package bodies
15638 @cindex @option{-ne} (@command{gnatmetric})
15639 @item -ne
15640 Do not consider @code{exit} statements as @code{goto}s when
15641 computing Essential Complexity
15643 @cindex @option{--no-static-loop} (@command{gnatmetric})
15644 @item --no-static-loop
15645 Do not consider static loops when computing cyclomatic complexity
15647 @item --extra-exit-points
15648 Report the extra exit points for subprogram bodies. As an exit point, this
15649 metric counts @code{return} statements and raise statements in case when the
15650 raised exception is not handled in the same body. In case of a function this
15651 metric subtracts 1 from the number of exit points, because a function body
15652 must contain at least one @code{return} statement.
15654 @item --no-extra-exit-points
15655 Do not report the extra exit points for subprogram bodies
15656 @end table
15659 @node Coupling Metrics Control
15660 @subsubsection Coupling Metrics Control
15661 @cindex Coupling metrics control in @command{gnatmetric}
15663 @noindent
15664 @cindex Coupling metrics (in @command{gnatmetric})
15665 Coupling metrics measure the dependencies between a given entity and other
15666 entities in the program. This information is useful since high coupling
15667 may signal potential issues with maintainability as the program evolves.
15669 @command{gnatmetric} computes the following coupling metrics:
15671 @itemize @bullet
15673 @item
15674 @emph{object-oriented coupling}, for classes in traditional object-oriented
15675 sense;
15677 @item
15678 @emph{unit coupling}, for all the program units making up a program;
15680 @item
15681 @emph{control coupling}, reflecting dependencies between a unit and
15682 other units that contain subprograms.
15683 @end itemize
15685 @noindent
15686 Two kinds of coupling metrics are computed:
15688 @itemize @bullet
15689 @item fan-out coupling (``efferent coupling''):
15690 @cindex fan-out coupling
15691 @cindex efferent coupling
15692 the number of entities the given entity depends upon. This metric
15693 reflects how the given entity depends on the changes in the
15694 ``external world''.
15696 @item fan-in coupling (``afferent'' coupling):
15697 @cindex fan-in coupling
15698 @cindex afferent coupling
15699 the number of entities that depend on a given entity.
15700 This metric reflects how the ``external world'' depends on the changes in a
15701 given entity.
15702 @end itemize
15704 @noindent
15705 Object-oriented coupling metrics measure the dependencies
15706 between a given class (or a group of classes) and the other classes in the
15707 program. In this subsection the term ``class'' is used in its traditional
15708 object-oriented programming sense (an instantiable module that contains data
15709 and/or method members). A @emph{category} (of classes) is a group of closely
15710 related classes that are reused and/or modified together.
15712 A class @code{K}'s fan-out coupling is the number of classes
15713 that @code{K} depends upon.
15714 A category's fan-out coupling is the number of classes outside the
15715 category that the classes inside the category depend upon.
15717 A class @code{K}'s fan-in coupling is the number of classes
15718 that depend upon @code{K}.
15719 A category's fan-in coupling is the number of classes outside the
15720 category that depend on classes belonging to the category.
15722 Ada's object-oriented paradigm separates the instantiable entity
15723 (type) from the module (package), so the definition of the coupling
15724 metrics for Ada maps the class and class category notions
15725 onto Ada constructs.
15727 For the coupling metrics, several kinds of modules that define a tagged type
15728 or an interface type  -- library packages, library generic packages, and
15729 library generic package instantiations -- are considered to be classes.
15730 A category consists of a library package (or
15731 a library generic package) that defines a tagged or an interface type,
15732 together with all its descendant (generic) packages that define tagged
15733 or interface types. Thus a
15734 category is an Ada hierarchy of library-level program units. Class
15735 coupling in Ada is referred to as ``tagged coupling'', and category coupling
15736 is referred to as ``hierarchy coupling''.
15738 For any package serving as a class, its body and subunits (if any) are
15739 considered together with its spec when computing dependencies, and coupling
15740 metrics are reported for spec units only. Dependencies between classes
15741 mean Ada semantic dependencies. For object-oriented coupling
15742 metrics, only dependencies on units treated as classes are
15743 considered.
15745 Similarly, for unit and control coupling an entity is considered to be the
15746 conceptual construct consisting of the entity's specification, body, and
15747 any subunits (transitively).
15748 @command{gnatmetric} computes
15749 the dependencies of all these units as a whole, but
15750 metrics are only reported for spec
15751 units (or for a subprogram body unit in case if there is no
15752 separate spec for the given subprogram).
15754 For unit coupling, dependencies are computed between all kinds of program
15755 units. For control coupling, the dependencies of a given unit are limited to
15756 those units that define subprograms. Thus control fan-out coupling is reported
15757 for all units, but control fan-in coupling is only reported for units
15758 that define subprograms.
15760 The following simple example illustrates the difference between unit coupling
15761 and control coupling metrics:
15763 @smallexample @c ada
15764 @group
15765 @b{package} Lib_1 @b{is}
15766     @b{function} F_1 (I : Integer) @b{return} Integer;
15767 @b{end} Lib_1;
15768 @end group
15770 @group
15771 @b{package} Lib_2 @b{is}
15772     @b{type} T_2 @b{is} @b{new} Integer;
15773 @b{end} Lib_2;
15774 @end group
15776 @group
15777 @b{package} @b{body} Lib_1 @b{is}
15778     @b{function} F_1 (I : Integer) @b{return} Integer @b{is}
15779     @b{begin}
15780        @b{return} I + 1;
15781     @b{end} F_1;
15782 @b{end} Lib_1;
15783 @end group
15785 @group
15786 @b{with} Lib_2; @b{use} Lib_2;
15787 @b{package} Pack @b{is}
15788     Var : T_2;
15789     @b{function} Fun (I : Integer) @b{return} Integer;
15790 @b{end} Pack;
15791 @end group
15793 @group
15794 @b{with} Lib_1; @b{use} Lib_1;
15795 @b{package} @b{body} Pack @b{is}
15796     @b{function} Fun (I : Integer) @b{return} Integer @b{is}
15797     @b{begin}
15798        @b{return} F_1 (I);
15799     @b{end} Fun;
15800 @b{end} Pack;
15801 @end group
15802 @end smallexample
15804 @noindent
15805 If we apply @command{gnatmetric} with the @option{--coupling-all} option to
15806 these units, the result will be:
15808 @smallexample
15809 @group
15810 Coupling metrics:
15811 =================
15812     Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
15813        control fan-out coupling  : 0
15814        control fan-in coupling   : 1
15815        unit fan-out coupling     : 0
15816        unit fan-in coupling      : 1
15817 @end group
15819 @group
15820     Unit Pack (C:\customers\662\L406-007\pack.ads)
15821        control fan-out coupling  : 1
15822        control fan-in coupling   : 0
15823        unit fan-out coupling     : 2
15824        unit fan-in coupling      : 0
15825 @end group
15827 @group
15828     Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
15829        control fan-out coupling  : 0
15830        unit fan-out coupling     : 0
15831        unit fan-in coupling      : 1
15832 @end group
15833 @end smallexample
15835 @noindent
15836 The result does not contain values for object-oriented
15837 coupling because none of the argument units contains a tagged type and
15838 therefore none of these units can be treated as a class.
15840 The @code{Pack} package (spec and body) depends on two
15841 units -- @code{Lib_1} @code{and Lib_2} -- and so its unit fan-out coupling
15842 is 2. Since nothing depends on it, its unit fan-in coupling is 0, as
15843 is its control fan-in coupling. Only one of the units @code{Pack} depends
15844 upon defines a subprogram, so its control fan-out coupling is 1.
15846 @code{Lib_2} depends on nothing, so its fan-out metrics are 0. It does
15847 not define any subprograms, so it has no control fan-in metric.
15848 One unit (@code{Pack}) depends on it , so its unit fan-in coupling is 1.
15850 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
15851 Its control fan-in coupling is 1 (because there is one unit
15852 depending on it).
15854 When computing coupling metrics, @command{gnatmetric} counts only
15855 dependencies between units that are arguments of the @command{gnatmetric}
15856 invocation. Coupling metrics are program-wide (or project-wide) metrics, so
15857 you should invoke @command{gnatmetric} for
15858 the complete set of sources comprising your program. This can be done
15859 by invoking @command{gnatmetric} with the corresponding project file
15860 and with the @option{-U} option.
15862 By default, all the coupling metrics are disabled. You can use the following
15863 switches to specify the coupling metrics to be computed and reported:
15865 @table @option
15867 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
15868 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
15869 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
15870 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
15873 @item --coupling-all
15874 Report all the coupling metrics
15876 @item --tagged-coupling-out
15877 Report tagged (class) fan-out coupling
15879 @item --tagged-coupling-in
15880 Report tagged (class) fan-in coupling
15882 @item --hierarchy-coupling-out
15883 Report hierarchy (category) fan-out coupling
15885 @item --hierarchy-coupling-in
15886 Report hierarchy (category) fan-in coupling
15888 @item --unit-coupling-out
15889 Report unit fan-out coupling
15891 @item --unit-coupling-in
15892 Report unit fan-in coupling
15894 @item --control-coupling-out
15895 Report control fan-out coupling
15897 @item --control-coupling-in
15898 Report control fan-in coupling
15899 @end table
15901 @node Other gnatmetric Switches
15902 @subsection Other @code{gnatmetric} Switches
15904 @noindent
15905 Additional @command{gnatmetric} switches are as follows:
15907 @table @option
15908 @item --version
15909 @cindex @option{--version} @command{gnatmetric}
15910 Display Copyright and version, then exit disregarding all other options.
15912 @item --help
15913 @cindex @option{--help} @command{gnatmetric}
15914 Display usage, then exit disregarding all other options.
15916 @item -P @var{file}
15917 @cindex @option{-P} @command{gnatmetric}
15918 Indicates the name of the project file that describes the set of sources
15919 to be processed. The exact set of argument sources depends on other options
15920 specified, see below.
15922 @item -U
15923 @cindex @option{-U} @command{gnatmetric}
15924 If a project file is specified and no argument source is explicitly
15925 specified (either directly or by means of @option{-files} option), process
15926 all the units of the closure of the argument project. Otherwise this option
15927 has no effect.
15929 @item -U @var{main_unit}
15930 If a project file is specified and no argument source is explicitly
15931 specified (either directly or by means of @option{-files} option), process
15932 the closure of units rooted at @var{main_unit}. Otherwise this option
15933 has no effect.
15935 @item -X@var{name}=@var{value}
15936 @cindex @option{-X} @command{gnatmetric}
15937 Indicates that external variable @var{name} in the argument project
15938 has the value @var{value}. Has no effect if no project is specified as
15939 tool argument.
15941 @item --subdirs=@var{dir}
15942 @cindex @option{--subdirs=@var{dir}} @command{gnatmetric}
15943 Use the specified subdirectory of the project objects file (or of the
15944 project file directory if the project does not specify an object directory)
15945 for tool output files. Has no effect if no project is specified as
15946 tool argument r if @option{--no_objects_dir} is specified.
15948 @item --no_objects_dir
15949 @cindex @option{--no_objects_dir} @command{gnatmetric}
15950 Place all the result files into the current directory instead of
15951 project objects directory. This corresponds to the @command{gnatcheck}
15952 behavior when it is called with the project file from the
15953 GNAT driver. Has no effect if no project is specified.
15955 @item -files @var{filename}
15956 @cindex @option{-files} (@code{gnatmetric})
15957 Take the argument source files from the specified file. This file should be an
15958 ordinary text file containing file names separated by spaces or
15959 line breaks. You can use this switch more than once in the same call to
15960 @command{gnatmetric}. You also can combine this switch with
15961 an explicit list of files.
15963 @item -j@var{n}
15964 @cindex @option{-j} (@command{gnatmetric})
15965 Use @var{n} processes to carry out the tree creations (internal representations
15966 of the argument sources). On a multiprocessor machine this speeds up processing
15967 of big sets of argument sources. If @var{n} is 0, then the maximum number of
15968 parallel tree creations is the number of core processors on the platform.
15970 @cindex @option{-t} (@command{gnatmetric})
15971 @item -t
15972 Print out execution time.
15974 @item -v
15975 @cindex @option{-v} (@command{gnatmetric})
15976 Verbose mode;
15977 @command{gnatmetric} generates version information and then
15978 a trace of sources being processed.
15980 @item -q
15981 @cindex @option{-q} (@command{gnatmetric})
15982 Quiet mode.
15983 @end table
15985 @noindent
15986 If a project file is specified and no argument source is explicitly
15987 specified (either directly or by means of @option{-files} option), and no
15988 @option{-U} is specified, then the set of processed sources is
15989 all the immediate units of the argument project.
15992 @ignore
15993 @node Generate project-wide metrics
15994 @subsection Generate project-wide metrics
15996 In order to compute metrics on all units of a given project, you can use
15997 the @command{gnat} driver along with the @option{-P} option:
15998 @smallexample
15999    gnat metric -Pproj
16000 @end smallexample
16002 @noindent
16003 If the project @code{proj} depends upon other projects, you can compute
16004 the metrics on the project closure using the @option{-U} option:
16005 @smallexample
16006    gnat metric -Pproj -U
16007 @end smallexample
16009 @noindent
16010 Finally, if not all the units are relevant to a particular main
16011 program in the project closure, you can generate metrics for the set
16012 of units needed to create a given main program (unit closure) using
16013 the @option{-U} option followed by the name of the main unit:
16014 @smallexample
16015    gnat metric -Pproj -U main
16016 @end smallexample
16017 @end ignore
16018 @end ifclear
16021 @c ***********************************
16022 @node File Name Krunching with gnatkr
16023 @chapter File Name Krunching with @code{gnatkr}
16024 @findex gnatkr
16026 @noindent
16027 This chapter discusses the method used by the compiler to shorten
16028 the default file names chosen for Ada units so that they do not
16029 exceed the maximum length permitted. It also describes the
16030 @code{gnatkr} utility that can be used to determine the result of
16031 applying this shortening.
16032 @menu
16033 * About gnatkr::
16034 * Using gnatkr::
16035 * Krunching Method::
16036 * Examples of gnatkr Usage::
16037 @end menu
16039 @node About gnatkr
16040 @section About @code{gnatkr}
16042 @noindent
16043 The default file naming rule in GNAT
16044 is that the file name must be derived from
16045 the unit name. The exact default rule is as follows:
16046 @itemize @bullet
16047 @item
16048 Take the unit name and replace all dots by hyphens.
16049 @item
16050 If such a replacement occurs in the
16051 second character position of a name, and the first character is
16052 @samp{a}, @samp{g}, @samp{s}, or @samp{i},
16053 then replace the dot by the character
16054 @samp{~} (tilde)
16055 instead of a minus.
16056 @end itemize
16057 The reason for this exception is to avoid clashes
16058 with the standard names for children of System, Ada, Interfaces,
16059 and GNAT, which use the prefixes
16060 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
16061 respectively.
16063 The @option{-gnatk@var{nn}}
16064 switch of the compiler activates a ``krunching''
16065 circuit that limits file names to nn characters (where nn is a decimal
16066 integer). For example, using OpenVMS,
16067 where the maximum file name length is
16068 39, the value of nn is usually set to 39, but if you want to generate
16069 a set of files that would be usable if ported to a system with some
16070 different maximum file length, then a different value can be specified.
16071 The default value of 39 for OpenVMS need not be specified.
16073 The @code{gnatkr} utility can be used to determine the krunched name for
16074 a given file, when krunched to a specified maximum length.
16076 @node Using gnatkr
16077 @section Using @code{gnatkr}
16079 @noindent
16080 The @code{gnatkr} command has the form
16082 @smallexample
16083 @c $ gnatkr @var{name} @ovar{length}
16084 @c Expanding @ovar macro inline (explanation in macro def comments)
16085 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16086 @end smallexample
16089 @noindent
16090 @var{name} is the uncrunched file name, derived from the name of the unit
16091 in the standard manner described in the previous section (i.e., in particular
16092 all dots are replaced by hyphens). The file name may or may not have an
16093 extension (defined as a suffix of the form period followed by arbitrary
16094 characters other than period). If an extension is present then it will
16095 be preserved in the output. For example, when krunching @file{hellofile.ads}
16096 to eight characters, the result will be hellofil.ads.
16098 Note: for compatibility with previous versions of @code{gnatkr} dots may
16099 appear in the name instead of hyphens, but the last dot will always be
16100 taken as the start of an extension. So if @code{gnatkr} is given an argument
16101 such as @file{Hello.World.adb} it will be treated exactly as if the first
16102 period had been a hyphen, and for example krunching to eight characters
16103 gives the result @file{hellworl.adb}.
16105 Note that the result is always all lower case (except on OpenVMS where it is
16106 all upper case). Characters of the other case are folded as required.
16108 @var{length} represents the length of the krunched name. The default
16109 when no argument is given is 8 characters. A length of zero stands for
16110 unlimited, in other words do not chop except for system files where the
16111 implied crunching length is always eight characters.
16113 @noindent
16114 The output is the krunched name. The output has an extension only if the
16115 original argument was a file name with an extension.
16117 @node Krunching Method
16118 @section Krunching Method
16120 @noindent
16121 The initial file name is determined by the name of the unit that the file
16122 contains. The name is formed by taking the full expanded name of the
16123 unit and replacing the separating dots with hyphens and
16124 using lowercase
16125 for all letters, except that a hyphen in the second character position is
16126 replaced by a tilde if the first character is
16127 @samp{a}, @samp{i}, @samp{g}, or @samp{s}.
16128 The extension is @code{.ads} for a
16129 spec and @code{.adb} for a body.
16130 Krunching does not affect the extension, but the file name is shortened to
16131 the specified length by following these rules:
16133 @itemize @bullet
16134 @item
16135 The name is divided into segments separated by hyphens, tildes or
16136 underscores and all hyphens, tildes, and underscores are
16137 eliminated. If this leaves the name short enough, we are done.
16139 @item
16140 If the name is too long, the longest segment is located (left-most
16141 if there are two of equal length), and shortened by dropping
16142 its last character. This is repeated until the name is short enough.
16144 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16145 to fit the name into 8 characters as required by some operating systems.
16147 @smallexample
16148 our-strings-wide_fixed 22
16149 our strings wide fixed 19
16150 our string  wide fixed 18
16151 our strin   wide fixed 17
16152 our stri    wide fixed 16
16153 our stri    wide fixe  15
16154 our str     wide fixe  14
16155 our str     wid  fixe  13
16156 our str     wid  fix   12
16157 ou  str     wid  fix   11
16158 ou  st      wid  fix   10
16159 ou  st      wi   fix   9
16160 ou  st      wi   fi    8
16161 Final file name: oustwifi.adb
16162 @end smallexample
16164 @item
16165 The file names for all predefined units are always krunched to eight
16166 characters. The krunching of these predefined units uses the following
16167 special prefix replacements:
16169 @table @file
16170 @item ada-
16171 replaced by @file{a-}
16173 @item gnat-
16174 replaced by @file{g-}
16176 @item interfaces-
16177 replaced by @file{i-}
16179 @item system-
16180 replaced by @file{s-}
16181 @end table
16183 These system files have a hyphen in the second character position. That
16184 is why normal user files replace such a character with a
16185 tilde, to
16186 avoid confusion with system file names.
16188 As an example of this special rule, consider
16189 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16191 @smallexample
16192 ada-strings-wide_fixed 22
16193 a-  strings wide fixed 18
16194 a-  string  wide fixed 17
16195 a-  strin   wide fixed 16
16196 a-  stri    wide fixed 15
16197 a-  stri    wide fixe  14
16198 a-  str     wide fixe  13
16199 a-  str     wid  fixe  12
16200 a-  str     wid  fix   11
16201 a-  st      wid  fix   10
16202 a-  st      wi   fix   9
16203 a-  st      wi   fi    8
16204 Final file name: a-stwifi.adb
16205 @end smallexample
16206 @end itemize
16208 Of course no file shortening algorithm can guarantee uniqueness over all
16209 possible unit names, and if file name krunching is used then it is your
16210 responsibility to ensure that no name clashes occur. The utility
16211 program @code{gnatkr} is supplied for conveniently determining the
16212 krunched name of a file.
16214 @node Examples of gnatkr Usage
16215 @section Examples of @code{gnatkr} Usage
16217 @smallexample
16218 @iftex
16219 @leftskip=0cm
16220 @end iftex
16221 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16222 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16223 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16224 $ gnatkr grandparent-parent-child     --> grparchi
16225 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16226 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16227 @end smallexample
16229 @node Preprocessing with gnatprep
16230 @chapter Preprocessing with @code{gnatprep}
16231 @findex gnatprep
16233 @noindent
16234 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16235 preprocessing.
16236 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16237 special GNAT features.
16238 For further discussion of conditional compilation in general, see
16239 @ref{Conditional Compilation}.
16241 @menu
16242 * Preprocessing Symbols::
16243 * Using gnatprep::
16244 * Switches for gnatprep::
16245 * Form of Definitions File::
16246 * Form of Input Text for gnatprep::
16247 @end menu
16249 @node Preprocessing Symbols
16250 @section Preprocessing Symbols
16252 @noindent
16253 Preprocessing symbols are defined in definition files and referred to in
16254 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16255 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16256 all characters need to be in the ASCII set (no accented letters).
16258 @node Using gnatprep
16259 @section Using @code{gnatprep}
16261 @noindent
16262 To call @code{gnatprep} use
16264 @smallexample
16265 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16266 @c Expanding @ovar macro inline (explanation in macro def comments)
16267 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16268 @end smallexample
16270 @noindent
16271 where
16272 @table @var
16273 @item switches
16274 is an optional sequence of switches as described in the next section.
16276 @item infile
16277 is the full name of the input file, which is an Ada source
16278 file containing preprocessor directives.
16280 @item outfile
16281 is the full name of the output file, which is an Ada source
16282 in standard Ada form. When used with GNAT, this file name will
16283 normally have an ads or adb suffix.
16285 @item deffile
16286 is the full name of a text file containing definitions of
16287 preprocessing symbols to be referenced by the preprocessor. This argument is
16288 optional, and can be replaced by the use of the @option{-D} switch.
16290 @end table
16292 @node Switches for gnatprep
16293 @section Switches for @code{gnatprep}
16295 @table @option
16296 @c !sort!
16298 @item -b
16299 @cindex @option{-b} (@command{gnatprep})
16300 Causes both preprocessor lines and the lines deleted by
16301 preprocessing to be replaced by blank lines in the output source file,
16302 preserving line numbers in the output file.
16304 @item -c
16305 @cindex @option{-c} (@command{gnatprep})
16306 Causes both preprocessor lines and the lines deleted
16307 by preprocessing to be retained in the output source as comments marked
16308 with the special string @code{"--! "}. This option will result in line numbers
16309 being preserved in the output file.
16311 @item -C
16312 @cindex @option{-C} (@command{gnatprep})
16313 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16314 If this option is specified, then comments are scanned and any $symbol
16315 substitutions performed as in program text. This is particularly useful
16316 when structured comments are used (e.g., when writing programs in the
16317 SPARK dialect of Ada). Note that this switch is not available when
16318 doing integrated preprocessing (it would be useless in this context
16319 since comments are ignored by the compiler in any case).
16321 @item -Dsymbol=value
16322 @cindex @option{-D} (@command{gnatprep})
16323 Defines a new preprocessing symbol, associated with value. If no value is given
16324 on the command line, then symbol is considered to be @code{True}. This switch
16325 can be used in place of a definition file.
16328 @item -r
16329 @cindex @option{-r} (@command{gnatprep})
16330 Causes a @code{Source_Reference} pragma to be generated that
16331 references the original input file, so that error messages will use
16332 the file name of this original file. The use of this switch implies
16333 that preprocessor lines are not to be removed from the file, so its
16334 use will force @option{-b} mode if
16335 @option{-c}
16336 has not been specified explicitly.
16338 Note that if the file to be preprocessed contains multiple units, then
16339 it will be necessary to @code{gnatchop} the output file from
16340 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16341 in the preprocessed file, it will be respected by
16342 @code{gnatchop -r}
16343 so that the final chopped files will correctly refer to the original
16344 input source file for @code{gnatprep}.
16346 @item -s
16347 @cindex @option{-s} (@command{gnatprep})
16348 Causes a sorted list of symbol names and values to be
16349 listed on the standard output file.
16351 @item -u
16352 @cindex @option{-u} (@command{gnatprep})
16353 Causes undefined symbols to be treated as having the value FALSE in the context
16354 of a preprocessor test. In the absence of this option, an undefined symbol in
16355 a @code{#if} or @code{#elsif} test will be treated as an error.
16357 @end table
16359 @noindent
16360 Note: if neither @option{-b} nor @option{-c} is present,
16361 then preprocessor lines and
16362 deleted lines are completely removed from the output, unless -r is
16363 specified, in which case -b is assumed.
16365 @node Form of Definitions File
16366 @section Form of Definitions File
16368 @noindent
16369 The definitions file contains lines of the form
16371 @smallexample
16372 symbol := value
16373 @end smallexample
16375 @noindent
16376 where symbol is a preprocessing symbol, and value is one of the following:
16378 @itemize @bullet
16379 @item
16380 Empty, corresponding to a null substitution
16381 @item
16382 A string literal using normal Ada syntax
16383 @item
16384 Any sequence of characters from the set
16385 (letters, digits, period, underline).
16386 @end itemize
16388 @noindent
16389 Comment lines may also appear in the definitions file, starting with
16390 the usual @code{--},
16391 and comments may be added to the definitions lines.
16393 @node Form of Input Text for gnatprep
16394 @section Form of Input Text for @code{gnatprep}
16396 @noindent
16397 The input text may contain preprocessor conditional inclusion lines,
16398 as well as general symbol substitution sequences.
16400 The preprocessor conditional inclusion commands have the form
16402 @smallexample
16403 @group
16404 @cartouche
16405 #if @i{expression} @r{[}then@r{]}
16406    lines
16407 #elsif @i{expression} @r{[}then@r{]}
16408    lines
16409 #elsif @i{expression} @r{[}then@r{]}
16410    lines
16411 @dots{}
16412 #else
16413    lines
16414 #end if;
16415 @end cartouche
16416 @end group
16417 @end smallexample
16419 @noindent
16420 In this example, @i{expression} is defined by the following grammar:
16421 @smallexample
16422 @i{expression} ::=  <symbol>
16423 @i{expression} ::=  <symbol> = "<value>"
16424 @i{expression} ::=  <symbol> = <symbol>
16425 @i{expression} ::=  <symbol> = <integer>
16426 @i{expression} ::=  <symbol> > <integer>
16427 @i{expression} ::=  <symbol> >= <integer>
16428 @i{expression} ::=  <symbol> < <integer>
16429 @i{expression} ::=  <symbol> <= <integer>
16430 @i{expression} ::=  <symbol> 'Defined
16431 @i{expression} ::=  not @i{expression}
16432 @i{expression} ::=  @i{expression} and @i{expression}
16433 @i{expression} ::=  @i{expression} or @i{expression}
16434 @i{expression} ::=  @i{expression} and then @i{expression}
16435 @i{expression} ::=  @i{expression} or else @i{expression}
16436 @i{expression} ::=  ( @i{expression} )
16437 @end smallexample
16439 The following restriction exists: it is not allowed to have "and" or "or"
16440 following "not" in the same expression without parentheses. For example, this
16441 is not allowed:
16443 @smallexample
16444    not X or Y
16445 @end smallexample
16447 This should be one of the following:
16449 @smallexample
16450    (not X) or Y
16451    not (X or Y)
16452 @end smallexample
16454 @noindent
16455 For the first test (@i{expression} ::= <symbol>) the symbol must have
16456 either the value true or false, that is to say the right-hand of the
16457 symbol definition must be one of the (case-insensitive) literals
16458 @code{True} or @code{False}. If the value is true, then the
16459 corresponding lines are included, and if the value is false, they are
16460 excluded.
16462 When comparing a symbol to an integer, the integer is any non negative
16463 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
16464 2#11#. The symbol value must also be a non negative integer. Integer values
16465 in the range 0 .. 2**31-1 are supported.
16467 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16468 the symbol has been defined in the definition file or by a @option{-D}
16469 switch on the command line. Otherwise, the test is false.
16471 The equality tests are case insensitive, as are all the preprocessor lines.
16473 If the symbol referenced is not defined in the symbol definitions file,
16474 then the effect depends on whether or not switch @option{-u}
16475 is specified. If so, then the symbol is treated as if it had the value
16476 false and the test fails. If this switch is not specified, then
16477 it is an error to reference an undefined symbol. It is also an error to
16478 reference a symbol that is defined with a value other than @code{True}
16479 or @code{False}.
16481 The use of the @code{not} operator inverts the sense of this logical test.
16482 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16483 operators, without parentheses. For example, "if not X or Y then" is not
16484 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16486 The @code{then} keyword is optional as shown
16488 The @code{#} must be the first non-blank character on a line, but
16489 otherwise the format is free form. Spaces or tabs may appear between
16490 the @code{#} and the keyword. The keywords and the symbols are case
16491 insensitive as in normal Ada code. Comments may be used on a
16492 preprocessor line, but other than that, no other tokens may appear on a
16493 preprocessor line. Any number of @code{elsif} clauses can be present,
16494 including none at all. The @code{else} is optional, as in Ada.
16496 The @code{#} marking the start of a preprocessor line must be the first
16497 non-blank character on the line, i.e., it must be preceded only by
16498 spaces or horizontal tabs.
16500 Symbol substitution outside of preprocessor lines is obtained by using
16501 the sequence
16503 @smallexample
16504 $symbol
16505 @end smallexample
16507 @noindent
16508 anywhere within a source line, except in a comment or within a
16509 string literal. The identifier
16510 following the @code{$} must match one of the symbols defined in the symbol
16511 definition file, and the result is to substitute the value of the
16512 symbol in place of @code{$symbol} in the output file.
16514 Note that although the substitution of strings within a string literal
16515 is not possible, it is possible to have a symbol whose defined value is
16516 a string literal. So instead of setting XYZ to @code{hello} and writing:
16518 @smallexample
16519 Header : String := "$XYZ";
16520 @end smallexample
16522 @noindent
16523 you should set XYZ to @code{"hello"} and write:
16525 @smallexample
16526 Header : String := $XYZ;
16527 @end smallexample
16529 @noindent
16530 and then the substitution will occur as desired.
16532 @node The GNAT Library Browser gnatls
16533 @chapter The GNAT Library Browser @code{gnatls}
16534 @findex gnatls
16535 @cindex Library browser
16537 @noindent
16538 @code{gnatls} is a tool that outputs information about compiled
16539 units. It gives the relationship between objects, unit names and source
16540 files. It can also be used to check the source dependencies of a unit
16541 as well as various characteristics.
16543 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16544 driver (see @ref{The GNAT Driver and Project Files}).
16546 @menu
16547 * Running gnatls::
16548 * Switches for gnatls::
16549 * Examples of gnatls Usage::
16550 @end menu
16552 @node Running gnatls
16553 @section Running @code{gnatls}
16555 @noindent
16556 The @code{gnatls} command has the form
16558 @smallexample
16559 $ gnatls switches @var{object_or_ali_file}
16560 @end smallexample
16562 @noindent
16563 The main argument is the list of object or @file{ali} files
16564 (@pxref{The Ada Library Information Files})
16565 for which information is requested.
16567 In normal mode, without additional option, @code{gnatls} produces a
16568 four-column listing. Each line represents information for a specific
16569 object. The first column gives the full path of the object, the second
16570 column gives the name of the principal unit in this object, the third
16571 column gives the status of the source and the fourth column gives the
16572 full path of the source representing this unit.
16573 Here is a simple example of use:
16575 @smallexample
16576 $ gnatls *.o
16577 ./demo1.o            demo1            DIF demo1.adb
16578 ./demo2.o            demo2             OK demo2.adb
16579 ./hello.o            h1                OK hello.adb
16580 ./instr-child.o      instr.child      MOK instr-child.adb
16581 ./instr.o            instr             OK instr.adb
16582 ./tef.o              tef              DIF tef.adb
16583 ./text_io_example.o  text_io_example   OK text_io_example.adb
16584 ./tgef.o             tgef             DIF tgef.adb
16585 @end smallexample
16587 @noindent
16588 The first line can be interpreted as follows: the main unit which is
16589 contained in
16590 object file @file{demo1.o} is demo1, whose main source is in
16591 @file{demo1.adb}. Furthermore, the version of the source used for the
16592 compilation of demo1 has been modified (DIF). Each source file has a status
16593 qualifier which can be:
16595 @table @code
16596 @item OK (unchanged)
16597 The version of the source file used for the compilation of the
16598 specified unit corresponds exactly to the actual source file.
16600 @item MOK (slightly modified)
16601 The version of the source file used for the compilation of the
16602 specified unit differs from the actual source file but not enough to
16603 require recompilation. If you use gnatmake with the qualifier
16604 @option{-m (minimal recompilation)}, a file marked
16605 MOK will not be recompiled.
16607 @item DIF (modified)
16608 No version of the source found on the path corresponds to the source
16609 used to build this object.
16611 @item ??? (file not found)
16612 No source file was found for this unit.
16614 @item HID (hidden,  unchanged version not first on PATH)
16615 The version of the source that corresponds exactly to the source used
16616 for compilation has been found on the path but it is hidden by another
16617 version of the same source that has been modified.
16619 @end table
16621 @node Switches for gnatls
16622 @section Switches for @code{gnatls}
16624 @noindent
16625 @code{gnatls} recognizes the following switches:
16627 @table @option
16628 @c !sort!
16629 @cindex @option{--version} @command{gnatls}
16630 Display Copyright and version, then exit disregarding all other options.
16632 @item --help
16633 @cindex @option{--help} @command{gnatls}
16634 If @option{--version} was not used, display usage, then exit disregarding
16635 all other options.
16637 @item -a
16638 @cindex @option{-a} (@code{gnatls})
16639 Consider all units, including those of the predefined Ada library.
16640 Especially useful with @option{-d}.
16642 @item -d
16643 @cindex @option{-d} (@code{gnatls})
16644 List sources from which specified units depend on.
16646 @item -h
16647 @cindex @option{-h} (@code{gnatls})
16648 Output the list of options.
16650 @item -o
16651 @cindex @option{-o} (@code{gnatls})
16652 Only output information about object files.
16654 @item -s
16655 @cindex @option{-s} (@code{gnatls})
16656 Only output information about source files.
16658 @item -u
16659 @cindex @option{-u} (@code{gnatls})
16660 Only output information about compilation units.
16662 @item -files=@var{file}
16663 @cindex @option{-files} (@code{gnatls})
16664 Take as arguments the files listed in text file @var{file}.
16665 Text file @var{file} may contain empty lines that are ignored.
16666 Each nonempty line should contain the name of an existing file.
16667 Several such switches may be specified simultaneously.
16669 @item -aO@var{dir}
16670 @itemx -aI@var{dir}
16671 @itemx -I@var{dir}
16672 @itemx  -I-
16673 @itemx -nostdinc
16674 @cindex @option{-aO} (@code{gnatls})
16675 @cindex @option{-aI} (@code{gnatls})
16676 @cindex @option{-I} (@code{gnatls})
16677 @cindex @option{-I-} (@code{gnatls})
16678 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16679 flags (@pxref{Switches for gnatmake}).
16681 @item -aP@var{dir}
16682 @cindex @option{-aP} (@code{gnatls})
16683 Add @var{dir} at the beginning of the project search dir.
16685 @item --RTS=@var{rts-path}
16686 @cindex @option{--RTS} (@code{gnatls})
16687 Specifies the default location of the runtime library. Same meaning as the
16688 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16690 @item -v
16691 @cindex @option{-v} (@code{gnatls})
16692 Verbose mode. Output the complete source, object and project paths. Do not use
16693 the default column layout but instead use long format giving as much as
16694 information possible on each requested units, including special
16695 characteristics such as:
16697 @table @code
16698 @item  Preelaborable
16699 The unit is preelaborable in the Ada sense.
16701 @item No_Elab_Code
16702 No elaboration code has been produced by the compiler for this unit.
16704 @item Pure
16705 The unit is pure in the Ada sense.
16707 @item Elaborate_Body
16708 The unit contains a pragma Elaborate_Body.
16710 @item Remote_Types
16711 The unit contains a pragma Remote_Types.
16713 @item Shared_Passive
16714 The unit contains a pragma Shared_Passive.
16716 @item Predefined
16717 This unit is part of the predefined environment and cannot be modified
16718 by the user.
16720 @item Remote_Call_Interface
16721 The unit contains a pragma Remote_Call_Interface.
16723 @end table
16725 @end table
16727 @node Examples of gnatls Usage
16728 @section Example of @code{gnatls} Usage
16730 @noindent
16731 Example of using the verbose switch. Note how the source and
16732 object paths are affected by the -I switch.
16734 @smallexample
16735 $ gnatls -v -I.. demo1.o
16737 GNATLS 5.03w (20041123-34)
16738 Copyright 1997-2004 Free Software Foundation, Inc.
16740 Source Search Path:
16741    <Current_Directory>
16742    ../
16743    /home/comar/local/adainclude/
16745 Object Search Path:
16746    <Current_Directory>
16747    ../
16748    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16750 Project Search Path:
16751    <Current_Directory>
16752    /home/comar/local/lib/gnat/
16754 ./demo1.o
16755    Unit =>
16756      Name   => demo1
16757      Kind   => subprogram body
16758      Flags  => No_Elab_Code
16759      Source => demo1.adb    modified
16760 @end smallexample
16762 @noindent
16763 The following is an example of use of the dependency list.
16764 Note the use of the -s switch
16765 which gives a straight list of source files. This can be useful for
16766 building specialized scripts.
16768 @smallexample
16769 $ gnatls -d demo2.o
16770 ./demo2.o   demo2        OK demo2.adb
16771                          OK gen_list.ads
16772                          OK gen_list.adb
16773                          OK instr.ads
16774                          OK instr-child.ads
16776 $ gnatls -d -s -a demo1.o
16777 demo1.adb
16778 /home/comar/local/adainclude/ada.ads
16779 /home/comar/local/adainclude/a-finali.ads
16780 /home/comar/local/adainclude/a-filico.ads
16781 /home/comar/local/adainclude/a-stream.ads
16782 /home/comar/local/adainclude/a-tags.ads
16783 gen_list.ads
16784 gen_list.adb
16785 /home/comar/local/adainclude/gnat.ads
16786 /home/comar/local/adainclude/g-io.ads
16787 instr.ads
16788 /home/comar/local/adainclude/system.ads
16789 /home/comar/local/adainclude/s-exctab.ads
16790 /home/comar/local/adainclude/s-finimp.ads
16791 /home/comar/local/adainclude/s-finroo.ads
16792 /home/comar/local/adainclude/s-secsta.ads
16793 /home/comar/local/adainclude/s-stalib.ads
16794 /home/comar/local/adainclude/s-stoele.ads
16795 /home/comar/local/adainclude/s-stratt.ads
16796 /home/comar/local/adainclude/s-tasoli.ads
16797 /home/comar/local/adainclude/s-unstyp.ads
16798 /home/comar/local/adainclude/unchconv.ads
16799 @end smallexample
16802 @node Cleaning Up with gnatclean
16803 @chapter Cleaning Up with @code{gnatclean}
16804 @findex gnatclean
16805 @cindex Cleaning tool
16807 @noindent
16808 @code{gnatclean} is a tool that allows the deletion of files produced by the
16809 compiler, binder and linker, including ALI files, object files, tree files,
16810 expanded source files, library files, interface copy source files, binder
16811 generated files and executable files.
16813 @menu
16814 * Running gnatclean::
16815 * Switches for gnatclean::
16816 @c * Examples of gnatclean Usage::
16817 @end menu
16819 @node Running gnatclean
16820 @section Running @code{gnatclean}
16822 @noindent
16823 The @code{gnatclean} command has the form:
16825 @smallexample
16826 $ gnatclean switches @var{names}
16827 @end smallexample
16829 @noindent
16830 @var{names} is a list of source file names. Suffixes @code{.ads} and
16831 @code{adb} may be omitted. If a project file is specified using switch
16832 @code{-P}, then @var{names} may be completely omitted.
16834 @noindent
16835 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16836 if switch @code{-c} is not specified, by the binder and
16837 the linker. In informative-only mode, specified by switch
16838 @code{-n}, the list of files that would have been deleted in
16839 normal mode is listed, but no file is actually deleted.
16841 @node Switches for gnatclean
16842 @section Switches for @code{gnatclean}
16844 @noindent
16845 @code{gnatclean} recognizes the following switches:
16847 @table @option
16848 @c !sort!
16849 @cindex @option{--version} @command{gnatclean}
16850 Display Copyright and version, then exit disregarding all other options.
16852 @item --help
16853 @cindex @option{--help} @command{gnatclean}
16854 If @option{--version} was not used, display usage, then exit disregarding
16855 all other options.
16857 @item --subdirs=subdir
16858 Actual object directory of each project file is the subdirectory subdir of the
16859 object directory specified or defaulted in the project file.
16861 @item --unchecked-shared-lib-imports
16862 By default, shared library projects are not allowed to import static library
16863 projects. When this switch is used on the command line, this restriction is
16864 relaxed.
16866 @item -c
16867 @cindex @option{-c} (@code{gnatclean})
16868 Only attempt to delete the files produced by the compiler, not those produced
16869 by the binder or the linker. The files that are not to be deleted are library
16870 files, interface copy files, binder generated files and executable files.
16872 @item -D @var{dir}
16873 @cindex @option{-D} (@code{gnatclean})
16874 Indicate that ALI and object files should normally be found in directory
16875 @var{dir}.
16877 @item -F
16878 @cindex @option{-F} (@code{gnatclean})
16879 When using project files, if some errors or warnings are detected during
16880 parsing and verbose mode is not in effect (no use of switch
16881 -v), then error lines start with the full path name of the project
16882 file, rather than its simple file name.
16884 @item -h
16885 @cindex @option{-h} (@code{gnatclean})
16886 Output a message explaining the usage of @code{gnatclean}.
16888 @item -n
16889 @cindex @option{-n} (@code{gnatclean})
16890 Informative-only mode. Do not delete any files. Output the list of the files
16891 that would have been deleted if this switch was not specified.
16893 @item -P@var{project}
16894 @cindex @option{-P} (@code{gnatclean})
16895 Use project file @var{project}. Only one such switch can be used.
16896 When cleaning a project file, the files produced by the compilation of the
16897 immediate sources or inherited sources of the project files are to be
16898 deleted. This is not depending on the presence or not of executable names
16899 on the command line.
16901 @item -q
16902 @cindex @option{-q} (@code{gnatclean})
16903 Quiet output. If there are no errors, do not output anything, except in
16904 verbose mode (switch -v) or in informative-only mode
16905 (switch -n).
16907 @item -r
16908 @cindex @option{-r} (@code{gnatclean})
16909 When a project file is specified (using switch -P),
16910 clean all imported and extended project files, recursively. If this switch
16911 is not specified, only the files related to the main project file are to be
16912 deleted. This switch has no effect if no project file is specified.
16914 @item -v
16915 @cindex @option{-v} (@code{gnatclean})
16916 Verbose mode.
16918 @item -vP@emph{x}
16919 @cindex @option{-vP} (@code{gnatclean})
16920 Indicates the verbosity of the parsing of GNAT project files.
16921 @xref{Switches Related to Project Files}.
16923 @item -X@var{name=value}
16924 @cindex @option{-X} (@code{gnatclean})
16925 Indicates that external variable @var{name} has the value @var{value}.
16926 The Project Manager will use this value for occurrences of
16927 @code{external(name)} when parsing the project file.
16928 @xref{Switches Related to Project Files}.
16930 @item -aO@var{dir}
16931 @cindex @option{-aO} (@code{gnatclean})
16932 When searching for ALI and object files, look in directory
16933 @var{dir}.
16935 @item -I@var{dir}
16936 @cindex @option{-I} (@code{gnatclean})
16937 Equivalent to @option{-aO@var{dir}}.
16939 @item -I-
16940 @cindex @option{-I-} (@code{gnatclean})
16941 @cindex Source files, suppressing search
16942 Do not look for ALI or object files in the directory
16943 where @code{gnatclean} was invoked.
16945 @end table
16947 @c @node Examples of gnatclean Usage
16948 @c @section Examples of @code{gnatclean} Usage
16950 @node GNAT and Libraries
16951 @chapter GNAT and Libraries
16952 @cindex Library, building, installing, using
16954 @noindent
16955 This chapter describes how to build and use libraries with GNAT, and also shows
16956 how to recompile the GNAT run-time library. You should be familiar with the
16957 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16958 chapter.
16960 @menu
16961 * Introduction to Libraries in GNAT::
16962 * General Ada Libraries::
16963 * Stand-alone Ada Libraries::
16964 * Rebuilding the GNAT Run-Time Library::
16965 @end menu
16967 @node Introduction to Libraries in GNAT
16968 @section Introduction to Libraries in GNAT
16970 @noindent
16971 A library is, conceptually, a collection of objects which does not have its
16972 own main thread of execution, but rather provides certain services to the
16973 applications that use it. A library can be either statically linked with the
16974 application, in which case its code is directly included in the application,
16975 or, on platforms that support it, be dynamically linked, in which case
16976 its code is shared by all applications making use of this library.
16978 GNAT supports both types of libraries.
16979 In the static case, the compiled code can be provided in different ways. The
16980 simplest approach is to provide directly the set of objects resulting from
16981 compilation of the library source files. Alternatively, you can group the
16982 objects into an archive using whatever commands are provided by the operating
16983 system. For the latter case, the objects are grouped into a shared library.
16985 In the GNAT environment, a library has three types of components:
16986 @itemize @bullet
16987 @item
16988 Source files.
16989 @item
16990 @file{ALI} files.
16991 @xref{The Ada Library Information Files}.
16992 @item
16993 Object files, an archive or a shared library.
16994 @end itemize
16996 @noindent
16997 A GNAT library may expose all its source files, which is useful for
16998 documentation purposes. Alternatively, it may expose only the units needed by
16999 an external user to make use of the library. That is to say, the specs
17000 reflecting the library services along with all the units needed to compile
17001 those specs, which can include generic bodies or any body implementing an
17002 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17003 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17005 All compilation units comprising an application, including those in a library,
17006 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17007 computes the elaboration order from the @file{ALI} files and this is why they
17008 constitute a mandatory part of GNAT libraries.
17009 @emph{Stand-alone libraries} are the exception to this rule because a specific
17010 library elaboration routine is produced independently of the application(s)
17011 using the library.
17013 @node General Ada Libraries
17014 @section General Ada Libraries
17016 @menu
17017 * Building a library::
17018 * Installing a library::
17019 * Using a library::
17020 @end menu
17022 @node Building a library
17023 @subsection Building a library
17025 @noindent
17026 The easiest way to build a library is to use the Project Manager,
17027 which supports a special type of project called a @emph{Library Project}
17028 (@pxref{Library Projects}).
17030 A project is considered a library project, when two project-level attributes
17031 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17032 control different aspects of library configuration, additional optional
17033 project-level attributes can be specified:
17034 @table @code
17035 @item Library_Kind
17036 This attribute controls whether the library is to be static or dynamic
17038 @item Library_Version
17039 This attribute specifies the library version; this value is used
17040 during dynamic linking of shared libraries to determine if the currently
17041 installed versions of the binaries are compatible.
17043 @item Library_Options
17044 @item Library_GCC
17045 These attributes specify additional low-level options to be used during
17046 library generation, and redefine the actual application used to generate
17047 library.
17048 @end table
17050 @noindent
17051 The GNAT Project Manager takes full care of the library maintenance task,
17052 including recompilation of the source files for which objects do not exist
17053 or are not up to date, assembly of the library archive, and installation of
17054 the library (i.e., copying associated source, object and @file{ALI} files
17055 to the specified location).
17057 Here is a simple library project file:
17058 @smallexample @c ada
17059 project My_Lib @b{is}
17060    @b{for} Source_Dirs @b{use} ("src1", "src2");
17061    @b{for} Object_Dir @b{use} "obj";
17062    @b{for} Library_Name @b{use} "mylib";
17063    @b{for} Library_Dir @b{use} "lib";
17064    @b{for} Library_Kind @b{use} "dynamic";
17065 @b{end} My_lib;
17066 @end smallexample
17068 @noindent
17069 and the compilation command to build and install the library:
17071 @smallexample @c ada
17072   $ gnatmake -Pmy_lib
17073 @end smallexample
17075 @noindent
17076 It is not entirely trivial to perform manually all the steps required to
17077 produce a library. We recommend that you use the GNAT Project Manager
17078 for this task. In special cases where this is not desired, the necessary
17079 steps are discussed below.
17081 There are various possibilities for compiling the units that make up the
17082 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17083 with a conventional script. For simple libraries, it is also possible to create
17084 a dummy main program which depends upon all the packages that comprise the
17085 interface of the library. This dummy main program can then be given to
17086 @command{gnatmake}, which will ensure that all necessary objects are built.
17088 After this task is accomplished, you should follow the standard procedure
17089 of the underlying operating system to produce the static or shared library.
17091 Here is an example of such a dummy program:
17092 @smallexample @c ada
17093 @group
17094 @b{with} My_Lib.Service1;
17095 @b{with} My_Lib.Service2;
17096 @b{with} My_Lib.Service3;
17097 @b{procedure} My_Lib_Dummy @b{is}
17098 @b{begin}
17099    @b{null};
17100 @b{end};
17101 @end group
17102 @end smallexample
17104 @noindent
17105 Here are the generic commands that will build an archive or a shared library.
17107 @smallexample
17108 # compiling the library
17109 $ gnatmake -c my_lib_dummy.adb
17111 # we don't need the dummy object itself
17112 $ rm my_lib_dummy.o my_lib_dummy.ali
17114 # create an archive with the remaining objects
17115 $ ar rc libmy_lib.a *.o
17116 # some systems may require "ranlib" to be run as well
17118 # or create a shared library
17119 $ gcc -shared -o libmy_lib.so *.o
17120 # some systems may require the code to have been compiled with -fPIC
17122 # remove the object files that are now in the library
17123 $ rm *.o
17125 # Make the ALI files read-only so that gnatmake will not try to
17126 # regenerate the objects that are in the library
17127 $ chmod -w *.ali
17128 @end smallexample
17130 @noindent
17131 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17132 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17133 be accessed by the directive @option{-l@var{xxx}} at link time.
17135 @node Installing a library
17136 @subsection Installing a library
17137 @cindex @code{ADA_PROJECT_PATH}
17138 @cindex @code{GPR_PROJECT_PATH}
17140 @noindent
17141 If you use project files, library installation is part of the library build
17142 process (@pxref{Installing a library with project files}).
17144 When project files are not an option, it is also possible, but not recommended,
17145 to install the library so that the sources needed to use the library are on the
17146 Ada source path and the ALI files & libraries be on the Ada Object path (see
17147 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17148 administrator can place general-purpose libraries in the default compiler
17149 paths, by specifying the libraries' location in the configuration files
17150 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17151 must be located in the GNAT installation tree at the same place as the gcc spec
17152 file. The location of the gcc spec file can be determined as follows:
17153 @smallexample
17154 $ gcc -v
17155 @end smallexample
17157 @noindent
17158 The configuration files mentioned above have a simple format: each line
17159 must contain one unique directory name.
17160 Those names are added to the corresponding path
17161 in their order of appearance in the file. The names can be either absolute
17162 or relative; in the latter case, they are relative to where theses files
17163 are located.
17165 The files @file{ada_source_path} and @file{ada_object_path} might not be
17166 present in a
17167 GNAT installation, in which case, GNAT will look for its run-time library in
17168 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17169 objects and @file{ALI} files). When the files exist, the compiler does not
17170 look in @file{adainclude} and @file{adalib}, and thus the
17171 @file{ada_source_path} file
17172 must contain the location for the GNAT run-time sources (which can simply
17173 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17174 contain the location for the GNAT run-time objects (which can simply
17175 be @file{adalib}).
17177 You can also specify a new default path to the run-time library at compilation
17178 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17179 the run-time library you want your program to be compiled with. This switch is
17180 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17181 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17183 It is possible to install a library before or after the standard GNAT
17184 library, by reordering the lines in the configuration files. In general, a
17185 library must be installed before the GNAT library if it redefines
17186 any part of it.
17188 @node Using a library
17189 @subsection Using a library
17191 @noindent Once again, the project facility greatly simplifies the use of
17192 libraries. In this context, using a library is just a matter of adding a
17193 @code{with} clause in the user project. For instance, to make use of the
17194 library @code{My_Lib} shown in examples in earlier sections, you can
17195 write:
17197 @smallexample @c projectfile
17198 @b{with} "my_lib";
17199 @b{project} My_Proj @b{is}
17200   @dots{}
17201 @b{end} My_Proj;
17202 @end smallexample
17204 Even if you have a third-party, non-Ada library, you can still use GNAT's
17205 Project Manager facility to provide a wrapper for it. For example, the
17206 following project, when @code{with}ed by your main project, will link with the
17207 third-party library @file{liba.a}:
17209 @smallexample @c projectfile
17210 @group
17211 @b{project} Liba @b{is}
17212    @b{for} Externally_Built @b{use} "true";
17213    @b{for} Source_Files @b{use} ();
17214    @b{for} Library_Dir @b{use} "lib";
17215    @b{for} Library_Name @b{use} "a";
17216    @b{for} Library_Kind @b{use} "static";
17217 @b{end} Liba;
17218 @end group
17219 @end smallexample
17220 This is an alternative to the use of @code{pragma Linker_Options}. It is
17221 especially interesting in the context of systems with several interdependent
17222 static libraries where finding a proper linker order is not easy and best be
17223 left to the tools having visibility over project dependence information.
17225 @noindent
17226 In order to use an Ada library manually, you need to make sure that this
17227 library is on both your source and object path
17228 (see @ref{Search Paths and the Run-Time Library (RTL)}
17229 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17230 in an archive or a shared library, you need to specify the desired
17231 library at link time.
17233 For example, you can use the library @file{mylib} installed in
17234 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17236 @smallexample
17237 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17238   -largs -lmy_lib
17239 @end smallexample
17241 @noindent
17242 This can be expressed more simply:
17243 @smallexample
17244 $ gnatmake my_appl
17245 @end smallexample
17246 @noindent
17247 when the following conditions are met:
17248 @itemize @bullet
17249 @item
17250 @file{/dir/my_lib_src} has been added by the user to the environment
17251 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17252 @file{ada_source_path}
17253 @item
17254 @file{/dir/my_lib_obj} has been added by the user to the environment
17255 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17256 @file{ada_object_path}
17257 @item
17258 a pragma @code{Linker_Options} has been added to one of the sources.
17259 For example:
17261 @smallexample @c ada
17262 @b{pragma} Linker_Options ("-lmy_lib");
17263 @end smallexample
17264 @end itemize
17266 Note that you may also load a library dynamically at
17267 run time given its filename, as illustrated in the GNAT @file{plugins} example
17268 in the directory @file{share/examples/gnat/plugins} within the GNAT
17269 install area.
17271 @node Stand-alone Ada Libraries
17272 @section Stand-alone Ada Libraries
17273 @cindex Stand-alone library, building, using
17275 @menu
17276 * Introduction to Stand-alone Libraries::
17277 * Building a Stand-alone Library::
17278 * Creating a Stand-alone Library to be used in a non-Ada context::
17279 * Restrictions in Stand-alone Libraries::
17280 @end menu
17282 @node Introduction to Stand-alone Libraries
17283 @subsection Introduction to Stand-alone Libraries
17285 @noindent
17286 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17287 necessary code to
17288 elaborate the Ada units that are included in the library. In contrast with
17289 an ordinary library, which consists of all sources, objects and @file{ALI}
17290 files of the
17291 library, a SAL may specify a restricted subset of compilation units
17292 to serve as a library interface. In this case, the fully
17293 self-sufficient set of files will normally consist of an objects
17294 archive, the sources of interface units' specs, and the @file{ALI}
17295 files of interface units.
17296 If an interface spec contains a generic unit or an inlined subprogram,
17297 the body's
17298 source must also be provided; if the units that must be provided in the source
17299 form depend on other units, the source and @file{ALI} files of those must
17300 also be provided.
17302 The main purpose of a SAL is to minimize the recompilation overhead of client
17303 applications when a new version of the library is installed. Specifically,
17304 if the interface sources have not changed, client applications do not need to
17305 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17306 version, controlled by @code{Library_Version} attribute, is not changed,
17307 then the clients do not need to be relinked.
17309 SALs also allow the library providers to minimize the amount of library source
17310 text exposed to the clients.  Such ``information hiding'' might be useful or
17311 necessary for various reasons.
17313 Stand-alone libraries are also well suited to be used in an executable whose
17314 main routine is not written in Ada.
17316 @node Building a Stand-alone Library
17317 @subsection Building a Stand-alone Library
17319 @noindent
17320 GNAT's Project facility provides a simple way of building and installing
17321 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17322 To be a Stand-alone Library Project, in addition to the two attributes
17323 that make a project a Library Project (@code{Library_Name} and
17324 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17325 @code{Library_Interface} must be defined.  For example:
17327 @smallexample @c projectfile
17328 @group
17329    @b{for} Library_Dir @b{use} "lib_dir";
17330    @b{for} Library_Name @b{use} "dummy";
17331    @b{for} Library_Interface @b{use} ("int1", "int1.child");
17332 @end group
17333 @end smallexample
17335 @noindent
17336 Attribute @code{Library_Interface} has a non-empty string list value,
17337 each string in the list designating a unit contained in an immediate source
17338 of the project file.
17340 When a Stand-alone Library is built, first the binder is invoked to build
17341 a package whose name depends on the library name
17342 (@file{b~dummy.ads/b} in the example above).
17343 This binder-generated package includes initialization and
17344 finalization procedures whose
17345 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17346 in the example
17347 above). The object corresponding to this package is included in the library.
17349 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17350 calling of these procedures if a static SAL is built, or if a shared SAL
17351 is built
17352 with the project-level attribute @code{Library_Auto_Init} set to
17353 @code{"false"}.
17355 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17356 (those that are listed in attribute @code{Library_Interface}) are copied to
17357 the Library Directory. As a consequence, only the Interface Units may be
17358 imported from Ada units outside of the library. If other units are imported,
17359 the binding phase will fail.
17361 @noindent
17362 It is also possible to build an encapsulated library where not only
17363 the code to elaborate and finalize the library is embedded but also
17364 ensuring that the library is linked only against static
17365 libraries. So an encapsulated library only depends on system
17366 libraries, all other code, including the GNAT runtime, is embedded. To
17367 build an encapsulated library the attribute
17368 @code{Library_Standalone} must be set to @code{encapsulated}:
17370 @smallexample @c projectfile
17371 @group
17372    @b{for} Library_Dir @b{use} "lib_dir";
17373    @b{for} Library_Name @b{use} "dummy";
17374    @b{for} Library_Kind @b{use} "dynamic";
17375    @b{for} Library_Interface @b{use} ("int1", "int1.child");
17376    @b{for} Library_Standalone @b{use} "encapsulated";
17377 @end group
17378 @end smallexample
17380 @noindent
17381 The default value for this attribute is @code{standard} in which case
17382 a stand-alone library is built.
17384 The attribute @code{Library_Src_Dir} may be specified for a
17385 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17386 single string value. Its value must be the path (absolute or relative to the
17387 project directory) of an existing directory. This directory cannot be the
17388 object directory or one of the source directories, but it can be the same as
17389 the library directory. The sources of the Interface
17390 Units of the library that are needed by an Ada client of the library will be
17391 copied to the designated directory, called the Interface Copy directory.
17392 These sources include the specs of the Interface Units, but they may also
17393 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17394 are used, or when there is a generic unit in the spec. Before the sources
17395 are copied to the Interface Copy directory, an attempt is made to delete all
17396 files in the Interface Copy directory.
17398 Building stand-alone libraries by hand is somewhat tedious, but for those
17399 occasions when it is necessary here are the steps that you need to perform:
17400 @itemize @bullet
17401 @item
17402 Compile all library sources.
17404 @item
17405 Invoke the binder with the switch @option{-n} (No Ada main program),
17406 with all the @file{ALI} files of the interfaces, and
17407 with the switch @option{-L} to give specific names to the @code{init}
17408 and @code{final} procedures.  For example:
17409 @smallexample
17410   gnatbind -n int1.ali int2.ali -Lsal1
17411 @end smallexample
17413 @item
17414 Compile the binder generated file:
17415 @smallexample
17416   gcc -c b~int2.adb
17417 @end smallexample
17419 @item
17420 Link the dynamic library with all the necessary object files,
17421 indicating to the linker the names of the @code{init} (and possibly
17422 @code{final}) procedures for automatic initialization (and finalization).
17423 The built library should be placed in a directory different from
17424 the object directory.
17426 @item
17427 Copy the @code{ALI} files of the interface to the library directory,
17428 add in this copy an indication that it is an interface to a SAL
17429 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17430 with letter ``P'') and make the modified copy of the @file{ALI} file
17431 read-only.
17432 @end itemize
17434 @noindent
17435 Using SALs is not different from using other libraries
17436 (see @ref{Using a library}).
17438 @node Creating a Stand-alone Library to be used in a non-Ada context
17439 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17441 @noindent
17442 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17443 a non-Ada context.
17445 The only extra step required is to ensure that library interface subprograms
17446 are compatible with the main program, by means of @code{pragma Export}
17447 or @code{pragma Convention}.
17449 Here is an example of simple library interface for use with C main program:
17451 @smallexample @c ada
17452 @b{package} My_Package @b{is}
17454    @b{procedure} Do_Something;
17455    @b{pragma} Export (C, Do_Something, "do_something");
17457    @b{procedure} Do_Something_Else;
17458    @b{pragma} Export (C, Do_Something_Else, "do_something_else");
17460 @b{end} My_Package;
17461 @end smallexample
17463 @noindent
17464 On the foreign language side, you must provide a ``foreign'' view of the
17465 library interface; remember that it should contain elaboration routines in
17466 addition to interface subprograms.
17468 The example below shows the content of @code{mylib_interface.h} (note
17469 that there is no rule for the naming of this file, any name can be used)
17470 @smallexample
17471 /* the library elaboration procedure */
17472 extern void mylibinit (void);
17474 /* the library finalization procedure */
17475 extern void mylibfinal (void);
17477 /* the interface exported by the library */
17478 extern void do_something (void);
17479 extern void do_something_else (void);
17480 @end smallexample
17482 @noindent
17483 Libraries built as explained above can be used from any program, provided
17484 that the elaboration procedures (named @code{mylibinit} in the previous
17485 example) are called before the library services are used. Any number of
17486 libraries can be used simultaneously, as long as the elaboration
17487 procedure of each library is called.
17489 Below is an example of a C program that uses the @code{mylib} library.
17491 @smallexample
17492 #include "mylib_interface.h"
17495 main (void)
17497    /* First, elaborate the library before using it */
17498    mylibinit ();
17500    /* Main program, using the library exported entities */
17501    do_something ();
17502    do_something_else ();
17504    /* Library finalization at the end of the program */
17505    mylibfinal ();
17506    return 0;
17508 @end smallexample
17510 @noindent
17511 Note that invoking any library finalization procedure generated by
17512 @code{gnatbind} shuts down the Ada run-time environment.
17513 Consequently, the
17514 finalization of all Ada libraries must be performed at the end of the program.
17515 No call to these libraries or to the Ada run-time library should be made
17516 after the finalization phase.
17518 @node Restrictions in Stand-alone Libraries
17519 @subsection Restrictions in Stand-alone Libraries
17521 @noindent
17522 The pragmas listed below should be used with caution inside libraries,
17523 as they can create incompatibilities with other Ada libraries:
17524 @itemize @bullet
17525 @item pragma @code{Locking_Policy}
17526 @item pragma @code{Partition_Elaboration_Policy}
17527 @item pragma @code{Queuing_Policy}
17528 @item pragma @code{Task_Dispatching_Policy}
17529 @item pragma @code{Unreserve_All_Interrupts}
17530 @end itemize
17532 @noindent
17533 When using a library that contains such pragmas, the user must make sure
17534 that all libraries use the same pragmas with the same values. Otherwise,
17535 @code{Program_Error} will
17536 be raised during the elaboration of the conflicting
17537 libraries. The usage of these pragmas and its consequences for the user
17538 should therefore be well documented.
17540 Similarly, the traceback in the exception occurrence mechanism should be
17541 enabled or disabled in a consistent manner across all libraries.
17542 Otherwise, Program_Error will be raised during the elaboration of the
17543 conflicting libraries.
17545 If the @code{Version} or @code{Body_Version}
17546 attributes are used inside a library, then you need to
17547 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17548 libraries, so that version identifiers can be properly computed.
17549 In practice these attributes are rarely used, so this is unlikely
17550 to be a consideration.
17552 @node  Rebuilding the GNAT Run-Time Library
17553 @section Rebuilding the GNAT Run-Time Library
17554 @cindex GNAT Run-Time Library, rebuilding
17555 @cindex Building the GNAT Run-Time Library
17556 @cindex Rebuilding the GNAT Run-Time Library
17557 @cindex Run-Time Library, rebuilding
17559 @noindent
17560 It may be useful to recompile the GNAT library in various contexts, the
17561 most important one being the use of partition-wide configuration pragmas
17562 such as @code{Normalize_Scalars}. A special Makefile called
17563 @code{Makefile.adalib} is provided to that effect and can be found in
17564 the directory containing the GNAT library. The location of this
17565 directory depends on the way the GNAT environment has been installed and can
17566 be determined by means of the command:
17568 @smallexample
17569 $ gnatls -v
17570 @end smallexample
17572 @noindent
17573 The last entry in the object search path usually contains the
17574 gnat library. This Makefile contains its own documentation and in
17575 particular the set of instructions needed to rebuild a new library and
17576 to use it.
17578 @node Using the GNU make Utility
17579 @chapter Using the GNU @code{make} Utility
17580 @findex make
17582 @noindent
17583 This chapter offers some examples of makefiles that solve specific
17584 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
17585 make, make, GNU @code{make}}), nor does it try to replace the
17586 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
17588 All the examples in this section are specific to the GNU version of
17589 make. Although @command{make} is a standard utility, and the basic language
17590 is the same, these examples use some advanced features found only in
17591 @code{GNU make}.
17593 @menu
17594 * Using gnatmake in a Makefile::
17595 * Automatically Creating a List of Directories::
17596 * Generating the Command Line Switches::
17597 * Overcoming Command Line Length Limits::
17598 @end menu
17600 @node Using gnatmake in a Makefile
17601 @section Using gnatmake in a Makefile
17602 @findex makefile
17603 @cindex GNU make
17605 @noindent
17606 Complex project organizations can be handled in a very powerful way by
17607 using GNU make combined with gnatmake. For instance, here is a Makefile
17608 which allows you to build each subsystem of a big project into a separate
17609 shared library. Such a makefile allows you to significantly reduce the link
17610 time of very big applications while maintaining full coherence at
17611 each step of the build process.
17613 The list of dependencies are handled automatically by
17614 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17615 the appropriate directories.
17617 Note that you should also read the example on how to automatically
17618 create the list of directories
17619 (@pxref{Automatically Creating a List of Directories})
17620 which might help you in case your project has a lot of subdirectories.
17622 @smallexample
17623 @iftex
17624 @leftskip=0cm
17625 @font@heightrm=cmr8
17626 @heightrm
17627 @end iftex
17628 ## This Makefile is intended to be used with the following directory
17629 ## configuration:
17630 ##  - The sources are split into a series of csc (computer software components)
17631 ##    Each of these csc is put in its own directory.
17632 ##    Their name are referenced by the directory names.
17633 ##    They will be compiled into shared library (although this would also work
17634 ##    with static libraries
17635 ##  - The main program (and possibly other packages that do not belong to any
17636 ##    csc is put in the top level directory (where the Makefile is).
17637 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17638 ##                    \_ second_csc (sources) __ lib (will contain the library)
17639 ##                    \_ @dots{}
17640 ## Although this Makefile is build for shared library, it is easy to modify
17641 ## to build partial link objects instead (modify the lines with -shared and
17642 ## gnatlink below)
17644 ## With this makefile, you can change any file in the system or add any new
17645 ## file, and everything will be recompiled correctly (only the relevant shared
17646 ## objects will be recompiled, and the main program will be re-linked).
17648 # The list of computer software component for your project. This might be
17649 # generated automatically.
17650 CSC_LIST=aa bb cc
17652 # Name of the main program (no extension)
17653 MAIN=main
17655 # If we need to build objects with -fPIC, uncomment the following line
17656 #NEED_FPIC=-fPIC
17658 # The following variable should give the directory containing libgnat.so
17659 # You can get this directory through 'gnatls -v'. This is usually the last
17660 # directory in the Object_Path.
17661 GLIB=@dots{}
17663 # The directories for the libraries
17664 # (This macro expands the list of CSC to the list of shared libraries, you
17665 # could simply use the expanded form:
17666 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17667 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17669 $@{MAIN@}: objects $@{LIB_DIR@}
17670     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17671     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17673 objects::
17674     # recompile the sources
17675     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17677 # Note: In a future version of GNAT, the following commands will be simplified
17678 # by a new tool, gnatmlib
17679 $@{LIB_DIR@}:
17680     mkdir -p $@{dir $@@ @}
17681     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17682     cd $@{dir $@@ @} && cp -f ../*.ali .
17684 # The dependencies for the modules
17685 # Note that we have to force the expansion of *.o, since in some cases
17686 # make won't be able to do it itself.
17687 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17688 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17689 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17691 # Make sure all of the shared libraries are in the path before starting the
17692 # program
17693 run::
17694     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17696 clean::
17697     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17698     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17699     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17700     $@{RM@} *.o *.ali $@{MAIN@}
17701 @end smallexample
17703 @node Automatically Creating a List of Directories
17704 @section Automatically Creating a List of Directories
17706 @noindent
17707 In most makefiles, you will have to specify a list of directories, and
17708 store it in a variable. For small projects, it is often easier to
17709 specify each of them by hand, since you then have full control over what
17710 is the proper order for these directories, which ones should be
17711 included.
17713 However, in larger projects, which might involve hundreds of
17714 subdirectories, it might be more convenient to generate this list
17715 automatically.
17717 The example below presents two methods. The first one, although less
17718 general, gives you more control over the list. It involves wildcard
17719 characters, that are automatically expanded by @command{make}. Its
17720 shortcoming is that you need to explicitly specify some of the
17721 organization of your project, such as for instance the directory tree
17722 depth, whether some directories are found in a separate tree, @enddots{}
17724 The second method is the most general one. It requires an external
17725 program, called @command{find}, which is standard on all Unix systems. All
17726 the directories found under a given root directory will be added to the
17727 list.
17729 @smallexample
17730 @iftex
17731 @leftskip=0cm
17732 @font@heightrm=cmr8
17733 @heightrm
17734 @end iftex
17735 # The examples below are based on the following directory hierarchy:
17736 # All the directories can contain any number of files
17737 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17738 #                       ->  ab
17739 #                       ->  ac
17740 #                ->  b  ->  ba  ->  baa
17741 #                       ->  bb
17742 #                       ->  bc
17743 # This Makefile creates a variable called DIRS, that can be reused any time
17744 # you need this list (see the other examples in this section)
17746 # The root of your project's directory hierarchy
17747 ROOT_DIRECTORY=.
17749 ####
17750 # First method: specify explicitly the list of directories
17751 # This allows you to specify any subset of all the directories you need.
17752 ####
17754 DIRS := a/aa/ a/ab/ b/ba/
17756 ####
17757 # Second method: use wildcards
17758 # Note that the argument(s) to wildcard below should end with a '/'.
17759 # Since wildcards also return file names, we have to filter them out
17760 # to avoid duplicate directory names.
17761 # We thus use make's @code{dir} and @code{sort} functions.
17762 # It sets DIRs to the following value (note that the directories aaa and baa
17763 # are not given, unless you change the arguments to wildcard).
17764 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17765 ####
17767 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17768                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17770 ####
17771 # Third method: use an external program
17772 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17773 # This is the most complete command: it sets DIRs to the following value:
17774 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17775 ####
17777 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17779 @end smallexample
17781 @node Generating the Command Line Switches
17782 @section Generating the Command Line Switches
17784 @noindent
17785 Once you have created the list of directories as explained in the
17786 previous section (@pxref{Automatically Creating a List of Directories}),
17787 you can easily generate the command line arguments to pass to gnatmake.
17789 For the sake of completeness, this example assumes that the source path
17790 is not the same as the object path, and that you have two separate lists
17791 of directories.
17793 @smallexample
17794 # see "Automatically creating a list of directories" to create
17795 # these variables
17796 SOURCE_DIRS=
17797 OBJECT_DIRS=
17799 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17800 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17802 all:
17803         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17804 @end smallexample
17806 @node Overcoming Command Line Length Limits
17807 @section Overcoming Command Line Length Limits
17809 @noindent
17810 One problem that might be encountered on big projects is that many
17811 operating systems limit the length of the command line. It is thus hard to give
17812 gnatmake the list of source and object directories.
17814 This example shows how you can set up environment variables, which will
17815 make @command{gnatmake} behave exactly as if the directories had been
17816 specified on the command line, but have a much higher length limit (or
17817 even none on most systems).
17819 It assumes that you have created a list of directories in your Makefile,
17820 using one of the methods presented in
17821 @ref{Automatically Creating a List of Directories}.
17822 For the sake of completeness, we assume that the object
17823 path (where the ALI files are found) is different from the sources patch.
17825 Note a small trick in the Makefile below: for efficiency reasons, we
17826 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17827 expanded immediately by @code{make}. This way we overcome the standard
17828 make behavior which is to expand the variables only when they are
17829 actually used.
17831 On Windows, if you are using the standard Windows command shell, you must
17832 replace colons with semicolons in the assignments to these variables.
17834 @smallexample
17835 @iftex
17836 @leftskip=0cm
17837 @font@heightrm=cmr8
17838 @heightrm
17839 @end iftex
17840 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17841 # This is the same thing as putting the -I arguments on the command line.
17842 # (the equivalent of using -aI on the command line would be to define
17843 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17844 # You can of course have different values for these variables.
17846 # Note also that we need to keep the previous values of these variables, since
17847 # they might have been set before running 'make' to specify where the GNAT
17848 # library is installed.
17850 # see "Automatically creating a list of directories" to create these
17851 # variables
17852 SOURCE_DIRS=
17853 OBJECT_DIRS=
17855 empty:=
17856 space:=$@{empty@} $@{empty@}
17857 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17858 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17859 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17860 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17861 export ADA_INCLUDE_PATH
17862 export ADA_OBJECTS_PATH
17864 all:
17865         gnatmake main_unit
17866 @end smallexample
17868 @node Memory Management Issues
17869 @chapter Memory Management Issues
17871 @noindent
17872 This chapter describes some useful memory pools provided in the GNAT library
17873 and in particular the GNAT Debug Pool facility, which can be used to detect
17874 incorrect uses of access values (including ``dangling references'').
17875 @ifclear FSFEDITION
17876 It also describes the @command{gnatmem} tool, which can be used to track down
17877 ``memory leaks''.
17878 @end ifclear
17880 @menu
17881 * Some Useful Memory Pools::
17882 * The GNAT Debug Pool Facility::
17883 @ifclear FSFEDITION
17884 * The gnatmem Tool::
17885 @end ifclear
17886 @end menu
17888 @node Some Useful Memory Pools
17889 @section Some Useful Memory Pools
17890 @findex Memory Pool
17891 @cindex storage, pool
17893 @noindent
17894 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17895 storage pool. Allocations use the standard system call @code{malloc} while
17896 deallocations use the standard system call @code{free}. No reclamation is
17897 performed when the pool goes out of scope. For performance reasons, the
17898 standard default Ada allocators/deallocators do not use any explicit storage
17899 pools but if they did, they could use this storage pool without any change in
17900 behavior. That is why this storage pool is used  when the user
17901 manages to make the default implicit allocator explicit as in this example:
17902 @smallexample @c ada
17903    @b{type} T1 @b{is} @b{access} Something;
17904     --@i{ no Storage pool is defined for T2}
17905    @b{type} T2 @b{is} @b{access} Something_Else;
17906    @b{for} T2'Storage_Pool @b{use} T1'Storage_Pool;
17907    --@i{ the above is equivalent to}
17908    @b{for} T2'Storage_Pool @b{use} System.Pool_Global.Global_Pool_Object;
17909 @end smallexample
17911 @noindent
17912 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17913 pool. The allocation strategy is similar to @code{Pool_Local}'s
17914 except that the all
17915 storage allocated with this pool is reclaimed when the pool object goes out of
17916 scope. This pool provides a explicit mechanism similar to the implicit one
17917 provided by several Ada 83 compilers for allocations performed through a local
17918 access type and whose purpose was to reclaim memory when exiting the
17919 scope of a given local access. As an example, the following program does not
17920 leak memory even though it does not perform explicit deallocation:
17922 @smallexample @c ada
17923 @b{with} System.Pool_Local;
17924 @b{procedure} Pooloc1 @b{is}
17925    @b{procedure} Internal @b{is}
17926       @b{type} A @b{is} @b{access} Integer;
17927       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17928       @b{for} A'Storage_Pool @b{use} X;
17929       v : A;
17930    @b{begin}
17931       @b{for} I @b{in}  1 .. 50 @b{loop}
17932          v := @b{new} Integer;
17933       @b{end} @b{loop};
17934    @b{end} Internal;
17935 @b{begin}
17936    @b{for} I @b{in}  1 .. 100 @b{loop}
17937       Internal;
17938    @b{end} @b{loop};
17939 @b{end} Pooloc1;
17940 @end smallexample
17942 @noindent
17943 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17944 @code{Storage_Size} is specified for an access type.
17945 The whole storage for the pool is
17946 allocated at once, usually on the stack at the point where the access type is
17947 elaborated. It is automatically reclaimed when exiting the scope where the
17948 access type is defined. This package is not intended to be used directly by the
17949 user and it is implicitly used for each such declaration:
17951 @smallexample @c ada
17952    @b{type} T1 @b{is} @b{access} Something;
17953    @b{for} T1'Storage_Size @b{use} 10_000;
17954 @end smallexample
17956 @node The GNAT Debug Pool Facility
17957 @section The GNAT Debug Pool Facility
17958 @findex Debug Pool
17959 @cindex storage, pool, memory corruption
17961 @noindent
17962 The use of unchecked deallocation and unchecked conversion can easily
17963 lead to incorrect memory references. The problems generated by such
17964 references are usually difficult to tackle because the symptoms can be
17965 very remote from the origin of the problem. In such cases, it is
17966 very helpful to detect the problem as early as possible. This is the
17967 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17969 In order to use the GNAT specific debugging pool, the user must
17970 associate a debug pool object with each of the access types that may be
17971 related to suspected memory problems. See Ada Reference Manual 13.11.
17972 @smallexample @c ada
17973 @b{type} Ptr @b{is} @b{access} Some_Type;
17974 Pool : GNAT.Debug_Pools.Debug_Pool;
17975 @b{for} Ptr'Storage_Pool @b{use} Pool;
17976 @end smallexample
17978 @noindent
17979 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17980 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17981 allow the user to redefine allocation and deallocation strategies. They
17982 also provide a checkpoint for each dereference, through the use of
17983 the primitive operation @code{Dereference} which is implicitly called at
17984 each dereference of an access value.
17986 Once an access type has been associated with a debug pool, operations on
17987 values of the type may raise four distinct exceptions,
17988 which correspond to four potential kinds of memory corruption:
17989 @itemize @bullet
17990 @item
17991 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17992 @item
17993 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17994 @item
17995 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17996 @item
17997 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17998 @end itemize
18000 @noindent
18001 For types associated with a Debug_Pool, dynamic allocation is performed using
18002 the standard GNAT allocation routine. References to all allocated chunks of
18003 memory are kept in an internal dictionary. Several deallocation strategies are
18004 provided, whereupon the user can choose to release the memory to the system,
18005 keep it allocated for further invalid access checks, or fill it with an easily
18006 recognizable pattern for debug sessions. The memory pattern is the old IBM
18007 hexadecimal convention: @code{16#DEADBEEF#}.
18009 See the documentation in the file g-debpoo.ads for more information on the
18010 various strategies.
18012 Upon each dereference, a check is made that the access value denotes a
18013 properly allocated memory location. Here is a complete example of use of
18014 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18015 @smallexample @c ada
18016 @iftex
18017 @leftskip=0cm
18018 @end iftex
18019 @b{with} Gnat.Io; @b{use} Gnat.Io;
18020 @b{with} Unchecked_Deallocation;
18021 @b{with} Unchecked_Conversion;
18022 @b{with} GNAT.Debug_Pools;
18023 @b{with} System.Storage_Elements;
18024 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
18025 @b{procedure} Debug_Pool_Test @b{is}
18027    @b{type} T @b{is} @b{access} Integer;
18028    @b{type} U @b{is} @b{access} @b{all} T;
18030    P : GNAT.Debug_Pools.Debug_Pool;
18031    @b{for} T'Storage_Pool @b{use} P;
18033    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
18034    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
18035    A, B : @b{aliased} T;
18037    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
18039 @b{begin}
18040    Info (P);
18041    A := @b{new} Integer;
18042    B := @b{new} Integer;
18043    B := A;
18044    Info (P);
18045    Free (A);
18046    @b{begin}
18047       Put_Line (Integer'Image(B.@b{all}));
18048    @b{exception}
18049       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18050    @b{end};
18051    @b{begin}
18052       Free (B);
18053    @b{exception}
18054       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18055    @b{end};
18056    B := UC(A'Access);
18057    @b{begin}
18058       Put_Line (Integer'Image(B.@b{all}));
18059    @b{exception}
18060       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18061    @b{end};
18062    @b{begin}
18063       Free (B);
18064    @b{exception}
18065       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
18066    @b{end};
18067    Info (P);
18068 @b{end} Debug_Pool_Test;
18069 @end smallexample
18071 @noindent
18072 The debug pool mechanism provides the following precise diagnostics on the
18073 execution of this erroneous program:
18074 @smallexample
18075 Debug Pool info:
18076   Total allocated bytes :  0
18077   Total deallocated bytes :  0
18078   Current Water Mark:  0
18079   High Water Mark:  0
18081 Debug Pool info:
18082   Total allocated bytes :  8
18083   Total deallocated bytes :  0
18084   Current Water Mark:  8
18085   High Water Mark:  8
18087 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18088 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18089 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18090 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18091 Debug Pool info:
18092   Total allocated bytes :  8
18093   Total deallocated bytes :  4
18094   Current Water Mark:  4
18095   High Water Mark:  8
18096 @end smallexample
18098 @ifclear FSFEDITION
18099 @node The gnatmem Tool
18100 @section The @command{gnatmem} Tool
18101 @findex gnatmem
18103 @noindent
18104 The @code{gnatmem} utility monitors dynamic allocation and
18105 deallocation activity in a program, and displays information about
18106 incorrect deallocations and possible sources of memory leaks.
18107 It is designed to work in association with a static runtime library
18108 only and in this context provides three types of information:
18109 @itemize @bullet
18110 @item
18111 General information concerning memory management, such as the total
18112 number of allocations and deallocations, the amount of allocated
18113 memory and the high water mark, i.e.@: the largest amount of allocated
18114 memory in the course of program execution.
18116 @item
18117 Backtraces for all incorrect deallocations, that is to say deallocations
18118 which do not correspond to a valid allocation.
18120 @item
18121 Information on each allocation that is potentially the origin of a memory
18122 leak.
18123 @end itemize
18125 @menu
18126 * Running gnatmem::
18127 * Switches for gnatmem::
18128 * Example of gnatmem Usage::
18129 @end menu
18131 @node Running gnatmem
18132 @subsection Running @code{gnatmem}
18134 @noindent
18135 @code{gnatmem} makes use of the output created by the special version of
18136 allocation and deallocation routines that record call information. This allows
18137 it to obtain accurate dynamic memory usage history at a minimal cost to the
18138 execution speed. Note however, that @code{gnatmem} is not supported on all
18139 platforms (currently, it is supported on AIX, HP-UX, GNU/Linux, Solaris and
18140 Windows NT/2000/XP (x86).
18142 @noindent
18143 The @code{gnatmem} command has the form
18145 @smallexample
18146 @c    $ gnatmem @ovar{switches} user_program
18147 @c Expanding @ovar macro inline (explanation in macro def comments)
18148       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18149 @end smallexample
18151 @noindent
18152 The program must have been linked with the instrumented version of the
18153 allocation and deallocation routines. This is done by linking with the
18154 @file{libgmem.a} library. For correct symbolic backtrace information,
18155 the user program should be compiled with debugging options
18156 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18158 @smallexample
18159 $ gnatmake -g my_program -largs -lgmem
18160 @end smallexample
18162 @noindent
18163 As library @file{libgmem.a} contains an alternate body for package
18164 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18165 when an executable is linked with library @file{libgmem.a}. It is then not
18166 recommended to use @command{gnatmake} with switch @option{-a}.
18168 @noindent
18169 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18170 This file contains information about all allocations and deallocations
18171 performed by the program. It is produced by the instrumented allocations and
18172 deallocations routines and will be used by @code{gnatmem}.
18174 In order to produce symbolic backtrace information for allocations and
18175 deallocations performed by the GNAT run-time library, you need to use a
18176 version of that library that has been compiled with the @option{-g} switch
18177 (see @ref{Rebuilding the GNAT Run-Time Library}).
18179 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18180 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18181 @option{-i} switch, gnatmem will assume that this file can be found in the
18182 current directory. For example, after you have executed @file{my_program},
18183 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18185 @smallexample
18186 $ gnatmem my_program
18187 @end smallexample
18189 @noindent
18190 This will produce the output with the following format:
18192 *************** debut cc
18193 @smallexample
18194 $ gnatmem my_program
18196 Global information
18197 ------------------
18198    Total number of allocations        :  45
18199    Total number of deallocations      :   6
18200    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18201    High Water Mark                    :  11.40 Kilobytes
18206 Allocation Root # 2
18207 -------------------
18208  Number of non freed allocations    :  11
18209  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18210  High Water Mark                    :   1.27 Kilobytes
18211  Backtrace                          :
18212    my_program.adb:23 my_program.alloc
18216 @end smallexample
18218 The first block of output gives general information. In this case, the
18219 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18220 Unchecked_Deallocation routine occurred.
18222 @noindent
18223 Subsequent paragraphs display  information on all allocation roots.
18224 An allocation root is a specific point in the execution of the program
18225 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18226 construct. This root is represented by an execution backtrace (or subprogram
18227 call stack). By default the backtrace depth for allocations roots is 1, so
18228 that a root corresponds exactly to a source location. The backtrace can
18229 be made deeper, to make the root more specific.
18231 @node Switches for gnatmem
18232 @subsection Switches for @code{gnatmem}
18234 @noindent
18235 @code{gnatmem} recognizes the following switches:
18237 @table @option
18239 @item -q
18240 @cindex @option{-q} (@code{gnatmem})
18241 Quiet. Gives the minimum output needed to identify the origin of the
18242 memory leaks. Omits statistical information.
18244 @item @var{N}
18245 @cindex @var{N} (@code{gnatmem})
18246 N is an integer literal (usually between 1 and 10) which controls the
18247 depth of the backtraces defining allocation root. The default value for
18248 N is 1. The deeper the backtrace, the more precise the localization of
18249 the root. Note that the total number of roots can depend on this
18250 parameter. This parameter must be specified @emph{before} the name of the
18251 executable to be analyzed, to avoid ambiguity.
18253 @item -b n
18254 @cindex @option{-b} (@code{gnatmem})
18255 This switch has the same effect as just depth parameter.
18257 @item -i @var{file}
18258 @cindex @option{-i} (@code{gnatmem})
18259 Do the @code{gnatmem} processing starting from @file{file}, rather than
18260 @file{gmem.out} in the current directory.
18262 @item -m n
18263 @cindex @option{-m} (@code{gnatmem})
18264 This switch causes @code{gnatmem} to mask the allocation roots that have less
18265 than n leaks.  The default value is 1. Specifying the value of 0 will allow
18266 examination of even the roots that did not result in leaks.
18268 @item -s order
18269 @cindex @option{-s} (@code{gnatmem})
18270 This switch causes @code{gnatmem} to sort the allocation roots according to the
18271 specified order of sort criteria, each identified by a single letter. The
18272 currently supported criteria are @code{n, h, w} standing respectively for
18273 number of unfreed allocations, high watermark, and final watermark
18274 corresponding to a specific root. The default order is @code{nwh}.
18276 @item -t
18277 @cindex @option{-t} (@code{gnatmem})
18278 This switch causes memory allocated size to be always output in bytes.
18279 Default @code{gnatmem} behavior is to show memory sizes less then 1 kilobyte
18280 in bytes, from 1 kilobyte till 1 megabyte in kilobytes and the rest in
18281 megabytes.
18283 @end table
18285 @node Example of gnatmem Usage
18286 @subsection Example of @code{gnatmem} Usage
18288 @noindent
18289 The following example shows the use of @code{gnatmem}
18290 on a simple memory-leaking program.
18291 Suppose that we have the following Ada program:
18293 @smallexample @c ada
18294 @group
18295 @cartouche
18296 @b{with} Unchecked_Deallocation;
18297 @b{procedure} Test_Gm @b{is}
18299    @b{type} T @b{is} @b{array} (1..1000) @b{of} Integer;
18300    @b{type} Ptr @b{is} @b{access} T;
18301    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (T, Ptr);
18302    A : Ptr;
18304    @b{procedure} My_Alloc @b{is}
18305    @b{begin}
18306       A := @b{new} T;
18307    @b{end} My_Alloc;
18309    @b{procedure} My_DeAlloc @b{is}
18310       B : Ptr := A;
18311    @b{begin}
18312       Free (B);
18313    @b{end} My_DeAlloc;
18315 @b{begin}
18316    My_Alloc;
18317    @b{for} I @b{in} 1 .. 5 @b{loop}
18318       @b{for} J @b{in} I .. 5 @b{loop}
18319          My_Alloc;
18320       @b{end} @b{loop};
18321       My_Dealloc;
18322    @b{end} @b{loop};
18323 @b{end};
18324 @end cartouche
18325 @end group
18326 @end smallexample
18328 @noindent
18329 The program needs to be compiled with debugging option and linked with
18330 @code{gmem} library:
18332 @smallexample
18333 $ gnatmake -g test_gm -largs -lgmem
18334 @end smallexample
18336 @noindent
18337 Then we execute the program as usual:
18339 @smallexample
18340 $ test_gm
18341 @end smallexample
18343 @noindent
18344 Then @code{gnatmem} is invoked simply with
18345 @smallexample
18346 $ gnatmem test_gm
18347 @end smallexample
18349 @noindent
18350 which produces the following output (result may vary on different platforms):
18352 @smallexample
18353 Global information
18354 ------------------
18355    Total number of allocations        :  18
18356    Total number of deallocations      :   5
18357    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18358    High Water Mark                    :  56.90 Kilobytes
18360 Allocation Root # 1
18361 -------------------
18362  Number of non freed allocations    :  11
18363  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18364  High Water Mark                    :  46.88 Kilobytes
18365  Backtrace                          :
18366    test_gm.adb:11 test_gm.my_alloc
18368 Allocation Root # 2
18369 -------------------
18370  Number of non freed allocations    :   1
18371  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18372  High Water Mark                    :  10.02 Kilobytes
18373  Backtrace                          :
18374    s-secsta.adb:81 system.secondary_stack.ss_init
18376 Allocation Root # 3
18377 -------------------
18378  Number of non freed allocations    :   1
18379  Final Water Mark (non freed mem)   :  12 Bytes
18380  High Water Mark                    :  12 Bytes
18381  Backtrace                          :
18382    s-secsta.adb:181 system.secondary_stack.ss_init
18383 @end smallexample
18385 @noindent
18386 Note that the GNAT run time contains itself a certain number of
18387 allocations that have no  corresponding deallocation,
18388 as shown here for root #2 and root
18389 #3. This is a normal behavior when the number of non-freed allocations
18390 is one, it allocates dynamic data structures that the run time needs for
18391 the complete lifetime of the program. Note also that there is only one
18392 allocation root in the user program with a single line back trace:
18393 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18394 program shows that 'My_Alloc' is called at 2 different points in the
18395 source (line 21 and line 24). If those two allocation roots need to be
18396 distinguished, the backtrace depth parameter can be used:
18398 @smallexample
18399 $ gnatmem 3 test_gm
18400 @end smallexample
18402 @noindent
18403 which will give the following output:
18405 @smallexample
18406 Global information
18407 ------------------
18408    Total number of allocations        :  18
18409    Total number of deallocations      :   5
18410    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18411    High Water Mark                    :  56.90 Kilobytes
18413 Allocation Root # 1
18414 -------------------
18415  Number of non freed allocations    :  10
18416  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18417  High Water Mark                    :  42.97 Kilobytes
18418  Backtrace                          :
18419    test_gm.adb:11 test_gm.my_alloc
18420    test_gm.adb:24 test_gm
18421    b_test_gm.c:52 main
18423 Allocation Root # 2
18424 -------------------
18425  Number of non freed allocations    :   1
18426  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18427  High Water Mark                    :  10.02 Kilobytes
18428  Backtrace                          :
18429    s-secsta.adb:81  system.secondary_stack.ss_init
18430    s-secsta.adb:283 <system__secondary_stack___elabb>
18431    b_test_gm.c:33   adainit
18433 Allocation Root # 3
18434 -------------------
18435  Number of non freed allocations    :   1
18436  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18437  High Water Mark                    :   3.91 Kilobytes
18438  Backtrace                          :
18439    test_gm.adb:11 test_gm.my_alloc
18440    test_gm.adb:21 test_gm
18441    b_test_gm.c:52 main
18443 Allocation Root # 4
18444 -------------------
18445  Number of non freed allocations    :   1
18446  Final Water Mark (non freed mem)   :  12 Bytes
18447  High Water Mark                    :  12 Bytes
18448  Backtrace                          :
18449    s-secsta.adb:181 system.secondary_stack.ss_init
18450    s-secsta.adb:283 <system__secondary_stack___elabb>
18451    b_test_gm.c:33   adainit
18452 @end smallexample
18454 @noindent
18455 The allocation root #1 of the first example has been split in 2 roots #1
18456 and #3 thanks to the more precise associated backtrace.
18457 @end ifclear
18459 @node Stack Related Facilities
18460 @chapter Stack Related Facilities
18462 @noindent
18463 This chapter describes some useful tools associated with stack
18464 checking and analysis. In
18465 particular, it deals with dynamic and static stack usage measurements.
18467 @menu
18468 * Stack Overflow Checking::
18469 * Static Stack Usage Analysis::
18470 * Dynamic Stack Usage Analysis::
18471 @end menu
18473 @node Stack Overflow Checking
18474 @section Stack Overflow Checking
18475 @cindex Stack Overflow Checking
18476 @cindex -fstack-check
18478 @noindent
18479 For most operating systems, @command{gcc} does not perform stack overflow
18480 checking by default. This means that if the main environment task or
18481 some other task exceeds the available stack space, then unpredictable
18482 behavior will occur. Most native systems offer some level of protection by
18483 adding a guard page at the end of each task stack. This mechanism is usually
18484 not enough for dealing properly with stack overflow situations because
18485 a large local variable could ``jump'' above the guard page.
18486 Furthermore, when the
18487 guard page is hit, there may not be any space left on the stack for executing
18488 the exception propagation code. Enabling stack checking avoids
18489 such situations.
18491 To activate stack checking, compile all units with the gcc option
18492 @option{-fstack-check}. For example:
18494 @smallexample
18495 gcc -c -fstack-check package1.adb
18496 @end smallexample
18498 @noindent
18499 Units compiled with this option will generate extra instructions to check
18500 that any use of the stack (for procedure calls or for declaring local
18501 variables in declare blocks) does not exceed the available stack space.
18502 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18504 For declared tasks, the stack size is controlled by the size
18505 given in an applicable @code{Storage_Size} pragma or by the value specified
18506 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18507 the default size as defined in the GNAT runtime otherwise.
18509 For the environment task, the stack size depends on
18510 system defaults and is unknown to the compiler. Stack checking
18511 may still work correctly if a fixed
18512 size stack is allocated, but this cannot be guaranteed.
18513 To ensure that a clean exception is signalled for stack
18514 overflow, set the environment variable
18515 @env{GNAT_STACK_LIMIT} to indicate the maximum
18516 stack area that can be used, as in:
18517 @cindex GNAT_STACK_LIMIT
18519 @smallexample
18520 SET GNAT_STACK_LIMIT 1600
18521 @end smallexample
18523 @noindent
18524 The limit is given in kilobytes, so the above declaration would
18525 set the stack limit of the environment task to 1.6 megabytes.
18526 Note that the only purpose of this usage is to limit the amount
18527 of stack used by the environment task. If it is necessary to
18528 increase the amount of stack for the environment task, then this
18529 is an operating systems issue, and must be addressed with the
18530 appropriate operating systems commands.
18532 @node Static Stack Usage Analysis
18533 @section Static Stack Usage Analysis
18534 @cindex Static Stack Usage Analysis
18535 @cindex -fstack-usage
18537 @noindent
18538 A unit compiled with @option{-fstack-usage} will generate an extra file
18539 that specifies
18540 the maximum amount of stack used, on a per-function basis.
18541 The file has the same
18542 basename as the target object file with a @file{.su} extension.
18543 Each line of this file is made up of three fields:
18545 @itemize
18546 @item
18547 The name of the function.
18548 @item
18549 A number of bytes.
18550 @item
18551 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18552 @end itemize
18554 The second field corresponds to the size of the known part of the function
18555 frame.
18557 The qualifier @code{static} means that the function frame size
18558 is purely static.
18559 It usually means that all local variables have a static size.
18560 In this case, the second field is a reliable measure of the function stack
18561 utilization.
18563 The qualifier @code{dynamic} means that the function frame size is not static.
18564 It happens mainly when some local variables have a dynamic size. When this
18565 qualifier appears alone, the second field is not a reliable measure
18566 of the function stack analysis. When it is qualified with  @code{bounded}, it
18567 means that the second field is a reliable maximum of the function stack
18568 utilization.
18570 A unit compiled with @option{-Wstack-usage} will issue a warning for each
18571 subprogram whose stack usage might be larger than the specified amount of
18572 bytes.  The wording is in keeping with the qualifier documented above.
18574 @node Dynamic Stack Usage Analysis
18575 @section Dynamic Stack Usage Analysis
18577 @noindent
18578 It is possible to measure the maximum amount of stack used by a task, by
18579 adding a switch to @command{gnatbind}, as:
18581 @smallexample
18582 $ gnatbind -u0 file
18583 @end smallexample
18585 @noindent
18586 With this option, at each task termination, its stack usage is  output on
18587 @file{stderr}.
18588 It is not always convenient to output the stack usage when the program
18589 is still running. Hence, it is possible to delay this output until program
18590 termination. for a given number of tasks specified as the argument of the
18591 @option{-u} option. For instance:
18593 @smallexample
18594 $ gnatbind -u100 file
18595 @end smallexample
18597 @noindent
18598 will buffer the stack usage information of the first 100 tasks to terminate and
18599 output this info at program termination. Results are displayed in four
18600 columns:
18602 @noindent
18603 Index | Task Name | Stack Size | Stack Usage
18605 @noindent
18606 where:
18608 @table @emph
18609 @item Index
18610 is a number associated with each task.
18612 @item Task Name
18613 is the name of the task analyzed.
18615 @item Stack Size
18616 is the maximum size for the stack.
18618 @item Stack Usage
18619 is the measure done by the stack analyzer. In order to prevent overflow, the stack
18620 is not entirely analyzed, and it's not possible to know exactly how
18621 much has actually been used.
18623 @end table
18625 @noindent
18626 The environment task stack, e.g., the stack that contains the main unit, is
18627 only processed when the environment variable GNAT_STACK_LIMIT is set.
18629 @noindent
18630 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
18631 stack usage reports at run-time. See its body for the details.
18633 @ifclear FSFEDITION
18634 @c *********************************
18635 @c *            GNATCHECK          *
18636 @c *********************************
18637 @node Verifying Properties with gnatcheck
18638 @chapter Verifying Properties with @command{gnatcheck}
18639 @findex gnatcheck
18640 @cindex @command{gnatcheck}
18642 @noindent
18643 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18644 of Ada source files according to a given set of semantic rules.
18645 @cindex ASIS
18647 In order to check compliance with a given rule, @command{gnatcheck} has to
18648 semantically analyze the Ada sources.
18649 Therefore, checks can only be performed on
18650 legal Ada units. Moreover, when a unit depends semantically upon units located
18651 outside the current directory, the source search path has to be provided when
18652 calling @command{gnatcheck}, either through a specified project file or
18653 through @command{gnatcheck} switches.
18655 For full details, refer to @cite{GNATcheck Reference Manual} document.
18656 @end ifclear
18658 @ifclear FSFEDITION
18659 @c *********************************
18660 @node Creating Sample Bodies with gnatstub
18661 @chapter Creating Sample Bodies with @command{gnatstub}
18662 @findex gnatstub
18664 @noindent
18665 @command{gnatstub} creates empty but compilable bodies
18666 for library unit declarations and empty but compilable
18667 subunit for body stubs.
18669 To create a body or a subunit, @command{gnatstub} invokes the Ada
18670 compiler and generates and uses the ASIS tree for the input source;
18671 thus the input must be legal Ada code, and the tool should have all the
18672 information needed to compile the input source. To provide this information,
18673 you may specify as a tool parameter the project file the input source belongs to
18674 (or you may call @command{gnatstub}
18675 through the @command{gnat} driver (see @ref{The GNAT Driver and
18676 Project Files}). Another possibility is to specify the source search
18677 path and needed configuration files in @option{-cargs} section of @command{gnatstub}
18678 call, see the description of the @command{gnatstub} switches below.
18680 If the @command{gnatstub} argument source contains preprocessing directives
18681 then the needed options should be provided to run preprocessor as a part of
18682 the @command{gnatstub} call, and the generated body stub will correspond to
18683 the preprocessed source.
18685 By default, all the program unit bodies generated by @code{gnatstub}
18686 raise the predefined @code{Program_Error} exception, which will catch
18687 accidental calls of generated stubs. This behavior can be changed with
18688 option @option{--no-exception} (see below).
18690 @menu
18691 * Running gnatstub::
18692 * Switches for gnatstub::
18693 @end menu
18695 @node Running gnatstub
18696 @section Running @command{gnatstub}
18698 @noindent
18699 @command{gnatstub} has a command-line interface of the form:
18701 @smallexample
18702 @c $ gnatstub @ovar{switches} @var{filename}
18703 @c Expanding @ovar macro inline (explanation in macro def comments)
18704 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
18705 @end smallexample
18707 @noindent
18708 where
18709 @table @var
18710 @item filename
18711 is the name of the source file that contains a library unit declaration
18712 for which a body must be created or a library unit body for which subunits
18713 must be created for the body stubs declared in this body.
18714 The file name may contain the path information.
18715 If the name does not follow GNAT file naming conventions and a set
18716 of seitches does not contain a project file that defines naming
18717 conventions, the name of the body file must
18718 be provided
18719 explicitly as the value of the @option{-o@var{body-name}} option.
18720 If the file name follows the GNAT file naming
18721 conventions and the name of the body file is not provided,
18722 @command{gnatstub}
18723 takes the naming conventions for the generated source from the
18724 project file provided as a parameter of @option{-P} switch if any,
18725 or creates the name file to generate using the standard GNAT
18726 naming conventions.
18728 @item @samp{@var{gcc_switches}} is a list of switches for
18729 @command{gcc}. They will be passed on to all compiler invocations made by
18730 @command{gnatstub} to generate the ASIS trees. Here you can provide
18731 @option{-I} switches to form the source search path,
18732 use the @option{-gnatec} switch to set the configuration file,
18733 use the @option{-gnat05} switch if sources should be compiled in
18734 Ada 2005 mode etc.
18736 @item switches
18737 is an optional sequence of switches as described in the next section
18738 @end table
18740 @node Switches for gnatstub
18741 @section Switches for @command{gnatstub}
18743 @table @option
18744 @c !sort!
18746 @item --version
18747 @cindex @option{--version} @command{gnatstub}
18748 Display Copyright and version, then exit disregarding all other options.
18750 @item --help
18751 @cindex @option{--help} @command{gnatstub}
18752 Display usage, then exit disregarding all other options.
18754 @item -P @var{file}
18755 @cindex @option{-P} @command{gnatstub}
18756 Indicates the name of the project file that describes the set of sources
18757 to be processed.
18759 @item -X@var{name}=@var{value}
18760 @cindex @option{-X} @command{gnatstub}
18761 Indicates that external variable @var{name} in the argument project
18762 has the value @var{value}. Has no effect if no project is specified as
18763 tool argument.
18765 @item --subunits
18766 @cindex @option{--subunits} (@command{gnatstub})
18767 Generate subunits for body stubs. If this switch is specified,
18768 @command{gnatstub} expects a library unit body as an agrument file,
18769 otherwise a library unit declaration is expected. If a body stub
18770 already has a corresponding subunit, @command{gnatstub} does not
18771 generate anything for it.
18773 @item -f
18774 @cindex @option{-f} (@command{gnatstub})
18775 If the destination directory already contains a file with the name of the
18776 body file
18777 for the argument spec file, replace it with the generated body stub.
18778 This switch cannot be used together with @option{--subunits}.
18780 @item -hs
18781 @cindex @option{-hs} (@command{gnatstub})
18782 Put the comment header (i.e., all the comments preceding the
18783 compilation unit) from the source of the library unit declaration
18784 into the body stub.
18786 @item -hg
18787 @cindex @option{-hg} (@command{gnatstub})
18788 Put a sample comment header into the body stub.
18790 @item --header-file=@var{filename}
18791 @cindex @option{--header-file} (@command{gnatstub})
18792 Use the content of the file as the comment header for a generated body stub.
18794 @item -IDIR
18795 @cindex @option{-IDIR} (@command{gnatstub})
18796 @itemx -I-
18797 @cindex @option{-I-} (@command{gnatstub})
18798 These switches have  the same meaning as in calls to
18799 @command{gcc}.
18800 They define  the source search path in the call to
18801 @command{gcc} issued
18802 by @command{gnatstub} to compile an argument source file.
18804 @item -gnatec@var{PATH}
18805 @cindex @option{-gnatec} (@command{gnatstub})
18806 This switch has the same meaning as in calls to @command{gcc}.
18807 It defines the additional configuration file to be passed to the call to
18808 @command{gcc} issued
18809 by @command{gnatstub} to compile an argument source file.
18811 @item -gnatyM@var{n}
18812 @cindex @option{-gnatyM} (@command{gnatstub})
18813 (@var{n} is a non-negative integer). Set the maximum line length that is
18814 allowed in a source file. The default is 79. The maximum value that can be
18815 specified is 32767. Note that in the special case of configuration
18816 pragma files, the maximum is always 32767 regardless of whether or
18817 not this switch appears.
18819 @item -gnaty@var{n}
18820 @cindex @option{-gnaty} (@command{gnatstub})
18821 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18822 the generated body sample to @var{n}.
18823 The default indentation is 3.
18825 @item -gnatyo
18826 @cindex @option{-gnatyo} (@command{gnatstub})
18827 Order local bodies alphabetically. (By default local bodies are ordered
18828 in the same way as the corresponding local specs in the argument spec file.)
18830 @item -i@var{n}
18831 @cindex @option{-i} (@command{gnatstub})
18832 Same as @option{-gnaty@var{n}}
18834 @item -k
18835 @cindex @option{-k} (@command{gnatstub})
18836 Do not remove the tree file (i.e., the snapshot of the compiler internal
18837 structures used by @command{gnatstub}) after creating the body stub.
18839 @item -l@var{n}
18840 @cindex @option{-l} (@command{gnatstub})
18841 Same as @option{-gnatyM@var{n}}
18843 @item --no-exception
18844 @cindex @option{--no-exception} (@command{gnatstub})
18845 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
18846 This is not always possible for function stubs.
18848 @item --no-local-header
18849 @cindex @option{--no-local-header} (@command{gnatstub})
18850 Do not place local comment header with unit name before body stub for a
18851 unit.
18853 @item -o @var{body-name}
18854 @cindex @option{-o} (@command{gnatstub})
18855 Body file name.  This should be set if the argument file name does not
18856 follow
18857 the GNAT file naming
18858 conventions. If this switch is omitted the default name for the body will be
18859 obtained
18860 from the argument file name according to the GNAT file naming conventions.
18862 @item --dir=@var{dir-name}
18863 @cindex @option{--dir} (@command{gnatstub})
18864 The path to the directory to place the generated files into.
18865 If this switch is not set, the generated library unit body is
18866 placed in the current directory, and generated sununits -
18867 in the directory where the argument body is located.
18869 @item -W@var{e}
18870 @cindex @option{-W} (@command{gnatstub})
18871 Specify the wide character encoding method for the output body file.
18872 @var{e} is one of the following:
18874 @itemize @bullet
18876 @item h
18877 Hex encoding
18879 @item u
18880 Upper half encoding
18882 @item s
18883 Shift/JIS encoding
18885 @item e
18886 EUC encoding
18888 @item 8
18889 UTF-8 encoding
18891 @item b
18892 Brackets encoding (default value)
18893 @end itemize
18895 @item -q
18896 @cindex @option{-q} (@command{gnatstub})
18897 Quiet mode: do not generate a confirmation when a body is
18898 successfully created, and do not generate a message when a body is not
18899 required for an
18900 argument unit.
18902 @item -r
18903 @cindex @option{-r} (@command{gnatstub})
18904 Reuse the tree file (if it exists) instead of creating it.  Instead of
18905 creating the tree file for the library unit declaration, @command{gnatstub}
18906 tries to find it in the current directory and use it for creating
18907 a body. If the tree file is not found, no body is created. This option
18908 also implies @option{-k}, whether or not
18909 the latter is set explicitly.
18911 @item -t
18912 @cindex @option{-t} (@command{gnatstub})
18913 Overwrite the existing tree file.  If the current directory already
18914 contains the file which, according to the GNAT file naming rules should
18915 be considered as a tree file for the argument source file,
18916 @command{gnatstub}
18917 will refuse to create the tree file needed to create a sample body
18918 unless this option is set.
18920 @item -v
18921 @cindex @option{-v} (@command{gnatstub})
18922 Verbose mode: generate version information.
18924 @end table
18925 @end ifclear
18927 @ifclear FSFEDITION
18928 @c *********************************
18929 @node Creating Unit Tests with gnattest
18930 @chapter Creating Unit Tests with @command{gnattest}
18931 @findex gnattest
18933 @noindent
18934 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
18935 as well as a test driver infrastructure (harness). @command{gnattest} creates
18936 a skeleton for each visible subprogram in the packages under consideration when
18937 they do not exist already.
18939 In order to process source files from a project, @command{gnattest} has to
18940 semantically analyze the sources. Therefore, test skeletons can only be
18941 generated for legal Ada units. If a unit is dependent on other units,
18942 those units should be among the source files of the project or of other projects
18943 imported by this one.
18945 Generated skeletons and harnesses are based on the AUnit testing framework.
18946 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
18947 for Java or CppUnit for C++. While it is advised that gnattest users read
18948 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
18949 For correct operation of @command{gnattest}, AUnit should be installed and
18950 aunit.gpr must be on the project path. This happens automatically when Aunit
18951 is installed at its default location.
18952 @menu
18953 * Running gnattest::
18954 * Switches for gnattest::
18955 * Project Attributes for gnattest::
18956 * Simple Example::
18957 * Setting Up and Tearing Down the Testing Environment::
18958 * Regenerating Tests::
18959 * Default Test Behavior::
18960 * Testing Primitive Operations of Tagged Types::
18961 * Testing Inheritance::
18962 * Tagged Types Substitutability Testing::
18963 * Testing with Contracts::
18964 * Additional Tests::
18965 * Putting Tests under Version Control::
18966 * Support for other platforms/run-times::
18967 * Current Limitations::
18968 @end menu
18970 @node Running gnattest
18971 @section Running @command{gnattest}
18973 @noindent
18974 @command{gnattest} has a command-line interface of the form
18976 @smallexample
18977 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
18978 @c Expanding @ovar macro inline (explanation in macro def comments)
18979 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18980 @end smallexample
18982 @noindent
18983 where
18984 @table @var
18986 @item -Pprojname
18987 specifies the project defining the location of source files. When no
18988 file names are provided on the command line, all sources in the project
18989 are used as input. This switch is required.
18991 @item filename
18992 is the name of the source file containing the library unit package declaration
18993 for which a test package will be created. The file name may be given with a
18994 path.
18996 @item @samp{@var{gcc_switches}}
18997 is a list of switches for
18998 @command{gcc}. These switches will be passed on to all compiler invocations
18999 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19000 @option{-I} switches to form the source search path,
19001 use the @option{-gnatec} switch to set the configuration file,
19002 use the @option{-gnat05} switch if sources should be compiled in
19003 Ada 2005 mode, etc.
19005 @item switches
19006 is an optional sequence of switches as described in the next section.
19008 @end table
19010 @command{gnattest} results can be found in two different places.
19012 @itemize @bullet
19013 @item automatic harness:
19014 the harness code, which is located by default in "gnattest/harness" directory
19015 that is created in the object directory of corresponding project file. All of
19016 this code is generated completely automatically and can be destroyed and
19017 regenerated at will. It is not recommended to modify this code manually, since
19018 it could easily be overridden by mistake. The entry point in the harness code is
19019 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19020 using a command such as:
19022 @smallexample
19023 gnatmake -P<harness-dir>/test_driver
19024 test_runner
19025 @end smallexample
19027 Note that you might need to specify the necessary values of scenario variables
19028 when you are not using the AUnit defaults.
19030 @item actual unit test skeletons:
19031 a test skeleton for each visible subprogram is created in a separate file, if it
19032 doesn't exist already. By default, those separate test files are located in a
19033 "gnattest/tests" directory that is created in the object directory of
19034 corresponding project file. For example, if a source file my_unit.ads in
19035 directory src contains a visible subprogram Proc, then the corresponding unit
19036 test will be found in file src/tests/my_unit-test_data-tests.adb and will be
19037 called Test_Proc_<code>. <code> is a signature encoding used to differentiate
19038 test names in case of overloading.
19040 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19041 this will cause a name conflict with the generated test package.
19042 @end itemize
19044 @node Switches for gnattest
19045 @section Switches for @command{gnattest}
19047 @table @option
19048 @c !sort!
19050 @item --harness-only
19051 @cindex @option{--harness-only} (@command{gnattest})
19052 When this option is given, @command{gnattest} creates a harness for all
19053 sources, treating them as test packages.
19055 @item --additional-tests=@var{projname}
19056 @cindex @option{--additional-tests} (@command{gnattest})
19057 Sources described in @var{projname} are considered potential additional
19058 manual tests to be added to the test suite.
19060 @item -r
19061 @cindex @option{-r} (@command{gnattest})
19062 Recursively consider all sources from all projects.
19064 @item -X@var{name=value}
19065 @cindex @option{-X} (@command{gnattest})
19066 Indicate that external variable @var{name} has the value @var{value}.
19068 @item -q
19069 @cindex @option{-q} (@command{gnattest})
19070 Suppresses noncritical output messages.
19072 @item -v
19073 @cindex @option{-v} (@command{gnattest})
19074 Verbose mode: generates version information if specified by itself on the
19075 command line.  If specified via GNATtest_Switches, produces output
19076 about the execution of the tool.
19078 @item --validate-type-extensions
19079 @cindex @option{--validate-type-extensions} (@command{gnattest})
19080 Enables substitution check: run all tests from all parents in order
19081 to check substitutability.
19083 @item --skeleton-default=@var{val}
19084 @cindex @option{--skeleton-default} (@command{gnattest})
19085 Specifies the default behavior of generated skeletons. @var{val} can be either
19086 "fail" or "pass", "fail" being the default.
19088 @item --passed-tests=@var{val}
19089 @cindex @option{--passed-tests} (@command{gnattest})
19090 Specifies whether or not passed tests should be shown. @var{val} can be either
19091 "show" or "hide", "show" being the default.
19093 @item --exit-status=@var{val}
19094 @cindex @option{--exit-status} (@command{gnattest})
19095 Specifies whether or not generated test driver should return failure exit
19096 status if at least one test fails or crashes. @var{val} can be either
19097 "on" or "off", "off" being the default.
19100 @item --tests-root=@var{dirname}
19101 @cindex @option{--tests-root} (@command{gnattest})
19102 The hierarchy of source directories, if any, is recreated in the @var{dirname}
19103 directory, with test packages placed in directories corresponding to those of the sources.
19104 If the @var{dirname} is a relative path, it is considered relative to the object
19105 directory of the project file. When all sources from all projects are taken
19106 recursively from all projects, directory hierarchies of tested sources are
19107 recreated for each project in their object directories and test packages are
19108 placed accordingly.
19110 @item --subdir=@var{dirname}
19111 @cindex @option{--subdir} (@command{gnattest})
19112 Test packages are placed in a subdirectory of the corresponding source directory,
19113 with the name @var{dirname}. Thus, each set of unit tests is located in a subdirectory of the
19114 code under test.  If the sources are in separate directories, each source directory
19115 has a test subdirectory named @var{dirname}.
19117 @item --tests-dir=@var{dirname}
19118 @cindex @option{--tests-dir} (@command{gnattest})
19119 All test packages are placed in the @var{dirname} directory.
19120 If the @var{dirname} is a relative path, it is considered relative to the object
19121 directory of the project file. When all sources from all projects are taken
19122 recursively from all projects, @var{dirname} directories are created for each
19123 project in their object directories and test packages are placed accordingly.
19125 @item --harness-dir=@var{dirname}
19126 @cindex @option{--harness-dir} (@command{gnattest})
19127 specifies the directory that will hold the harness packages and project file
19128 for the test driver. If the @var{dirname} is a relative path, it is considered
19129 relative to the object directory of the project file.
19131 @item --separates
19132 @cindex @option{--separates} (@command{gnattest})
19133 Bodies of all test routines are generated as separates. Note that this mode is
19134 kept for compatibility reasons only and it is not advised to use it due to
19135 possible problems with hash in names of test skeletons when using an
19136 inconsistent casing. Separate test skeletons can be incorporated to monolith
19137 test package with improved hash being used by using @option{--transition}
19138 switch.
19141 @item --transition
19142 @cindex @option{--transition} (@command{gnattest})
19143 This allows transition from separate test routines to monolith test packages.
19144 All matching test routines are overwritten with contents of corresponding
19145 separates. Note that if separate test routines had any manually added with
19146 clauses they will be moved to the test package body as is and have to be moved
19147 by hand.
19149 @item --omit-sloc
19150 @cindex @option{--omit-sloc} (@command{gnattest})
19151 Suppresses comment line containing file name and line number of corresponding
19152 subprograms in test skeletons.
19154 @item --test-duration
19155 @cindex @option{--test-duration} (@command{gnattest})
19156 Adds time measurements for each test in generated test driver.
19158 @end table
19160 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19161 mutually exclusive.
19163 @node Project Attributes for gnattest
19164 @section Project Attributes for @command{gnattest}
19166 @noindent
19168 Most of the command-line options can also be passed to the tool by adding
19169 special attributes to the project file. Those attributes should be put in
19170 package gnattest. Here is the list of attributes:
19172 @itemize @bullet
19174 @item Tests_Root
19175 is used to select the same output mode as with the --tests-root option.
19176 This attribute cannot be used together with Subdir or Tests_Dir.
19178 @item Subdir
19179 is used to select the same output mode as with the --subdir option.
19180 This attribute cannot be used together with Tests_Root or Tests_Dir.
19182 @item Tests_Dir
19183 is used to select the same output mode as with the --tests-dir option.
19184 This attribute cannot be used together with Subdir or Tests_Root.
19186 @item Harness_Dir
19187 is used to specify the directory in which to place harness packages and project
19188 file for the test driver, otherwise specified by --harness-dir.
19190 @item Additional_Tests
19191 is used to specify the project file, otherwise given by
19192 --additional-tests switch.
19194 @item Skeletons_Default
19195 is used to specify the default behaviour of test skeletons, otherwise
19196 specified by --skeleton-default option. The value of this attribute
19197 should be either "pass" or "fail".
19199 @end itemize
19201 Each of those attributes can be overridden from the command line if needed.
19202 Other @command{gnattest} switches can also be passed via the project
19203 file as an attribute list called GNATtest_Switches.
19205 @node Simple Example
19206 @section Simple Example
19208 @noindent
19210 Let's take a very simple example using the first @command{gnattest} example
19211 located in:
19213 @smallexample
19214 <install_prefix>/share/examples/gnattest/simple
19215 @end smallexample
19217 This project contains a simple package containing one subprogram. By running gnattest:
19219 @smallexample
19220 $ gnattest --harness-dir=driver -Psimple.gpr
19221 @end smallexample
19223 a test driver is created in directory "driver". It can be compiled and run:
19225 @smallexample
19226 $ cd obj/driver
19227 $ gnatmake -Ptest_driver
19228 $ test_runner
19229 @end smallexample
19231 One failed test with diagnosis "test not implemented" is reported.
19232 Since no special output option was specified, the test package Simple.Tests
19233 is located in:
19235 @smallexample
19236 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19237 @end smallexample
19239 For each package containing visible subprograms, a child test package is
19240 generated. It contains one test routine per tested subprogram. Each
19241 declaration of a test subprogram has a comment specifying which tested
19242 subprogram it corresponds to. Bodies of test routines are placed in test package
19243 bodies and are surrounded by special comment sections. Those comment sections
19244 should not be removed or modified in order for gnattest to be able to regenerate
19245 test packages and keep already written tests in place.
19246 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19247 a single statement: a call to procedure Assert. It has two arguments:
19248 the Boolean expression we want to check and the diagnosis message to display if
19249 the condition is false.
19251 That is where actual testing code should be written after a proper setup.
19252 An actual check can be performed by replacing the Assert call with:
19254 @smallexample @c ada
19255 Assert (Inc (1) = 2, "wrong incrementation");
19256 @end smallexample
19258 After recompiling and running the test driver, one successfully passed test
19259 is reported.
19261 @node Setting Up and Tearing Down the Testing Environment
19262 @section Setting Up and Tearing Down the Testing Environment
19264 @noindent
19266 Besides test routines themselves, each test package has a parent package
19267 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19268 overwritten by the tool. Set_Up is called before each test routine of the
19269 package and Tear_Down is called after each test routine. Those two procedures
19270 can be used to perform necessary initialization and finalization,
19271 memory allocation, etc. Test type declared in Test_Data package is parent type
19272 for the test type of test package and can have user-defined components whose
19273 values can be set by Set_Up routine and used in test routines afterwards.
19275 @node Regenerating Tests
19276 @section Regenerating Tests
19278 @noindent
19280 Bodies of test routines and test_data packages are never overridden after they
19281 have been created once. As long as the name of the subprogram, full expanded Ada
19282 names, and the order of its parameters is the same, and comment sections are
19283 intact the old test routine will fit in its place and no test skeleton will be
19284 generated for the subprogram.
19286 This can be demonstrated with the previous example. By uncommenting declaration
19287 and body of function Dec in simple.ads and simple.adb, running
19288 @command{gnattest} on the project, and then running the test driver:
19290 @smallexample
19291 gnattest --harness-dir=driver -Psimple.gpr
19292 cd obj/driver
19293 gnatmake -Ptest_driver
19294 test_runner
19295 @end smallexample
19297 the old test is not replaced with a stub, nor is it lost, but a new test
19298 skeleton is created for function Dec.
19300 The only way of regenerating tests skeletons is to remove the previously created
19301 tests together with corresponding comment sections.
19303 @node Default Test Behavior
19304 @section Default Test Behavior
19306 @noindent
19308 The generated test driver can treat unimplemented tests in two ways:
19309 either count them all as failed (this is useful to see which tests are still
19310 left to implement) or as passed (to sort out unimplemented ones from those
19311 actually failing).
19313 The test driver accepts a switch to specify this behavior:
19314 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19315 @command{gnattest}).
19317 The default behavior of the test driver is set with the same switch
19318 as passed to gnattest when generating the test driver.
19320 Passing it to the driver generated on the first example:
19322 @smallexample
19323 test_runner --skeleton-default=pass
19324 @end smallexample
19326 makes both tests pass, even the unimplemented one.
19328 @node Testing Primitive Operations of Tagged Types
19329 @section Testing Primitive Operations of Tagged Types
19331 @noindent
19333 Creation of test skeletons for primitive operations of tagged types entails
19334 a number of features. Test routines for all primitives of a given tagged type
19335 are placed in a separate child package named according to the tagged type. For
19336 example, if you have tagged type T in package P, all tests for primitives
19337 of T will be in P.T_Test_Data.T_Tests.
19339 Consider running gnattest on the second example (note: actual tests for this
19340 example already exist, so there's no need to worry if the tool reports that
19341 no new stubs were generated):
19343 @smallexample
19344 cd <install_prefix>/share/examples/gnattest/tagged_rec
19345 gnattest --harness-dir=driver -Ptagged_rec.gpr
19346 @end smallexample
19348 Taking a closer look at the test type declared in the test package
19349 Speed1.Controller_Test_Data is necessary. It is declared in:
19351 @smallexample
19352 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19353 @end smallexample
19355 Test types are direct or indirect descendants of
19356 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19357 subprograms, the user doesn't need to be concerned with them. However,
19358 when generating test packages for primitive operations, there are some things
19359 the user needs to know.
19361 Type Test_Controller has components that allow assignment of various
19362 derivations of type Controller. And if you look at the specification of
19363 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19364 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19365 Thus, test types mirror the hierarchy of tested types.
19367 The Set_Up procedure of Test_Data package corresponding to a test package
19368 of primitive operations of type T assigns to Fixture a reference to an
19369 object of that exact type T. Notice, however, that if the tagged type has
19370 discriminants, the Set_Up only has a commented template for setting
19371 up the fixture, since filling the discriminant with actual value is up
19372 to the user.
19374 The knowledge of the structure of test types allows additional testing
19375 without additional effort. Those possibilities are described below.
19377 @node Testing Inheritance
19378 @section Testing Inheritance
19380 @noindent
19382 Since the test type hierarchy mimics the hierarchy of tested types, the
19383 inheritance of tests takes place. An example of such inheritance can be
19384 seen by running the test driver generated for the second example. As previously
19385 mentioned, actual tests are already written for this example.
19387 @smallexample
19388 cd obj/driver
19389 gnatmake -Ptest_driver
19390 test_runner
19391 @end smallexample
19393 There are 6 passed tests while there are only 5 testable subprograms. The test
19394 routine for function Speed has been inherited and run against objects of the
19395 derived type.
19397 @node Tagged Types Substitutability Testing
19398 @section Tagged Types Substitutability Testing
19400 @noindent
19402 Tagged Types Substitutability Testing is a way of verifying the global type
19403 consistency by testing. Global type consistency is a principle stating that if
19404 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19405 then objects of type T may be replaced with objects of type S (that is,
19406 objects of type S may be substituted for objects of type T), without
19407 altering any of the desirable properties of the program. When the properties
19408 of the program are expressed in the form of subprogram preconditions and
19409 postconditions (let's call them pre and post), the principle is formulated as
19410 relations between the pre and post of primitive operations and the pre and post
19411 of their derived operations. The pre of a derived operation should not be
19412 stronger than the original pre, and the post of the derived operation should
19413 not be weaker than the original post. Those relations ensure that verifying if
19414 a dispatching call is safe can be done just by using the pre and post of the
19415 root operation.
19417 Verifying global type consistency by testing consists of running all the unit
19418 tests associated with the primitives of a given tagged type with objects of its
19419 derived types.
19421 In the example used in the previous section, there was clearly a violation of
19422 type consistency. The overriding primitive Adjust_Speed in package Speed2
19423 removes the functionality of the overridden primitive and thus doesn't respect
19424 the consistency principle.
19425 Gnattest has a special option to run overridden parent tests against objects
19426 of the type which have overriding primitives:
19428 @smallexample
19429 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19430 cd obj/driver
19431 gnatmake -Ptest_driver
19432 test_runner
19433 @end smallexample
19435 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19436 against objects of the derived type.
19438 Non-overridden tests are already inherited for derived test types, so the
19439 --validate-type-extensions enables the application of overriden tests to objects
19440 of derived types.
19442 @node Testing with Contracts
19443 @section Testing with Contracts
19445 @noindent
19447 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19448 as well as corresponding aspects.
19449 Test routines are generated, one per each Test_Case associated with a tested
19450 subprogram. Those test routines have special wrappers for tested functions
19451 that have composition of pre- and postcondition of the subprogram with
19452 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19453 either count for Nominal mode or do not count for Robustness mode).
19455 The third example demonstrates how this works:
19457 @smallexample
19458 cd <install_prefix>/share/examples/gnattest/contracts
19459 gnattest --harness-dir=driver -Pcontracts.gpr
19460 @end smallexample
19462 Putting actual checks within the range of the contract does not cause any
19463 error reports. For example, for the test routine which corresponds to
19464 test case 1:
19466 @smallexample @c ada
19467 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19468 @end smallexample
19470 and for the test routine corresponding to test case 2:
19472 @smallexample @c ada
19473 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19474 @end smallexample
19476 are acceptable:
19478 @smallexample
19479 cd obj/driver
19480 gnatmake -Ptest_driver
19481 test_runner
19482 @end smallexample
19484 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19485 a precondition violation for test case one. Also, by using any otherwise
19486 correct but positive pair of numbers in the second test routine, you can also
19487 get a precondition violation. Postconditions are checked and reported
19488 the same way.
19490 @node Additional Tests
19491 @section Additional Tests
19493 @noindent
19494 @command{gnattest} can add user-written tests to the main suite of the test
19495 driver. @command{gnattest} traverses the given packages and searches for test
19496 routines. All procedures with a single in out parameter of a type which is
19497 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19498 specifications are added to the suites and are then executed by the test driver.
19499 (Set_Up and Tear_Down are filtered out.)
19501 An example illustrates two ways of creating test harnesses for user-written
19502 tests. Directory additional_tests contains an AUnit-based test driver written
19503 by hand.
19505 @smallexample
19506 <install_prefix>/share/examples/gnattest/additional_tests/
19507 @end smallexample
19509 To create a test driver for already-written tests, use the --harness-only
19510 option:
19512 @smallexample
19513 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19514   --harness-only
19515 gnatmake -Pharness_only/test_driver.gpr
19516 harness_only/test_runner
19517 @end smallexample
19519 Additional tests can also be executed together with generated tests:
19521 @smallexample
19522 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19523   --harness-dir=mixing
19524 gnatmake -Pmixing/test_driver.gpr
19525 mixing/test_runner
19526 @end smallexample
19528 @node Putting Tests under Version Control
19529 @section Putting Tests under Version Control
19531 @noindent
19532 As has been stated earlier, @command{gnattest} generates two different types
19533 of code, test skeletons and harness. The harness is generated completely
19534 automatically each time, does not require manual changes and therefore should
19535 not be put under version control.
19536 It makes sense to put under version control files containing test data packages,
19537 both specs and bodies, and files containing bodies of test packages. Note that
19538 test package specs are also generated automatically each time and should not be
19539 put under version control.
19540 Option @option{--omit-sloc} may be usefull when putting test packages under VCS.
19542 @node Support for other platforms/run-times
19543 @section Support for other platforms/run-times
19545 @noindent
19546 @command{gnattest} can be used to generate the test harness for platforms
19547 and run-time libraries others than the default native target with the
19548 default full run-time. For example, when using a limited run-time library
19549 such as Zero FootPrint (ZFP), a simplified harness is generated.
19551 Two variables are used to tell the underlying AUnit framework how to generate
19552 the test harness: @code{PLATFORM}, which identifies the target, and
19553 @code{RUNTIME}, used to determine the run-time library for which the harness
19554 is generated. Corresponding prefix should also be used when calling
19555 @command{gnattest} for non-native targets. For example, the following options
19556 are used to generate the AUnit test harness for a PowerPC ELF target using
19557 the ZFP run-time library:
19559 @smallexample
19560 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19561 @end smallexample
19563 @node Current Limitations
19564 @section Current Limitations
19566 @noindent
19568 The tool currently does not support following features:
19570 @itemize @bullet
19571 @item generic tests for nested generic packages and their instantiations
19572 @item tests for protected subprograms and entries
19574 @end itemize
19575 @end ifclear
19578 @c *********************************
19579 @node Performing Dimensionality Analysis in GNAT
19580 @chapter Performing Dimensionality Analysis in GNAT
19581 @cindex Dimensionality analysis
19583 @noindent
19584 The GNAT compiler now supports dimensionality checking. The user can
19585 specify physical units for objects, and the compiler will verify that uses
19586 of these objects are compatible with their dimensions, in a fashion that is
19587 familiar to engineering practice. The dimensions of algebraic expressions
19588 (including powers with static exponents) are computed from their constituents.
19590 This feature depends on Ada 2012 aspect specifications, and is available from
19591 version 7.0.1 of GNAT onwards.
19592 The GNAT-specific aspect @code{Dimension_System}
19593 @cindex @code{Dimension_System} aspect
19594 allows you to define a system of units; the aspect @code{Dimension}
19595 @cindex @code{Dimension} aspect
19596 then allows the user to declare dimensioned quantities within a given system.
19597 (These aspects are described in the @i{Implementation Defined Aspects}
19598 chapter of the @i{GNAT Reference Manual}).
19600 The major advantage of this model is that it does not require the declaration of
19601 multiple operators for all possible combinations of types: it is only necessary
19602 to use the proper subtypes in object declarations.
19604 The simplest way to impose dimensionality checking on a computation is to make
19605 use of the package @code{System.Dim.Mks},
19606 @cindex @code{System.Dim.Mks} package (GNAT library)
19607 which is part of the GNAT library. This
19608 package defines a floating-point type @code{MKS_Type},
19609 @cindex @code{MKS_Type} type
19610 for which a sequence of
19611 dimension names are specified, together with their conventional abbreviations.
19612 The following should be read together with the full specification of the
19613 package, in file @file{s-dimmks.ads}.
19614 @cindex @file{s-dimmks.ads} file
19616 @smallexample @c ada
19617 @group
19618    @b{type} Mks_Type @b{is} @b{new} Long_Long_Float
19619      @b{with}
19620       Dimension_System => (
19621         (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
19622         (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
19623         (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
19624         (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
19625         (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
19626         (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
19627         (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
19628 @end group
19629 @end smallexample
19631 @noindent
19632 The package then defines a series of subtypes that correspond to these
19633 conventional units. For example:
19635 @smallexample @c ada
19636 @group
19637    @b{subtype} Length @b{is} Mks_Type
19638      @b{with}
19639       Dimension => (Symbol => 'm', Meter  => 1, @b{others} => 0);
19640 @end group
19641 @end smallexample
19643 @noindent
19644 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
19645 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
19646 @code{Luminous_Intensity} (the standard set of units of the SI system).
19648 The package also defines conventional names for values of each unit, for
19649 example:
19651 @smallexample @c ada
19652 @group
19653    m   : @b{constant} Length           := 1.0;
19654    kg  : @b{constant} Mass             := 1.0;
19655    s   : @b{constant} Time             := 1.0;
19656    A   : @b{constant} Electric_Current := 1.0;
19657 @end group
19658 @end smallexample
19660 @noindent
19661 as well as useful multiples of these units:
19663 @smallexample @c ada
19664 @group
19665    cm  : @b{constant} Length := 1.0E-02;
19666    g   : @b{constant} Mass   := 1.0E-03;
19667    min : @b{constant} Time   := 60.0;
19668    day : @b{constant} Time   := 60.0 * 24.0 * min;
19669   ...
19670 @end group
19671 @end smallexample
19673 @noindent
19674 Using this package, you can then define a derived unit by
19675 providing the aspect that
19676 specifies its dimensions within the MKS system, as well as the string to
19677 be used for output of a value of that unit:
19679 @smallexample @c ada
19680 @group
19681   @b{subtype} Acceleration @b{is} Mks_Type
19682     @b{with} Dimension => ("m/sec^2",
19683                        Meter => 1,
19684                        Second => -2,
19685                        @b{others} => 0);
19686 @end group
19687 @end smallexample
19689 @noindent
19690 Here is a complete example of use:
19692 @smallexample @c ada
19693 @group
19694 @b{with} System.Dim.MKS; @b{use} System.Dim.Mks;
19695 @b{with} System.Dim.Mks_IO; @b{use} System.Dim.Mks_IO;
19696 @b{with} Text_IO; @b{use} Text_IO;
19697 @b{procedure} Free_Fall @b{is}
19698   @b{subtype} Acceleration @b{is} Mks_Type
19699     @b{with} Dimension => ("m/sec^2", 1, 0, -2, @b{others} => 0);
19700   G : @b{constant} acceleration := 9.81 * m / (s ** 2);
19701   T : Time := 10.0*s;
19702   Distance : Length;
19703 @end group
19704 @group
19705 @b{begin}
19706   Put ("Gravitational constant: ");
19707   Put (G, Aft => 2, Exp => 0); Put_Line ("");
19708   Distance := 0.5 * G * T ** 2;
19709   Put ("distance travelled in 10 seconds of free fall ");
19710   Put (Distance, Aft => 2, Exp => 0);
19711   Put_Line ("");
19712 @b{end} Free_Fall;
19713 @end group
19714 @end smallexample
19716 @noindent
19717 Execution of this program yields:
19718 @smallexample
19719 @group
19720 Gravitational constant:  9.81 m/sec^2
19721 distance travelled in 10 seconds of free fall 490.50 m
19722 @end group
19723 @end smallexample
19725 @noindent
19726 However, incorrect assignments such as:
19728 @smallexample @c ada
19729 @group
19730    Distance := 5.0;
19731    Distance := 5.0 * kg:
19732 @end group
19733 @end smallexample
19735 @noindent
19736 are rejected with the following diagnoses:
19738 @smallexample
19739 @group
19740    Distance := 5.0;
19741       >>> dimensions mismatch in assignment
19742       >>> left-hand side has dimension [L]
19743       >>> right-hand side is dimensionless
19744 @end group
19746 @group
19747    Distance := 5.0 * kg:
19748       >>> dimensions mismatch in assignment
19749       >>> left-hand side has dimension [L]
19750       >>> right-hand side has dimension [M]
19751 @end group
19752 @end smallexample
19754 @noindent
19755 The dimensions of an expression are properly displayed, even if there is
19756 no explicit subtype for it. If we add to the program:
19758 @smallexample @c ada
19759 @group
19760       Put ("Final velocity: ");
19761       Put (G * T, Aft =>2, Exp =>0);
19762       Put_Line ("");
19763 @end group
19764 @end smallexample
19766 @noindent
19767 then the output includes:
19768 @smallexample
19769      Final velocity: 98.10 m.s**(-1)
19770 @end smallexample
19773 @c *********************************
19774 @node Generating Ada Bindings for C and C++ headers
19775 @chapter Generating Ada Bindings for C and C++ headers
19776 @findex binding
19778 @noindent
19779 GNAT now comes with a binding generator for C and C++ headers which is
19780 intended to do 95% of the tedious work of generating Ada specs from C
19781 or C++ header files.
19783 Note that this capability is not intended to generate 100% correct Ada specs,
19784 and will is some cases require manual adjustments, although it can often
19785 be used out of the box in practice.
19787 Some of the known limitations include:
19789 @itemize @bullet
19790 @item only very simple character constant macros are translated into Ada
19791 constants. Function macros (macros with arguments) are partially translated
19792 as comments, to be completed manually if needed.
19793 @item some extensions (e.g. vector types) are not supported
19794 @item pointers to pointers or complex structures are mapped to System.Address
19795 @item identifiers with identical name (except casing) will generate compilation
19796       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19797 @end itemize
19799 The code generated is using the Ada 2005 syntax, which makes it
19800 easier to interface with other languages than previous versions of Ada.
19802 @menu
19803 * Running the binding generator::
19804 * Generating bindings for C++ headers::
19805 * Switches::
19806 @end menu
19808 @node Running the binding generator
19809 @section Running the binding generator
19811 @noindent
19812 The binding generator is part of the @command{gcc} compiler and can be
19813 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
19814 spec files for the header files specified on the command line, and all
19815 header files needed by these files transitively. For example:
19817 @smallexample
19818 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
19819 $ gcc -c -gnat05 *.ads
19820 @end smallexample
19822 will generate, under GNU/Linux, the following files: @file{time_h.ads},
19823 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
19824 correspond to the files @file{/usr/include/time.h},
19825 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
19826 mode these Ada specs.
19828 The @code{-C} switch tells @command{gcc} to extract comments from headers,
19829 and will attempt to generate corresponding Ada comments.
19831 If you want to generate a single Ada file and not the transitive closure, you
19832 can use instead the @option{-fdump-ada-spec-slim} switch.
19834 You can optionally specify a parent unit, of which all generated units will
19835 be children, using @code{-fada-spec-parent=}@var{unit}.
19837 Note that we recommend when possible to use the @command{g++} driver to
19838 generate bindings, even for most C headers, since this will in general
19839 generate better Ada specs. For generating bindings for C++ headers, it is
19840 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
19841 is equivalent in this case. If @command{g++} cannot work on your C headers
19842 because of incompatibilities between C and C++, then you can fallback to
19843 @command{gcc} instead.
19845 For an example of better bindings generated from the C++ front-end,
19846 the name of the parameters (when available) are actually ignored by the C
19847 front-end. Consider the following C header:
19849 @smallexample
19850 extern void foo (int variable);
19851 @end smallexample
19853 with the C front-end, @code{variable} is ignored, and the above is handled as:
19855 @smallexample
19856 extern void foo (int);
19857 @end smallexample
19859 generating a generic:
19861 @smallexample
19862 procedure foo (param1 : int);
19863 @end smallexample
19865 with the C++ front-end, the name is available, and we generate:
19867 @smallexample
19868 procedure foo (variable : int);
19869 @end smallexample
19871 In some cases, the generated bindings will be more complete or more meaningful
19872 when defining some macros, which you can do via the @option{-D} switch. This
19873 is for example the case with @file{Xlib.h} under GNU/Linux:
19875 @smallexample
19876 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
19877 @end smallexample
19879 The above will generate more complete bindings than a straight call without
19880 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
19882 In other cases, it is not possible to parse a header file in a stand-alone
19883 manner, because other include files need to be included first. In this
19884 case, the solution is to create a small header file including the needed
19885 @code{#include} and possible @code{#define} directives. For example, to
19886 generate Ada bindings for @file{readline/readline.h}, you need to first
19887 include @file{stdio.h}, so you can create a file with the following two
19888 lines in e.g. @file{readline1.h}:
19890 @smallexample
19891 #include <stdio.h>
19892 #include <readline/readline.h>
19893 @end smallexample
19895 and then generate Ada bindings from this file:
19897 @smallexample
19898 $ g++ -c -fdump-ada-spec readline1.h
19899 @end smallexample
19901 @node Generating bindings for C++ headers
19902 @section Generating bindings for C++ headers
19904 @noindent
19905 Generating bindings for C++ headers is done using the same options, always
19906 with the @command{g++} compiler.
19908 In this mode, C++ classes will be mapped to Ada tagged types, constructors
19909 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
19910 multiple inheritance of abstract classes will be mapped to Ada interfaces
19911 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
19912 information on interfacing to C++).
19914 For example, given the following C++ header file:
19916 @smallexample
19917 @group
19918 @cartouche
19919 class Carnivore @{
19920 public:
19921    virtual int Number_Of_Teeth () = 0;
19924 class Domestic @{
19925 public:
19926    virtual void Set_Owner (char* Name) = 0;
19929 class Animal @{
19930 public:
19931   int Age_Count;
19932   virtual void Set_Age (int New_Age);
19935 class Dog : Animal, Carnivore, Domestic @{
19936  public:
19937   int  Tooth_Count;
19938   char *Owner;
19940   virtual int  Number_Of_Teeth ();
19941   virtual void Set_Owner (char* Name);
19943   Dog();
19945 @end cartouche
19946 @end group
19947 @end smallexample
19949 The corresponding Ada code is generated:
19951 @smallexample @c ada
19952 @group
19953 @cartouche
19954   @b{package} Class_Carnivore @b{is}
19955     @b{type} Carnivore @b{is} @b{limited} interface;
19956     @b{pragma} Import (CPP, Carnivore);
19958     @b{function} Number_Of_Teeth (this : @b{access} Carnivore) @b{return} int @b{is} @b{abstract};
19959   @b{end};
19960   @b{use} Class_Carnivore;
19962   @b{package} Class_Domestic @b{is}
19963     @b{type} Domestic @b{is} @b{limited} interface;
19964     @b{pragma} Import (CPP, Domestic);
19966     @b{procedure} Set_Owner
19967       (this : @b{access} Domestic;
19968        Name : Interfaces.C.Strings.chars_ptr) @b{is} @b{abstract};
19969   @b{end};
19970   @b{use} Class_Domestic;
19972   @b{package} Class_Animal @b{is}
19973     @b{type} Animal @b{is} @b{tagged} @b{limited} @b{record}
19974       Age_Count : @b{aliased} int;
19975     @b{end} @b{record};
19976     @b{pragma} Import (CPP, Animal);
19978     @b{procedure} Set_Age (this : @b{access} Animal; New_Age : int);
19979     @b{pragma} Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
19980   @b{end};
19981   @b{use} Class_Animal;
19983   @b{package} Class_Dog @b{is}
19984     @b{type} Dog @b{is} @b{new} Animal @b{and} Carnivore @b{and} Domestic @b{with} @b{record}
19985       Tooth_Count : @b{aliased} int;
19986       Owner : Interfaces.C.Strings.chars_ptr;
19987     @b{end} @b{record};
19988     @b{pragma} Import (CPP, Dog);
19990     @b{function} Number_Of_Teeth (this : @b{access} Dog) @b{return} int;
19991     @b{pragma} Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
19993     @b{procedure} Set_Owner
19994       (this : @b{access} Dog; Name : Interfaces.C.Strings.chars_ptr);
19995     @b{pragma} Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
19997     @b{function} New_Dog @b{return} Dog;
19998     @b{pragma} CPP_Constructor (New_Dog);
19999     @b{pragma} Import (CPP, New_Dog, "_ZN3DogC1Ev");
20000   @b{end};
20001   @b{use} Class_Dog;
20002 @end cartouche
20003 @end group
20004 @end smallexample
20006 @node Switches
20007 @section Switches
20009 @table @option
20010 @item -fdump-ada-spec
20011 @cindex @option{-fdump-ada-spec} (@command{gcc})
20012 Generate Ada spec files for the given header files transitively (including
20013 all header files that these headers depend upon).
20015 @item -fdump-ada-spec-slim
20016 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20017 Generate Ada spec files for the header files specified on the command line
20018 only.
20020 @item -fada-spec-parent=@var{unit}
20021 @cindex -fada-spec-parent (@command{gcc})
20022 Specifies that all files generated by @option{-fdump-ada-spec*} are
20023 to be child units of the specified parent unit.
20025 @item -C
20026 @cindex @option{-C} (@command{gcc})
20027 Extract comments from headers and generate Ada comments in the Ada spec files.
20028 @end table
20030 @node Other Utility Programs
20031 @chapter Other Utility Programs
20033 @noindent
20034 This chapter discusses some other utility programs available in the Ada
20035 environment.
20037 @menu
20038 * Using Other Utility Programs with GNAT::
20039 * The External Symbol Naming Scheme of GNAT::
20040 * Converting Ada Files to html with gnathtml::
20041 * Installing gnathtml::
20042 @end menu
20044 @node Using Other Utility Programs with GNAT
20045 @section Using Other Utility Programs with GNAT
20047 @noindent
20048 The object files generated by GNAT are in standard system format and in
20049 particular the debugging information uses this format. This means
20050 programs generated by GNAT can be used with existing utilities that
20051 depend on these formats.
20053 In general, any utility program that works with C will also often work with
20054 Ada programs generated by GNAT. This includes software utilities such as
20055 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20056 as Purify.
20058 @node The External Symbol Naming Scheme of GNAT
20059 @section The External Symbol Naming Scheme of GNAT
20061 @noindent
20062 In order to interpret the output from GNAT, when using tools that are
20063 originally intended for use with other languages, it is useful to
20064 understand the conventions used to generate link names from the Ada
20065 entity names.
20067 All link names are in all lowercase letters. With the exception of library
20068 procedure names, the mechanism used is simply to use the full expanded
20069 Ada name with dots replaced by double underscores. For example, suppose
20070 we have the following package spec:
20072 @smallexample @c ada
20073 @group
20074 @cartouche
20075 @b{package} QRS @b{is}
20076    MN : Integer;
20077 @b{end} QRS;
20078 @end cartouche
20079 @end group
20080 @end smallexample
20082 @noindent
20083 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20084 the corresponding link name is @code{qrs__mn}.
20085 @findex Export
20086 Of course if a @code{pragma Export} is used this may be overridden:
20088 @smallexample @c ada
20089 @group
20090 @cartouche
20091 @b{package} Exports @b{is}
20092    Var1 : Integer;
20093    @b{pragma} Export (Var1, C, External_Name => "var1_name");
20094    Var2 : Integer;
20095    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
20096 @b{end} Exports;
20097 @end cartouche
20098 @end group
20099 @end smallexample
20101 @noindent
20102 In this case, the link name for @var{Var1} is whatever link name the
20103 C compiler would assign for the C function @var{var1_name}. This typically
20104 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20105 system conventions, but other possibilities exist. The link name for
20106 @var{Var2} is @var{var2_link_name}, and this is not operating system
20107 dependent.
20109 @findex _main
20110 One exception occurs for library level procedures. A potential ambiguity
20111 arises between the required name @code{_main} for the C main program,
20112 and the name we would otherwise assign to an Ada library level procedure
20113 called @code{Main} (which might well not be the main program).
20115 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20116 names. So if we have a library level procedure such as
20118 @smallexample @c ada
20119 @group
20120 @cartouche
20121 @b{procedure} Hello (S : String);
20122 @end cartouche
20123 @end group
20124 @end smallexample
20126 @noindent
20127 the external name of this procedure will be @var{_ada_hello}.
20130 @node Converting Ada Files to html with gnathtml
20131 @section Converting Ada Files to HTML with @code{gnathtml}
20133 @noindent
20134 This @code{Perl} script allows Ada source files to be browsed using
20135 standard Web browsers. For installation procedure, see the section
20136 @xref{Installing gnathtml}.
20138 Ada reserved keywords are highlighted in a bold font and Ada comments in
20139 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20140 switch to suppress the generation of cross-referencing information, user
20141 defined variables and types will appear in a different color; you will
20142 be able to click on any identifier and go to its declaration.
20144 The command line is as follow:
20145 @smallexample
20146 @c $ perl gnathtml.pl @ovar{switches} @var{ada-files}
20147 @c Expanding @ovar macro inline (explanation in macro def comments)
20148 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{ada-files}
20149 @end smallexample
20151 @noindent
20152 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20153 an html file for every ada file, and a global file called @file{index.htm}.
20154 This file is an index of every identifier defined in the files.
20156 The available switches are the following ones:
20158 @table @option
20159 @item -83
20160 @cindex @option{-83} (@code{gnathtml})
20161 Only the Ada 83 subset of keywords will be highlighted.
20163 @item -cc @var{color}
20164 @cindex @option{-cc} (@code{gnathtml})
20165 This option allows you to change the color used for comments. The default
20166 value is green. The color argument can be any name accepted by html.
20168 @item -d
20169 @cindex @option{-d} (@code{gnathtml})
20170 If the Ada files depend on some other files (for instance through
20171 @code{with} clauses, the latter files will also be converted to html.
20172 Only the files in the user project will be converted to html, not the files
20173 in the run-time library itself.
20175 @item -D
20176 @cindex @option{-D} (@code{gnathtml})
20177 This command is the same as @option{-d} above, but @command{gnathtml} will
20178 also look for files in the run-time library, and generate html files for them.
20180 @item -ext @var{extension}
20181 @cindex @option{-ext} (@code{gnathtml})
20182 This option allows you to change the extension of the generated HTML files.
20183 If you do not specify an extension, it will default to @file{htm}.
20185 @item -f
20186 @cindex @option{-f} (@code{gnathtml})
20187 By default, gnathtml will generate html links only for global entities
20188 ('with'ed units, global variables and types,@dots{}).  If you specify
20189 @option{-f} on the command line, then links will be generated for local
20190 entities too.
20192 @item -l @var{number}
20193 @cindex @option{-l} (@code{gnathtml})
20194 If this switch is provided and @var{number} is not 0, then
20195 @code{gnathtml} will number the html files every @var{number} line.
20197 @item -I @var{dir}
20198 @cindex @option{-I} (@code{gnathtml})
20199 Specify a directory to search for library files (@file{.ALI} files) and
20200 source files. You can provide several -I switches on the command line,
20201 and the directories will be parsed in the order of the command line.
20203 @item -o @var{dir}
20204 @cindex @option{-o} (@code{gnathtml})
20205 Specify the output directory for html files. By default, gnathtml will
20206 saved the generated html files in a subdirectory named @file{html/}.
20208 @item -p @var{file}
20209 @cindex @option{-p} (@code{gnathtml})
20210 If you are using Emacs and the most recent Emacs Ada mode, which provides
20211 a full Integrated Development Environment for compiling, checking,
20212 running and debugging applications, you may use @file{.gpr} files
20213 to give the directories where Emacs can find sources and object files.
20215 Using this switch, you can tell gnathtml to use these files.
20216 This allows you to get an html version of your application, even if it
20217 is spread over multiple directories.
20219 @item -sc @var{color}
20220 @cindex @option{-sc} (@code{gnathtml})
20221 This switch allows you to change the color used for symbol
20222 definitions.
20223 The default value is red. The color argument can be any name accepted by html.
20225 @item -t @var{file}
20226 @cindex @option{-t} (@code{gnathtml})
20227 This switch provides the name of a file. This file contains a list of
20228 file names to be converted, and the effect is exactly as though they had
20229 appeared explicitly on the command line. This
20230 is the recommended way to work around the command line length limit on some
20231 systems.
20233 @end table
20235 @node Installing gnathtml
20236 @section Installing @code{gnathtml}
20238 @noindent
20239 @code{Perl} needs to be installed on your machine to run this script.
20240 @code{Perl} is freely available for almost every architecture and
20241 Operating System via the Internet.
20243 On Unix systems, you  may want to modify  the  first line of  the script
20244 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
20245 is. The syntax of this line is:
20246 @smallexample
20247 #!full_path_name_to_perl
20248 @end smallexample
20250 @noindent
20251 Alternatively, you may run the script using the following command line:
20253 @smallexample
20254 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20255 @c Expanding @ovar macro inline (explanation in macro def comments)
20256 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20257 @end smallexample
20260 @c ******************************
20261 @node Code Coverage and Profiling
20262 @chapter Code Coverage and Profiling
20263 @cindex Code Coverage
20264 @cindex Profiling
20266 @noindent
20267 This chapter describes how to use @code{gcov} - coverage testing tool - and
20268 @code{gprof} - profiler tool - on your Ada programs.
20270 @menu
20271 * Code Coverage of Ada Programs with gcov::
20272 * Profiling an Ada Program with gprof::
20273 @end menu
20275 @node Code Coverage of Ada Programs with gcov
20276 @section Code Coverage of Ada Programs with gcov
20277 @cindex gcov
20278 @cindex -fprofile-arcs
20279 @cindex -ftest-coverage
20280 @cindex -coverage
20281 @cindex Code Coverage
20283 @noindent
20284 @code{gcov} is a test coverage program: it analyzes the execution of a given
20285 program on selected tests, to help you determine the portions of the program
20286 that are still untested.
20288 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20289 User's Guide. You can refer to this documentation for a more complete
20290 description.
20292 This chapter provides a quick startup guide, and
20293 details some Gnat-specific features.
20295 @menu
20296 * Quick startup guide::
20297 * Gnat specifics::
20298 @end menu
20300 @node Quick startup guide
20301 @subsection Quick startup guide
20303 In order to perform coverage analysis of a program using @code{gcov}, 3
20304 steps are needed:
20306 @itemize @bullet
20307 @item
20308 Code instrumentation during the compilation process
20309 @item
20310 Execution of the instrumented program
20311 @item
20312 Execution of the @code{gcov} tool to generate the result.
20313 @end itemize
20315 The code instrumentation needed by gcov is created at the object level:
20316 The source code is not modified in any way, because the instrumentation code is
20317 inserted by gcc during the compilation process. To compile your code with code
20318 coverage activated, you need to recompile your whole project using the
20319 switches
20320 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20321 @code{-fprofile-arcs}.
20323 @smallexample
20324 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20325    -largs -fprofile-arcs
20326 @end smallexample
20328 This compilation process will create @file{.gcno} files together with
20329 the usual object files.
20331 Once the program is compiled with coverage instrumentation, you can
20332 run it as many times as needed - on portions of a test suite for
20333 example. The first execution will produce @file{.gcda} files at the
20334 same location as the @file{.gcno} files.  The following executions
20335 will update those files, so that a cumulative result of the covered
20336 portions of the program is generated.
20338 Finally, you need to call the @code{gcov} tool. The different options of
20339 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20341 This will create annotated source files with a @file{.gcov} extension:
20342 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20344 @node Gnat specifics
20345 @subsection Gnat specifics
20347 Because Ada semantics, portions of the source code may be shared among
20348 several object files. This is the case for example when generics are
20349 involved, when inlining is active  or when declarations generate  initialisation
20350 calls. In order to take
20351 into account this shared code, you need to call @code{gcov} on all
20352 source files of the tested program at once.
20354 The list of source files might exceed the system's maximum command line
20355 length. In order to bypass this limitation, a new mechanism has been
20356 implemented in @code{gcov}: you can now list all your project's files into a
20357 text file, and provide this file to gcov as a parameter,  preceded by a @@
20358 (e.g. @samp{gcov @@mysrclist.txt}).
20360 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20361 not supported as there can be unresolved symbols during the final link.
20363 @node Profiling an Ada Program with gprof
20364 @section Profiling an Ada Program with gprof
20365 @cindex gprof
20366 @cindex -pg
20367 @cindex Profiling
20369 @noindent
20370 This section is not meant to be an exhaustive documentation of @code{gprof}.
20371 Full documentation for it can be found in the GNU Profiler User's Guide
20372 documentation that is part of this GNAT distribution.
20374 Profiling a program helps determine the parts of a program that are executed
20375 most often, and are therefore the most time-consuming.
20377 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20378 better handle Ada programs and multitasking.
20379 It is currently supported on the following platforms
20380 @itemize @bullet
20381 @item
20382 linux x86/x86_64
20383 @item
20384 solaris sparc/sparc64/x86
20385 @item
20386 windows x86
20387 @end itemize
20389 @noindent
20390 In order to profile a program using @code{gprof}, 3 steps are needed:
20392 @itemize @bullet
20393 @item
20394 Code instrumentation, requiring a full recompilation of the project with the
20395 proper switches.
20396 @item
20397 Execution of the program under the analysis conditions, i.e. with the desired
20398 input.
20399 @item
20400 Analysis of the results using the @code{gprof} tool.
20401 @end itemize
20403 @noindent
20404 The following sections detail the different steps, and indicate how
20405 to interpret the results:
20406 @menu
20407 * Compilation for profiling::
20408 * Program execution::
20409 * Running gprof::
20410 * Interpretation of profiling results::
20411 @end menu
20413 @node Compilation for profiling
20414 @subsection Compilation for profiling
20415 @cindex -pg
20416 @cindex Profiling
20418 In order to profile a program the first step is to tell the compiler
20419 to generate the necessary profiling information. The compiler switch to be used
20420 is @code{-pg}, which must be added to other compilation switches. This
20421 switch needs to be specified both during compilation and link stages, and can
20422 be specified once when using gnatmake:
20424 @smallexample
20425 gnatmake -f -pg -P my_project
20426 @end smallexample
20428 @noindent
20429 Note that only the objects that were compiled with the @samp{-pg} switch will
20430 be profiled; if you need to profile your whole project, use the @samp{-f}
20431 gnatmake switch to force full recompilation.
20433 @node Program execution
20434 @subsection Program execution
20436 @noindent
20437 Once the program has been compiled for profiling, you can run it as usual.
20439 The only constraint imposed by profiling is that the program must terminate
20440 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20441 properly analyzed.
20443 Once the program completes execution, a data file called @file{gmon.out} is
20444 generated in the directory where the program was launched from. If this file
20445 already exists, it will be overwritten.
20447 @node Running gprof
20448 @subsection Running gprof
20450 @noindent
20451 The @code{gprof} tool is called as follow:
20453 @smallexample
20454 gprof my_prog gmon.out
20455 @end smallexample
20457 @noindent
20458 or simpler:
20460 @smallexample
20461 gprof my_prog
20462 @end smallexample
20464 @noindent
20465 The complete form of the gprof command line is the following:
20467 @smallexample
20468 gprof [switches] [executable [data-file]]
20469 @end smallexample
20471 @noindent
20472 @code{gprof} supports numerous switch. The order of these
20473 switch does not matter. The full list of options can be found in
20474 the GNU Profiler User's Guide documentation that comes with this documentation.
20476 The following is the subset of those switches that is most relevant:
20478 @table @option
20480 @item --demangle[=@var{style}]
20481 @itemx --no-demangle
20482 @cindex @option{--demangle} (@code{gprof})
20483 These options control whether symbol names should be demangled when
20484 printing output.  The default is to demangle C++ symbols.  The
20485 @code{--no-demangle} option may be used to turn off demangling. Different
20486 compilers have different mangling styles.  The optional demangling style
20487 argument can be used to choose an appropriate demangling style for your
20488 compiler, in particular Ada symbols generated by GNAT can be demangled using
20489 @code{--demangle=gnat}.
20491 @item -e @var{function_name}
20492 @cindex @option{-e} (@code{gprof})
20493 The @samp{-e @var{function}} option tells @code{gprof} not to print
20494 information about the function @var{function_name} (and its
20495 children@dots{}) in the call graph.  The function will still be listed
20496 as a child of any functions that call it, but its index number will be
20497 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
20498 given; only one @var{function_name} may be indicated with each @samp{-e}
20499 option.
20501 @item -E @var{function_name}
20502 @cindex @option{-E} (@code{gprof})
20503 The @code{-E @var{function}} option works like the @code{-e} option, but
20504 execution time spent in the function (and children who were not called from
20505 anywhere else), will not be used to compute the percentages-of-time for
20506 the call graph.  More than one @samp{-E} option may be given; only one
20507 @var{function_name} may be indicated with each @samp{-E} option.
20509 @item -f @var{function_name}
20510 @cindex @option{-f} (@code{gprof})
20511 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20512 call graph to the function @var{function_name} and its children (and
20513 their children@dots{}).  More than one @samp{-f} option may be given;
20514 only one @var{function_name} may be indicated with each @samp{-f}
20515 option.
20517 @item -F @var{function_name}
20518 @cindex @option{-F} (@code{gprof})
20519 The @samp{-F @var{function}} option works like the @code{-f} option, but
20520 only time spent in the function and its children (and their
20521 children@dots{}) will be used to determine total-time and
20522 percentages-of-time for the call graph.  More than one @samp{-F} option
20523 may be given; only one @var{function_name} may be indicated with each
20524 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
20526 @end table
20528 @node Interpretation of profiling results
20529 @subsection Interpretation of profiling results
20531 @noindent
20533 The results of the profiling analysis are represented by two arrays: the
20534 'flat profile' and the 'call graph'. Full documentation of those outputs
20535 can be found in the GNU Profiler User's Guide.
20537 The flat profile shows the time spent in each function of the program, and how
20538 many time it has been called. This allows you to locate easily the most
20539 time-consuming functions.
20541 The call graph shows, for each subprogram, the subprograms that call it,
20542 and the subprograms that it calls. It also provides an estimate of the time
20543 spent in each of those callers/called subprograms.
20545 @c ******************************
20546 @node Running and Debugging Ada Programs
20547 @chapter Running and Debugging Ada Programs
20548 @cindex Debugging
20550 @noindent
20551 This chapter discusses how to debug Ada programs.
20553 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20555 @enumerate
20556 @item
20557 The illegality may be a violation of the static semantics of Ada. In
20558 that case GNAT diagnoses the constructs in the program that are illegal.
20559 It is then a straightforward matter for the user to modify those parts of
20560 the program.
20562 @item
20563 The illegality may be a violation of the dynamic semantics of Ada. In
20564 that case the program compiles and executes, but may generate incorrect
20565 results, or may terminate abnormally with some exception.
20567 @item
20568 When presented with a program that contains convoluted errors, GNAT
20569 itself may terminate abnormally without providing full diagnostics on
20570 the incorrect user program.
20571 @end enumerate
20573 @menu
20574 * The GNAT Debugger GDB::
20575 * Running GDB::
20576 * Introduction to GDB Commands::
20577 * Using Ada Expressions::
20578 * Calling User-Defined Subprograms::
20579 * Using the Next Command in a Function::
20580 * Ada Exceptions::
20581 * Ada Tasks::
20582 * Debugging Generic Units::
20583 * Remote Debugging with gdbserver::
20584 * GNAT Abnormal Termination or Failure to Terminate::
20585 * Naming Conventions for GNAT Source Files::
20586 * Getting Internal Debugging Information::
20587 * Stack Traceback::
20588 @end menu
20590 @cindex Debugger
20591 @findex gdb
20593 @node The GNAT Debugger GDB
20594 @section The GNAT Debugger GDB
20596 @noindent
20597 @code{GDB} is a general purpose, platform-independent debugger that
20598 can be used to debug mixed-language programs compiled with @command{gcc},
20599 and in particular is capable of debugging Ada programs compiled with
20600 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20601 complex Ada data structures.
20603 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20604 for full details on the usage of @code{GDB}, including a section on
20605 its usage on programs. This manual should be consulted for full
20606 details. The section that follows is a brief introduction to the
20607 philosophy and use of @code{GDB}.
20609 When GNAT programs are compiled, the compiler optionally writes debugging
20610 information into the generated object file, including information on
20611 line numbers, and on declared types and variables. This information is
20612 separate from the generated code. It makes the object files considerably
20613 larger, but it does not add to the size of the actual executable that
20614 will be loaded into memory, and has no impact on run-time performance. The
20615 generation of debug information is triggered by the use of the
20616 -g switch in the @command{gcc} or @command{gnatmake} command
20617 used to carry out the compilations. It is important to emphasize that
20618 the use of these options does not change the generated code.
20620 The debugging information is written in standard system formats that
20621 are used by many tools, including debuggers and profilers. The format
20622 of the information is typically designed to describe C types and
20623 semantics, but GNAT implements a translation scheme which allows full
20624 details about Ada types and variables to be encoded into these
20625 standard C formats. Details of this encoding scheme may be found in
20626 the file exp_dbug.ads in the GNAT source distribution. However, the
20627 details of this encoding are, in general, of no interest to a user,
20628 since @code{GDB} automatically performs the necessary decoding.
20630 When a program is bound and linked, the debugging information is
20631 collected from the object files, and stored in the executable image of
20632 the program. Again, this process significantly increases the size of
20633 the generated executable file, but it does not increase the size of
20634 the executable program itself. Furthermore, if this program is run in
20635 the normal manner, it runs exactly as if the debug information were
20636 not present, and takes no more actual memory.
20638 However, if the program is run under control of @code{GDB}, the
20639 debugger is activated.  The image of the program is loaded, at which
20640 point it is ready to run.  If a run command is given, then the program
20641 will run exactly as it would have if @code{GDB} were not present. This
20642 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
20643 entirely non-intrusive until a breakpoint is encountered.  If no
20644 breakpoint is ever hit, the program will run exactly as it would if no
20645 debugger were present. When a breakpoint is hit, @code{GDB} accesses
20646 the debugging information and can respond to user commands to inspect
20647 variables, and more generally to report on the state of execution.
20649 @c **************
20650 @node Running GDB
20651 @section Running GDB
20653 @noindent
20654 This section describes how to initiate the debugger.
20655 @c The above sentence is really just filler, but it was otherwise
20656 @c clumsy to get the first paragraph nonindented given the conditional
20657 @c nature of the description
20659 The debugger can be launched from a @code{GPS} menu or
20660 directly from the command line. The description below covers the latter use.
20661 All the commands shown can be used in the @code{GPS} debug console window,
20662 but there are usually more GUI-based ways to achieve the same effect.
20664 The command to run @code{GDB} is
20666 @smallexample
20667 $ gdb program
20668 @end smallexample
20670 @noindent
20671 where @code{program} is the name of the executable file. This
20672 activates the debugger and results in a prompt for debugger commands.
20673 The simplest command is simply @code{run}, which causes the program to run
20674 exactly as if the debugger were not present. The following section
20675 describes some of the additional commands that can be given to @code{GDB}.
20677 @c *******************************
20678 @node Introduction to GDB Commands
20679 @section Introduction to GDB Commands
20681 @noindent
20682 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
20683 Debugging with GDB, gdb, Debugging with GDB},
20684 for extensive documentation on the use
20685 of these commands, together with examples of their use. Furthermore,
20686 the command @command{help} invoked from within GDB activates a simple help
20687 facility which summarizes the available commands and their options.
20688 In this section we summarize a few of the most commonly
20689 used commands to give an idea of what @code{GDB} is about. You should create
20690 a simple program with debugging information and experiment with the use of
20691 these @code{GDB} commands on the program as you read through the
20692 following section.
20694 @table @code
20695 @item set args @var{arguments}
20696 The @var{arguments} list above is a list of arguments to be passed to
20697 the program on a subsequent run command, just as though the arguments
20698 had been entered on a normal invocation of the program. The @code{set args}
20699 command is not needed if the program does not require arguments.
20701 @item run
20702 The @code{run} command causes execution of the program to start from
20703 the beginning. If the program is already running, that is to say if
20704 you are currently positioned at a breakpoint, then a prompt will ask
20705 for confirmation that you want to abandon the current execution and
20706 restart.
20708 @item breakpoint @var{location}
20709 The breakpoint command sets a breakpoint, that is to say a point at which
20710 execution will halt and @code{GDB} will await further
20711 commands. @var{location} is
20712 either a line number within a file, given in the format @code{file:linenumber},
20713 or it is the name of a subprogram. If you request that a breakpoint be set on
20714 a subprogram that is overloaded, a prompt will ask you to specify on which of
20715 those subprograms you want to breakpoint. You can also
20716 specify that all of them should be breakpointed. If the program is run
20717 and execution encounters the breakpoint, then the program
20718 stops and @code{GDB} signals that the breakpoint was encountered by
20719 printing the line of code before which the program is halted.
20721 @item catch exception @var{name}
20722 This command causes the program execution to stop whenever exception
20723 @var{name} is raised.  If @var{name} is omitted, then the execution is
20724 suspended when any exception is raised.
20726 @item print @var{expression}
20727 This will print the value of the given expression. Most simple
20728 Ada expression formats are properly handled by @code{GDB}, so the expression
20729 can contain function calls, variables, operators, and attribute references.
20731 @item continue
20732 Continues execution following a breakpoint, until the next breakpoint or the
20733 termination of the program.
20735 @item step
20736 Executes a single line after a breakpoint. If the next statement
20737 is a subprogram call, execution continues into (the first statement of)
20738 the called subprogram.
20740 @item next
20741 Executes a single line. If this line is a subprogram call, executes and
20742 returns from the call.
20744 @item list
20745 Lists a few lines around the current source location. In practice, it
20746 is usually more convenient to have a separate edit window open with the
20747 relevant source file displayed. Successive applications of this command
20748 print subsequent lines. The command can be given an argument which is a
20749 line number, in which case it displays a few lines around the specified one.
20751 @item backtrace
20752 Displays a backtrace of the call chain. This command is typically
20753 used after a breakpoint has occurred, to examine the sequence of calls that
20754 leads to the current breakpoint. The display includes one line for each
20755 activation record (frame) corresponding to an active subprogram.
20757 @item up
20758 At a breakpoint, @code{GDB} can display the values of variables local
20759 to the current frame. The command @code{up} can be used to
20760 examine the contents of other active frames, by moving the focus up
20761 the stack, that is to say from callee to caller, one frame at a time.
20763 @item down
20764 Moves the focus of @code{GDB} down from the frame currently being
20765 examined to the frame of its callee (the reverse of the previous command),
20767 @item frame @var{n}
20768 Inspect the frame with the given number. The value 0 denotes the frame
20769 of the current breakpoint, that is to say the top of the call stack.
20771 @item kill
20772 Kills the child process in which the program is running under GDB.
20773 This may be useful for several purposes:
20774 @itemize @bullet
20775 @item
20776 It allows you to recompile and relink your program, since on many systems
20777 you cannot regenerate an executable file while it is running in a process.
20778 @item
20779 You can run your program outside the debugger, on systems that do not
20780 permit executing a program outside GDB while breakpoints are set
20781 within GDB.
20782 @item
20783 It allows you to debug a core dump rather than a running process.
20784 @end itemize
20785 @end table
20787 @noindent
20788 The above list is a very short introduction to the commands that
20789 @code{GDB} provides. Important additional capabilities, including conditional
20790 breakpoints, the ability to execute command sequences on a breakpoint,
20791 the ability to debug at the machine instruction level and many other
20792 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20793 Debugging with GDB}.  Note that most commands can be abbreviated
20794 (for example, c for continue, bt for backtrace).
20796 @node Using Ada Expressions
20797 @section Using Ada Expressions
20798 @cindex Ada expressions
20800 @noindent
20801 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20802 extensions. The philosophy behind the design of this subset is
20804 @itemize @bullet
20805 @item
20806 That @code{GDB} should provide basic literals and access to operations for
20807 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
20808 leaving more sophisticated computations to subprograms written into the
20809 program (which therefore may be called from @code{GDB}).
20811 @item
20812 That type safety and strict adherence to Ada language restrictions
20813 are not particularly important to the @code{GDB} user.
20815 @item
20816 That brevity is important to the @code{GDB} user.
20817 @end itemize
20819 @noindent
20820 Thus, for brevity, the debugger acts as if there were
20821 implicit @code{with} and @code{use} clauses in effect for all user-written
20822 packages, thus making it unnecessary to fully qualify most names with
20823 their packages, regardless of context. Where this causes ambiguity,
20824 @code{GDB} asks the user's intent.
20826 For details on the supported Ada syntax, see @ref{Top,, Debugging with
20827 GDB, gdb, Debugging with GDB}.
20829 @node Calling User-Defined Subprograms
20830 @section Calling User-Defined Subprograms
20832 @noindent
20833 An important capability of @code{GDB} is the ability to call user-defined
20834 subprograms while debugging. This is achieved simply by entering
20835 a subprogram call statement in the form:
20837 @smallexample
20838 call subprogram-name (parameters)
20839 @end smallexample
20841 @noindent
20842 The keyword @code{call} can be omitted in the normal case where the
20843 @code{subprogram-name} does not coincide with any of the predefined
20844 @code{GDB} commands.
20846 The effect is to invoke the given subprogram, passing it the
20847 list of parameters that is supplied. The parameters can be expressions and
20848 can include variables from the program being debugged. The
20849 subprogram must be defined
20850 at the library level within your program, and @code{GDB} will call the
20851 subprogram within the environment of your program execution (which
20852 means that the subprogram is free to access or even modify variables
20853 within your program).
20855 The most important use of this facility is in allowing the inclusion of
20856 debugging routines that are tailored to particular data structures
20857 in your program. Such debugging routines can be written to provide a suitably
20858 high-level description of an abstract type, rather than a low-level dump
20859 of its physical layout. After all, the standard
20860 @code{GDB print} command only knows the physical layout of your
20861 types, not their abstract meaning. Debugging routines can provide information
20862 at the desired semantic level and are thus enormously useful.
20864 For example, when debugging GNAT itself, it is crucial to have access to
20865 the contents of the tree nodes used to represent the program internally.
20866 But tree nodes are represented simply by an integer value (which in turn
20867 is an index into a table of nodes).
20868 Using the @code{print} command on a tree node would simply print this integer
20869 value, which is not very useful. But the PN routine (defined in file
20870 treepr.adb in the GNAT sources) takes a tree node as input, and displays
20871 a useful high level representation of the tree node, which includes the
20872 syntactic category of the node, its position in the source, the integers
20873 that denote descendant nodes and parent node, as well as varied
20874 semantic information. To study this example in more detail, you might want to
20875 look at the body of the PN procedure in the stated file.
20877 Another useful application of this capability is to deal with situations of
20878 complex data which are not handled suitably by GDB. For example, if you specify
20879 Convention Fortran for a multi-dimensional array, GDB does not know that
20880 the ordering of array elements has been switched and will not properly
20881 address the array elements. In such a case, instead of trying to print the
20882 elements directly from GDB, you can write a callable procedure that prints
20883 the elements in the desired format.
20885 @node Using the Next Command in a Function
20886 @section Using the Next Command in a Function
20888 @noindent
20889 When you use the @code{next} command in a function, the current source
20890 location will advance to the next statement as usual. A special case
20891 arises in the case of a @code{return} statement.
20893 Part of the code for a return statement is the ``epilogue'' of the function.
20894 This is the code that returns to the caller. There is only one copy of
20895 this epilogue code, and it is typically associated with the last return
20896 statement in the function if there is more than one return. In some
20897 implementations, this epilogue is associated with the first statement
20898 of the function.
20900 The result is that if you use the @code{next} command from a return
20901 statement that is not the last return statement of the function you
20902 may see a strange apparent jump to the last return statement or to
20903 the start of the function. You should simply ignore this odd jump.
20904 The value returned is always that from the first return statement
20905 that was stepped through.
20907 @node Ada Exceptions
20908 @section Stopping when Ada Exceptions are Raised
20909 @cindex Exceptions
20911 @noindent
20912 You can set catchpoints that stop the program execution when your program
20913 raises selected exceptions.
20915 @table @code
20916 @item catch exception
20917 Set a catchpoint that stops execution whenever (any task in the) program
20918 raises any exception.
20920 @item catch exception @var{name}
20921 Set a catchpoint that stops execution whenever (any task in the) program
20922 raises the exception @var{name}.
20924 @item catch exception unhandled
20925 Set a catchpoint that stops executing whenever (any task in the) program
20926 raises an exception for which there is no handler.
20928 @item info exceptions
20929 @itemx info exceptions @var{regexp}
20930 The @code{info exceptions} command permits the user to examine all defined
20931 exceptions within Ada programs. With a regular expression, @var{regexp}, as
20932 argument, prints out only those exceptions whose name matches @var{regexp}.
20933 @end table
20935 @node Ada Tasks
20936 @section Ada Tasks
20937 @cindex Tasks
20939 @noindent
20940 @code{GDB} allows the following task-related commands:
20942 @table @code
20943 @item info tasks
20944 This command shows a list of current Ada tasks, as in the following example:
20946 @smallexample
20947 @iftex
20948 @leftskip=0cm
20949 @end iftex
20950 (gdb) info tasks
20951   ID       TID P-ID   Thread Pri State                 Name
20952    1   8088000   0   807e000  15 Child Activation Wait main_task
20953    2   80a4000   1   80ae000  15 Accept/Select Wait    b
20954    3   809a800   1   80a4800  15 Child Activation Wait a
20955 *  4   80ae800   3   80b8000  15 Running               c
20956 @end smallexample
20958 @noindent
20959 In this listing, the asterisk before the first task indicates it to be the
20960 currently running task. The first column lists the task ID that is used
20961 to refer to tasks in the following commands.
20963 @item break @var{linespec} task @var{taskid}
20964 @itemx break @var{linespec} task @var{taskid} if @dots{}
20965 @cindex Breakpoints and tasks
20966 These commands are like the @code{break @dots{} thread @dots{}}.
20967 @var{linespec} specifies source lines.
20969 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
20970 to specify that you only want @code{GDB} to stop the program when a
20971 particular Ada task reaches this breakpoint. @var{taskid} is one of the
20972 numeric task identifiers assigned by @code{GDB}, shown in the first
20973 column of the @samp{info tasks} display.
20975 If you do not specify @samp{task @var{taskid}} when you set a
20976 breakpoint, the breakpoint applies to @emph{all} tasks of your
20977 program.
20979 You can use the @code{task} qualifier on conditional breakpoints as
20980 well; in this case, place @samp{task @var{taskid}} before the
20981 breakpoint condition (before the @code{if}).
20983 @item task @var{taskno}
20984 @cindex Task switching
20986 This command allows switching to the task referred by @var{taskno}. In
20987 particular, this allows browsing of the backtrace of the specified
20988 task. It is advisable to switch back to the original task before
20989 continuing execution otherwise the scheduling of the program may be
20990 perturbed.
20991 @end table
20993 @noindent
20994 For more detailed information on the tasking support,
20995 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
20997 @node Debugging Generic Units
20998 @section Debugging Generic Units
20999 @cindex Debugging Generic Units
21000 @cindex Generics
21002 @noindent
21003 GNAT always uses code expansion for generic instantiation. This means that
21004 each time an instantiation occurs, a complete copy of the original code is
21005 made, with appropriate substitutions of formals by actuals.
21007 It is not possible to refer to the original generic entities in
21008 @code{GDB}, but it is always possible to debug a particular instance of
21009 a generic, by using the appropriate expanded names. For example, if we have
21011 @smallexample @c ada
21012 @group
21013 @cartouche
21014 @b{procedure} g @b{is}
21016    @b{generic} @b{package} k @b{is}
21017       @b{procedure} kp (v1 : @b{in} @b{out} integer);
21018    @b{end} k;
21020    @b{package} @b{body} k @b{is}
21021       @b{procedure} kp (v1 : @b{in} @b{out} integer) @b{is}
21022       @b{begin}
21023          v1 := v1 + 1;
21024       @b{end} kp;
21025    @b{end} k;
21027    @b{package} k1 @b{is} @b{new} k;
21028    @b{package} k2 @b{is} @b{new} k;
21030    var : integer := 1;
21032 @b{begin}
21033    k1.kp (var);
21034    k2.kp (var);
21035    k1.kp (var);
21036    k2.kp (var);
21037 @b{end};
21038 @end cartouche
21039 @end group
21040 @end smallexample
21042 @noindent
21043 Then to break on a call to procedure kp in the k2 instance, simply
21044 use the command:
21046 @smallexample
21047 (gdb) break g.k2.kp
21048 @end smallexample
21050 @noindent
21051 When the breakpoint occurs, you can step through the code of the
21052 instance in the normal manner and examine the values of local variables, as for
21053 other units.
21055 @node Remote Debugging with gdbserver
21056 @section Remote Debugging with gdbserver
21057 @cindex Remote Debugging with gdbserver
21059 @noindent
21060 On platforms where gdbserver is supported, it is possible to use this tool
21061 to debug your application remotely.  This can be useful in situations
21062 where the program needs to be run on a target host that is different
21063 from the host used for development, particularly when the target has
21064 a limited amount of resources (either CPU and/or memory).
21066 To do so, start your program using gdbserver on the target machine.
21067 gdbserver then automatically suspends the execution of your program
21068 at its entry point, waiting for a debugger to connect to it.  The
21069 following commands starts an application and tells gdbserver to
21070 wait for a connection with the debugger on localhost port 4444.
21072 @smallexample
21073 $ gdbserver localhost:4444 program
21074 Process program created; pid = 5685
21075 Listening on port 4444
21076 @end smallexample
21078 Once gdbserver has started listening, we can tell the debugger to establish
21079 a connection with this gdbserver, and then start the same debugging session
21080 as if the program was being debugged on the same host, directly under
21081 the control of GDB.
21083 @smallexample
21084 $ gdb program
21085 (gdb) target remote targethost:4444
21086 Remote debugging using targethost:4444
21087 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21088 (gdb) b foo.adb:3
21089 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21090 (gdb) continue
21091 Continuing.
21093 Breakpoint 1, foo () at foo.adb:4
21094 4       end foo;
21095 @end smallexample
21097 It is also possible to use gdbserver to attach to an already running
21098 program, in which case the execution of that program is simply suspended
21099 until the connection between the debugger and gdbserver is established.
21101 For more information on how to use gdbserver, @ref{Top, Server, Using
21102 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
21103 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21105 @node GNAT Abnormal Termination or Failure to Terminate
21106 @section GNAT Abnormal Termination or Failure to Terminate
21107 @cindex GNAT Abnormal Termination or Failure to Terminate
21109 @noindent
21110 When presented with programs that contain serious errors in syntax
21111 or semantics,
21112 GNAT may on rare occasions  experience problems in operation, such
21113 as aborting with a
21114 segmentation fault or illegal memory access, raising an internal
21115 exception, terminating abnormally, or failing to terminate at all.
21116 In such cases, you can activate
21117 various features of GNAT that can help you pinpoint the construct in your
21118 program that is the likely source of the problem.
21120 The following strategies are presented in increasing order of
21121 difficulty, corresponding to your experience in using GNAT and your
21122 familiarity with compiler internals.
21124 @enumerate
21125 @item
21126 Run @command{gcc} with the @option{-gnatf}. This first
21127 switch causes all errors on a given line to be reported. In its absence,
21128 only the first error on a line is displayed.
21130 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21131 are encountered, rather than after compilation is terminated. If GNAT
21132 terminates prematurely or goes into an infinite loop, the last error
21133 message displayed may help to pinpoint the culprit.
21135 @item
21136 Run @command{gcc} with the @option{-v (verbose)} switch. In this
21137 mode, @command{gcc} produces ongoing information about the progress of the
21138 compilation and provides the name of each procedure as code is
21139 generated. This switch allows you to find which Ada procedure was being
21140 compiled when it encountered a code generation problem.
21142 @item
21143 @cindex @option{-gnatdc} switch
21144 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21145 switch that does for the front-end what @option{-v} does
21146 for the back end. The system prints the name of each unit,
21147 either a compilation unit or nested unit, as it is being analyzed.
21148 @item
21149 Finally, you can start
21150 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21151 front-end of GNAT, and can be run independently (normally it is just
21152 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21153 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21154 @code{where} command is the first line of attack; the variable
21155 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21156 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21157 which the execution stopped, and @code{input_file name} indicates the name of
21158 the source file.
21159 @end enumerate
21161 @node Naming Conventions for GNAT Source Files
21162 @section Naming Conventions for GNAT Source Files
21164 @noindent
21165 In order to examine the workings of the GNAT system, the following
21166 brief description of its organization may be helpful:
21168 @itemize @bullet
21169 @item
21170 Files with prefix @file{sc} contain the lexical scanner.
21172 @item
21173 All files prefixed with @file{par} are components of the parser. The
21174 numbers correspond to chapters of the Ada Reference Manual. For example,
21175 parsing of select statements can be found in @file{par-ch9.adb}.
21177 @item
21178 All files prefixed with @file{sem} perform semantic analysis. The
21179 numbers correspond to chapters of the Ada standard. For example, all
21180 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21181 addition, some features of the language require sufficient special processing
21182 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21183 dynamic dispatching, etc.
21185 @item
21186 All files prefixed with @file{exp} perform normalization and
21187 expansion of the intermediate representation (abstract syntax tree, or AST).
21188 these files use the same numbering scheme as the parser and semantics files.
21189 For example, the construction of record initialization procedures is done in
21190 @file{exp_ch3.adb}.
21192 @item
21193 The files prefixed with @file{bind} implement the binder, which
21194 verifies the consistency of the compilation, determines an order of
21195 elaboration, and generates the bind file.
21197 @item
21198 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21199 data structures used by the front-end.
21201 @item
21202 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21203 the abstract syntax tree as produced by the parser.
21205 @item
21206 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21207 all entities, computed during semantic analysis.
21209 @item
21210 Library management issues are dealt with in files with prefix
21211 @file{lib}.
21213 @item
21214 @findex Ada
21215 @cindex Annex A
21216 Ada files with the prefix @file{a-} are children of @code{Ada}, as
21217 defined in Annex A.
21219 @item
21220 @findex Interfaces
21221 @cindex Annex B
21222 Files with prefix @file{i-} are children of @code{Interfaces}, as
21223 defined in Annex B.
21225 @item
21226 @findex System
21227 Files with prefix @file{s-} are children of @code{System}. This includes
21228 both language-defined children and GNAT run-time routines.
21230 @item
21231 @findex GNAT
21232 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
21233 general-purpose packages, fully documented in their specs. All
21234 the other @file{.c} files are modifications of common @command{gcc} files.
21235 @end itemize
21237 @node Getting Internal Debugging Information
21238 @section Getting Internal Debugging Information
21240 @noindent
21241 Most compilers have internal debugging switches and modes. GNAT
21242 does also, except GNAT internal debugging switches and modes are not
21243 secret. A summary and full description of all the compiler and binder
21244 debug flags are in the file @file{debug.adb}. You must obtain the
21245 sources of the compiler to see the full detailed effects of these flags.
21247 The switches that print the source of the program (reconstructed from
21248 the internal tree) are of general interest for user programs, as are the
21249 options to print
21250 the full internal tree, and the entity table (the symbol table
21251 information). The reconstructed source provides a readable version of the
21252 program after the front-end has completed analysis and  expansion,
21253 and is useful when studying the performance of specific constructs.
21254 For example, constraint checks are indicated, complex aggregates
21255 are replaced with loops and assignments, and tasking primitives
21256 are replaced with run-time calls.
21258 @node Stack Traceback
21259 @section Stack Traceback
21260 @cindex traceback
21261 @cindex stack traceback
21262 @cindex stack unwinding
21264 @noindent
21265 Traceback is a mechanism to display the sequence of subprogram calls that
21266 leads to a specified execution point in a program. Often (but not always)
21267 the execution point is an instruction at which an exception has been raised.
21268 This mechanism is also known as @i{stack unwinding} because it obtains
21269 its information by scanning the run-time stack and recovering the activation
21270 records of all active subprograms. Stack unwinding is one of the most
21271 important tools for program debugging.
21273 The first entry stored in traceback corresponds to the deepest calling level,
21274 that is to say the subprogram currently executing the instruction
21275 from which we want to obtain the traceback.
21277 Note that there is no runtime performance penalty when stack traceback
21278 is enabled, and no exception is raised during program execution.
21280 @menu
21281 * Non-Symbolic Traceback::
21282 * Symbolic Traceback::
21283 @end menu
21285 @node Non-Symbolic Traceback
21286 @subsection Non-Symbolic Traceback
21287 @cindex traceback, non-symbolic
21289 @noindent
21290 Note: this feature is not supported on all platforms. See
21291 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21292 platforms.
21294 @menu
21295 * Tracebacks From an Unhandled Exception::
21296 * Tracebacks From Exception Occurrences (non-symbolic)::
21297 * Tracebacks From Anywhere in a Program (non-symbolic)::
21298 @end menu
21300 @node Tracebacks From an Unhandled Exception
21301 @subsubsection Tracebacks From an Unhandled Exception
21303 @noindent
21304 A runtime non-symbolic traceback is a list of addresses of call instructions.
21305 To enable this feature you must use the @option{-E}
21306 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21307 of exception information. You can retrieve this information using the
21308 @code{addr2line} tool.
21310 Here is a simple example:
21312 @smallexample @c ada
21313 @cartouche
21314 @b{procedure} STB @b{is}
21316    @b{procedure} P1 @b{is}
21317    @b{begin}
21318       @b{raise} Constraint_Error;
21319    @b{end} P1;
21321    @b{procedure} P2 @b{is}
21322    @b{begin}
21323       P1;
21324    @b{end} P2;
21326 @b{begin}
21327    P2;
21328 @b{end} STB;
21329 @end cartouche
21330 @end smallexample
21332 @smallexample
21333 $ gnatmake stb -bargs -E
21334 $ stb
21336 Execution terminated by unhandled exception
21337 Exception name: CONSTRAINT_ERROR
21338 Message: stb.adb:5
21339 Call stack traceback locations:
21340 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21341 @end smallexample
21343 @noindent
21344 As we see the traceback lists a sequence of addresses for the unhandled
21345 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21346 guess that this exception come from procedure P1. To translate these
21347 addresses into the source lines where the calls appear, the
21348 @code{addr2line} tool, described below, is invaluable. The use of this tool
21349 requires the program to be compiled with debug information.
21351 @smallexample
21352 $ gnatmake -g stb -bargs -E
21353 $ stb
21355 Execution terminated by unhandled exception
21356 Exception name: CONSTRAINT_ERROR
21357 Message: stb.adb:5
21358 Call stack traceback locations:
21359 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21361 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21362    0x4011f1 0x77e892a4
21364 00401373 at d:/stb/stb.adb:5
21365 0040138B at d:/stb/stb.adb:10
21366 0040139C at d:/stb/stb.adb:14
21367 00401335 at d:/stb/b~stb.adb:104
21368 004011C4 at /build/@dots{}/crt1.c:200
21369 004011F1 at /build/@dots{}/crt1.c:222
21370 77E892A4 in ?? at ??:0
21371 @end smallexample
21373 @noindent
21374 The @code{addr2line} tool has several other useful options:
21376 @table @code
21377 @item --functions
21378 to get the function name corresponding to any location
21380 @item --demangle=gnat
21381 to use the gnat decoding mode for the function names. Note that
21382 for binutils version 2.9.x the option is simply @option{--demangle}.
21383 @end table
21385 @smallexample
21386 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21387    0x40139c 0x401335 0x4011c4 0x4011f1
21389 00401373 in stb.p1 at d:/stb/stb.adb:5
21390 0040138B in stb.p2 at d:/stb/stb.adb:10
21391 0040139C in stb at d:/stb/stb.adb:14
21392 00401335 in main at d:/stb/b~stb.adb:104
21393 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21394 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21395 @end smallexample
21397 @noindent
21398 From this traceback we can see that the exception was raised in
21399 @file{stb.adb} at line 5, which was reached from a procedure call in
21400 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21401 which contains the call to the main program.
21402 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21403 and the output will vary from platform to platform.
21405 It is also possible to use @code{GDB} with these traceback addresses to debug
21406 the program. For example, we can break at a given code location, as reported
21407 in the stack traceback:
21409 @smallexample
21410 $ gdb -nw stb
21411 @noindent
21412 Furthermore, this feature is not implemented inside Windows DLL. Only
21413 the non-symbolic traceback is reported in this case.
21415 (gdb) break *0x401373
21416 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21417 @end smallexample
21419 @noindent
21420 It is important to note that the stack traceback addresses
21421 do not change when debug information is included. This is particularly useful
21422 because it makes it possible to release software without debug information (to
21423 minimize object size), get a field report that includes a stack traceback
21424 whenever an internal bug occurs, and then be able to retrieve the sequence
21425 of calls with the same program compiled with debug information.
21427 @node Tracebacks From Exception Occurrences (non-symbolic)
21428 @subsubsection Tracebacks From Exception Occurrences
21430 @noindent
21431 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21432 The stack traceback is attached to the exception information string, and can
21433 be retrieved in an exception handler within the Ada program, by means of the
21434 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21436 @smallexample @c ada
21437 @b{with} Ada.Text_IO;
21438 @b{with} Ada.Exceptions;
21440 @b{procedure} STB @b{is}
21442    @b{use} Ada;
21443    @b{use} Ada.Exceptions;
21445    @b{procedure} P1 @b{is}
21446       K : Positive := 1;
21447    @b{begin}
21448       K := K - 1;
21449    @b{exception}
21450       @b{when} E : @b{others} =>
21451          Text_IO.Put_Line (Exception_Information (E));
21452    @b{end} P1;
21454    @b{procedure} P2 @b{is}
21455    @b{begin}
21456       P1;
21457    @b{end} P2;
21459 @b{begin}
21460    P2;
21461 @b{end} STB;
21462 @end smallexample
21464 @noindent
21465 This program will output:
21467 @smallexample
21468 $ stb
21470 Exception name: CONSTRAINT_ERROR
21471 Message: stb.adb:12
21472 Call stack traceback locations:
21473 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21474 @end smallexample
21476 @node Tracebacks From Anywhere in a Program (non-symbolic)
21477 @subsubsection Tracebacks From Anywhere in a Program
21479 @noindent
21480 It is also possible to retrieve a stack traceback from anywhere in a
21481 program. For this you need to
21482 use the @code{GNAT.Traceback} API. This package includes a procedure called
21483 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21484 display procedures described below. It is not necessary to use the
21485 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21486 is invoked explicitly.
21488 @noindent
21489 In the following example we compute a traceback at a specific location in
21490 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21491 convert addresses to strings:
21493 @smallexample @c ada
21494 @b{with} Ada.Text_IO;
21495 @b{with} GNAT.Traceback;
21496 @b{with} GNAT.Debug_Utilities;
21498 @b{procedure} STB @b{is}
21500    @b{use} Ada;
21501    @b{use} GNAT;
21502    @b{use} GNAT.Traceback;
21504    @b{procedure} P1 @b{is}
21505       TB  : Tracebacks_Array (1 .. 10);
21506       --@i{  We are asking for a maximum of 10 stack frames.}
21507       Len : Natural;
21508       --@i{  Len will receive the actual number of stack frames returned.}
21509    @b{begin}
21510       Call_Chain (TB, Len);
21512       Text_IO.Put ("In STB.P1 : ");
21514       @b{for} K @b{in} 1 .. Len @b{loop}
21515          Text_IO.Put (Debug_Utilities.Image (TB (K)));
21516          Text_IO.Put (' ');
21517       @b{end} @b{loop};
21519       Text_IO.New_Line;
21520    @b{end} P1;
21522    @b{procedure} P2 @b{is}
21523    @b{begin}
21524       P1;
21525    @b{end} P2;
21527 @b{begin}
21528    P2;
21529 @b{end} STB;
21530 @end smallexample
21532 @smallexample
21533 $ gnatmake -g stb
21534 $ stb
21536 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21537 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21538 @end smallexample
21540 @noindent
21541 You can then get further information by invoking the @code{addr2line}
21542 tool as described earlier (note that the hexadecimal addresses
21543 need to be specified in C format, with a leading ``0x'').
21545 @node Symbolic Traceback
21546 @subsection Symbolic Traceback
21547 @cindex traceback, symbolic
21549 @noindent
21550 A symbolic traceback is a stack traceback in which procedure names are
21551 associated with each code location.
21553 @noindent
21554 Note that this feature is not supported on all platforms. See
21555 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21556 list of currently supported platforms.
21558 @noindent
21559 Note that the symbolic traceback requires that the program be compiled
21560 with debug information. If it is not compiled with debug information
21561 only the non-symbolic information will be valid.
21563 @menu
21564 * Tracebacks From Exception Occurrences (symbolic)::
21565 * Tracebacks From Anywhere in a Program (symbolic)::
21566 @end menu
21568 @node Tracebacks From Exception Occurrences (symbolic)
21569 @subsubsection Tracebacks From Exception Occurrences
21571 @smallexample @c ada
21572 @b{with} Ada.Text_IO;
21573 @b{with} GNAT.Traceback.Symbolic;
21575 @b{procedure} STB @b{is}
21577    @b{procedure} P1 @b{is}
21578    @b{begin}
21579       @b{raise} Constraint_Error;
21580    @b{end} P1;
21582    @b{procedure} P2 @b{is}
21583    @b{begin}
21584       P1;
21585    @b{end} P2;
21587    @b{procedure} P3 @b{is}
21588    @b{begin}
21589       P2;
21590    @b{end} P3;
21592 @b{begin}
21593    P3;
21594 @b{exception}
21595    @b{when} E : @b{others} =>
21596       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21597 @b{end} STB;
21598 @end smallexample
21600 @smallexample
21601 $ gnatmake -g .\stb -bargs -E
21602 $ stb
21604 0040149F in stb.p1 at stb.adb:8
21605 004014B7 in stb.p2 at stb.adb:13
21606 004014CF in stb.p3 at stb.adb:18
21607 004015DD in ada.stb at stb.adb:22
21608 00401461 in main at b~stb.adb:168
21609 004011C4 in __mingw_CRTStartup at crt1.c:200
21610 004011F1 in mainCRTStartup at crt1.c:222
21611 77E892A4 in ?? at ??:0
21612 @end smallexample
21614 @noindent
21615 In the above example the ``.\'' syntax in the @command{gnatmake} command
21616 is currently required by @command{addr2line} for files that are in
21617 the current working directory.
21618 Moreover, the exact sequence of linker options may vary from platform
21619 to platform.
21620 The above @option{-largs} section is for Windows platforms. By contrast,
21621 under Unix there is no need for the @option{-largs} section.
21622 Differences across platforms are due to details of linker implementation.
21624 @node Tracebacks From Anywhere in a Program (symbolic)
21625 @subsubsection Tracebacks From Anywhere in a Program
21627 @noindent
21628 It is possible to get a symbolic stack traceback
21629 from anywhere in a program, just as for non-symbolic tracebacks.
21630 The first step is to obtain a non-symbolic
21631 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21632 information. Here is an example:
21634 @smallexample @c ada
21635 @b{with} Ada.Text_IO;
21636 @b{with} GNAT.Traceback;
21637 @b{with} GNAT.Traceback.Symbolic;
21639 @b{procedure} STB @b{is}
21641    @b{use} Ada;
21642    @b{use} GNAT.Traceback;
21643    @b{use} GNAT.Traceback.Symbolic;
21645    @b{procedure} P1 @b{is}
21646       TB  : Tracebacks_Array (1 .. 10);
21647       --@i{  We are asking for a maximum of 10 stack frames.}
21648       Len : Natural;
21649       --@i{  Len will receive the actual number of stack frames returned.}
21650    @b{begin}
21651       Call_Chain (TB, Len);
21652       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
21653    @b{end} P1;
21655    @b{procedure} P2 @b{is}
21656    @b{begin}
21657       P1;
21658    @b{end} P2;
21660 @b{begin}
21661    P2;
21662 @b{end} STB;
21663 @end smallexample
21665 @c ******************************
21667 @c **************************************
21668 @node Platform-Specific Information for the Run-Time Libraries
21669 @appendix Platform-Specific Information for the Run-Time Libraries
21670 @cindex Tasking and threads libraries
21671 @cindex Threads libraries and tasking
21672 @cindex Run-time libraries (platform-specific information)
21674 @noindent
21675 The GNAT run-time implementation may vary with respect to both the
21676 underlying threads library and the exception handling scheme.
21677 For threads support, one or more of the following are supplied:
21678 @itemize @bullet
21679 @item @b{native threads library}, a binding to the thread package from
21680 the underlying operating system
21682 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21683 POSIX thread package
21684 @end itemize
21686 @noindent
21687 For exception handling, either or both of two models are supplied:
21688 @itemize @bullet
21689 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21690 Most programs should experience a substantial speed improvement by
21691 being compiled with a ZCX run-time.
21692 This is especially true for
21693 tasking applications or applications with many exception handlers.}
21694 @cindex Zero-Cost Exceptions
21695 @cindex ZCX (Zero-Cost Exceptions)
21696 which uses binder-generated tables that
21697 are interrogated at run time to locate a handler
21699 @item @b{setjmp / longjmp} (``SJLJ''),
21700 @cindex setjmp/longjmp Exception Model
21701 @cindex SJLJ (setjmp/longjmp Exception Model)
21702 which uses dynamically-set data to establish
21703 the set of handlers
21704 @end itemize
21706 @noindent
21707 This appendix summarizes which combinations of threads and exception support
21708 are supplied on various GNAT platforms.
21709 It then shows how to select a particular library either
21710 permanently or temporarily,
21711 explains the properties of (and tradeoffs among) the various threads
21712 libraries, and provides some additional
21713 information about several specific platforms.
21715 @menu
21716 * Summary of Run-Time Configurations::
21717 * Specifying a Run-Time Library::
21718 * Choosing the Scheduling Policy::
21719 * Solaris-Specific Considerations::
21720 * Linux-Specific Considerations::
21721 * AIX-Specific Considerations::
21722 * RTX-Specific Considerations::
21723 * HP-UX-Specific Considerations::
21724 @end menu
21726 @node Summary of Run-Time Configurations
21727 @section Summary of Run-Time Configurations
21729 @multitable @columnfractions .30 .70
21730 @item @b{alpha-openvms}
21731 @item @code{@ @ }@i{rts-native (default)}
21732 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21733 @item @code{@ @ @ @ }Exceptions @tab ZCX
21735 @item @code{@ @ }@i{rts-sjlj}
21736 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21737 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21739 @item @b{ia64-hp_linux}
21740 @item @code{@ @ }@i{rts-native (default)}
21741 @item @code{@ @ @ @ }Tasking    @tab pthread library
21742 @item @code{@ @ @ @ }Exceptions @tab ZCX
21744 @item @b{ia64-hpux}
21745 @item @code{@ @ }@i{rts-native (default)}
21746 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21747 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21749 @item @b{ia64-openvms}
21750 @item @code{@ @ }@i{rts-native (default)}
21751 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21752 @item @code{@ @ @ @ }Exceptions @tab ZCX
21754 @item @b{ia64-sgi_linux}
21755 @item @code{@ @ }@i{rts-native (default)}
21756 @item @code{@ @ @ @ }Tasking    @tab pthread library
21757 @item @code{@ @ @ @ }Exceptions @tab ZCX
21759 @item @b{pa-hpux}
21760 @item @code{@ @ }@i{rts-native (default)}
21761 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21762 @item @code{@ @ @ @ }Exceptions @tab ZCX
21764 @item @code{@ @ }@i{rts-sjlj}
21765 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21766 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21768 @item @b{ppc-aix}
21769 @item @code{@ @ }@i{rts-native (default)}
21770 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21771 @item @code{@ @ @ @ }Exceptions @tab ZCX
21773 @item @code{@ @ }@i{rts-sjlj}
21774 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21775 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21777 @item @b{ppc-darwin}
21778 @item @code{@ @ }@i{rts-native (default)}
21779 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21780 @item @code{@ @ @ @ }Exceptions @tab ZCX
21782 @item @b{sparc-solaris}  @tab
21783 @item @code{@ @ }@i{rts-native (default)}
21784 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21785 @item @code{@ @ @ @ }Exceptions @tab ZCX
21787 @item @code{@ @ }@i{rts-pthread}
21788 @item @code{@ @ @ @ }Tasking    @tab pthread library
21789 @item @code{@ @ @ @ }Exceptions @tab ZCX
21791 @item @code{@ @ }@i{rts-sjlj}
21792 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21793 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21795 @item @b{sparc64-solaris}  @tab
21796 @item @code{@ @ }@i{rts-native (default)}
21797 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21798 @item @code{@ @ @ @ }Exceptions @tab ZCX
21800 @item @b{x86-linux}
21801 @item @code{@ @ }@i{rts-native (default)}
21802 @item @code{@ @ @ @ }Tasking    @tab pthread library
21803 @item @code{@ @ @ @ }Exceptions @tab ZCX
21805 @item @code{@ @ }@i{rts-sjlj}
21806 @item @code{@ @ @ @ }Tasking    @tab pthread library
21807 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21809 @item @b{x86-lynx}
21810 @item @code{@ @ }@i{rts-native (default)}
21811 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
21812 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21814 @item @b{x86-solaris}
21815 @item @code{@ @ }@i{rts-native (default)}
21816 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
21817 @item @code{@ @ @ @ }Exceptions @tab ZCX
21819 @item @code{@ @ }@i{rts-sjlj}
21820 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21821 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21823 @item @b{x86-windows}
21824 @item @code{@ @ }@i{rts-native (default)}
21825 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21826 @item @code{@ @ @ @ }Exceptions @tab ZCX
21828 @item @code{@ @ }@i{rts-sjlj}
21829 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21830 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21832 @item @b{x86-windows-rtx}
21833 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21834 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
21835 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21837 @item @code{@ @ }@i{rts-rtx-w32}
21838 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
21839 @item @code{@ @ @ @ }Exceptions @tab ZCX
21841 @item @b{x86_64-linux}
21842 @item @code{@ @ }@i{rts-native (default)}
21843 @item @code{@ @ @ @ }Tasking    @tab pthread library
21844 @item @code{@ @ @ @ }Exceptions @tab ZCX
21846 @item @code{@ @ }@i{rts-sjlj}
21847 @item @code{@ @ @ @ }Tasking    @tab pthread library
21848 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21850 @end multitable
21852 @node Specifying a Run-Time Library
21853 @section Specifying a Run-Time Library
21855 @noindent
21856 The @file{adainclude} subdirectory containing the sources of the GNAT
21857 run-time library, and the @file{adalib} subdirectory containing the
21858 @file{ALI} files and the static and/or shared GNAT library, are located
21859 in the gcc target-dependent area:
21861 @smallexample
21862 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21863 @end smallexample
21865 @noindent
21866 As indicated above, on some platforms several run-time libraries are supplied.
21867 These libraries are installed in the target dependent area and
21868 contain a complete source and binary subdirectory. The detailed description
21869 below explains the differences between the different libraries in terms of
21870 their thread support.
21872 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21873 This default run time is selected by the means of soft links.
21874 For example on x86-linux:
21876 @smallexample
21877 @group
21878  $(target-dir)
21879      |
21880      +--- adainclude----------+
21881      |                        |
21882      +--- adalib-----------+  |
21883      |                     |  |
21884      +--- rts-native       |  |
21885      |    |                |  |
21886      |    +--- adainclude <---+
21887      |    |                |
21888      |    +--- adalib <----+
21889      |
21890      +--- rts-sjlj
21891           |
21892           +--- adainclude
21893           |
21894           +--- adalib
21895 @end group
21896 @end smallexample
21898 @noindent
21899 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21900 these soft links can be modified with the following commands:
21902 @smallexample
21903 $ cd $target
21904 $ rm -f adainclude adalib
21905 $ ln -s rts-sjlj/adainclude adainclude
21906 $ ln -s rts-sjlj/adalib adalib
21907 @end smallexample
21909 @noindent
21910 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21911 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21912 @file{$target/ada_object_path}.
21914 Selecting another run-time library temporarily can be
21915 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21916 @cindex @option{--RTS} option
21918 @node Choosing the Scheduling Policy
21919 @section Choosing the Scheduling Policy
21921 @noindent
21922 When using a POSIX threads implementation, you have a choice of several
21923 scheduling policies: @code{SCHED_FIFO},
21924 @cindex @code{SCHED_FIFO} scheduling policy
21925 @code{SCHED_RR}
21926 @cindex @code{SCHED_RR} scheduling policy
21927 and @code{SCHED_OTHER}.
21928 @cindex @code{SCHED_OTHER} scheduling policy
21929 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21930 or @code{SCHED_RR} requires special (e.g., root) privileges.
21932 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21933 @code{SCHED_FIFO},
21934 @cindex @code{SCHED_FIFO} scheduling policy
21935 you can use one of the following:
21937 @itemize @bullet
21938 @item
21939 @code{pragma Time_Slice (0.0)}
21940 @cindex pragma Time_Slice
21941 @item
21942 the corresponding binder option @option{-T0}
21943 @cindex @option{-T0} option
21944 @item
21945 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21946 @cindex pragma Task_Dispatching_Policy
21947 @end itemize
21949 @noindent
21950 To specify @code{SCHED_RR},
21951 @cindex @code{SCHED_RR} scheduling policy
21952 you should use @code{pragma Time_Slice} with a
21953 value greater than @code{0.0}, or else use the corresponding @option{-T}
21954 binder option.
21956 @node Solaris-Specific Considerations
21957 @section Solaris-Specific Considerations
21958 @cindex Solaris Sparc threads libraries
21960 @noindent
21961 This section addresses some topics related to the various threads libraries
21962 on Sparc Solaris.
21964 @menu
21965 * Solaris Threads Issues::
21966 @end menu
21968 @node Solaris Threads Issues
21969 @subsection Solaris Threads Issues
21971 @noindent
21972 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21973 library based on POSIX threads --- @emph{rts-pthread}.
21974 @cindex rts-pthread threads library
21975 This run-time library has the advantage of being mostly shared across all
21976 POSIX-compliant thread implementations, and it also provides under
21977 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21978 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21979 and @code{PTHREAD_PRIO_PROTECT}
21980 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21981 semantics that can be selected using the predefined pragma
21982 @code{Locking_Policy}
21983 @cindex pragma Locking_Policy (under rts-pthread)
21984 with respectively
21985 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21986 @cindex @code{Inheritance_Locking} (under rts-pthread)
21987 @cindex @code{Ceiling_Locking} (under rts-pthread)
21989 As explained above, the native run-time library is based on the Solaris thread
21990 library (@code{libthread}) and is the default library.
21992 When the Solaris threads library is used (this is the default), programs
21993 compiled with GNAT can automatically take advantage of
21994 and can thus execute on multiple processors.
21995 The user can alternatively specify a processor on which the program should run
21996 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21997 is made by
21998 setting the environment variable @env{GNAT_PROCESSOR}
21999 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22000 to one of the following:
22002 @table @code
22003 @item -2
22004 Use the default configuration (run the program on all
22005 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22006 unset
22008 @item -1
22009 Let the run-time implementation choose one processor and run the program on
22010 that processor
22012 @item 0 .. Last_Proc
22013 Run the program on the specified processor.
22014 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22015 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22016 @end table
22018 @node Linux-Specific Considerations
22019 @section Linux-Specific Considerations
22020 @cindex Linux threads libraries
22022 @noindent
22023 On GNU/Linux without NPTL support (usually system with GNU C Library
22024 older than 2.3), the signal model is not POSIX compliant, which means
22025 that to send a signal to the process, you need to send the signal to all
22026 threads, e.g.@: by using @code{killpg()}.
22028 @node AIX-Specific Considerations
22029 @section AIX-Specific Considerations
22030 @cindex AIX resolver library
22032 @noindent
22033 On AIX, the resolver library initializes some internal structure on
22034 the first call to @code{get*by*} functions, which are used to implement
22035 @code{GNAT.Sockets.Get_Host_By_Name} and
22036 @code{GNAT.Sockets.Get_Host_By_Address}.
22037 If such initialization occurs within an Ada task, and the stack size for
22038 the task is the default size, a stack overflow may occur.
22040 To avoid this overflow, the user should either ensure that the first call
22041 to @code{GNAT.Sockets.Get_Host_By_Name} or
22042 @code{GNAT.Sockets.Get_Host_By_Addrss}
22043 occurs in the environment task, or use @code{pragma Storage_Size} to
22044 specify a sufficiently large size for the stack of the task that contains
22045 this call.
22047 @node RTX-Specific Considerations
22048 @section RTX-Specific Considerations
22049 @cindex RTX libraries
22051 @noindent
22052 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22053 API. Applications can be built to work in two different modes:
22055 @itemize @bullet
22056 @item
22057 Windows executables that run in Ring 3 to utilize memory protection
22058 (@emph{rts-rtx-w32}).
22060 @item
22061 Real-time subsystem (RTSS) executables that run in Ring 0, where
22062 performance can be optimized with RTSS applications taking precedent
22063 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22064 the Microsoft linker to handle RTSS libraries.
22066 @end itemize
22068 @node HP-UX-Specific Considerations
22069 @section HP-UX-Specific Considerations
22070 @cindex HP-UX Scheduling
22072 @noindent
22073 On HP-UX, appropriate privileges are required to change the scheduling
22074 parameters of a task. The calling process must have appropriate
22075 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22076 successfully change the scheduling parameters.
22078 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22079 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22080 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22082 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22083 one of the following:
22085 @itemize @bullet
22086 @item
22087 @code{pragma Time_Slice (0.0)}
22088 @cindex pragma Time_Slice
22089 @item
22090 the corresponding binder option @option{-T0}
22091 @cindex @option{-T0} option
22092 @item
22093 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22094 @cindex pragma Task_Dispatching_Policy
22095 @end itemize
22097 @noindent
22098 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22099 you should use @code{pragma Time_Slice} with a
22100 value greater than @code{0.0}, or use the corresponding @option{-T}
22101 binder option, or set the @code{pragma Task_Dispatching_Policy
22102 (Round_Robin_Within_Priorities)}.
22104 @c *******************************
22105 @node Example of Binder Output File
22106 @appendix Example of Binder Output File
22108 @noindent
22109 This Appendix displays the source code for @command{gnatbind}'s output
22110 file generated for a simple ``Hello World'' program.
22111 Comments have been added for clarification purposes.
22113 @smallexample @c adanocomment
22114 @iftex
22115 @leftskip=0cm
22116 @end iftex
22117 --  The package is called Ada_Main unless this name is actually used
22118 --  as a unit name in the partition, in which case some other unique
22119 --  name is used.
22121 @b{with} System;
22122 @b{package} ada_main @b{is}
22124    Elab_Final_Code : Integer;
22125    @b{pragma} Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22127    --  The main program saves the parameters (argument count,
22128    --  argument values, environment pointer) in global variables
22129    --  for later access by other units including
22130    --  Ada.Command_Line.
22132    gnat_argc : Integer;
22133    gnat_argv : System.Address;
22134    gnat_envp : System.Address;
22136    --  The actual variables are stored in a library routine. This
22137    --  is useful for some shared library situations, where there
22138    --  are problems if variables are not in the library.
22140    @b{pragma} Import (C, gnat_argc);
22141    @b{pragma} Import (C, gnat_argv);
22142    @b{pragma} Import (C, gnat_envp);
22144    --  The exit status is similarly an external location
22146    gnat_exit_status : Integer;
22147    @b{pragma} Import (C, gnat_exit_status);
22149    GNAT_Version : @b{constant} String :=
22150                     "GNAT Version: 6.0.0w (20061115)";
22151    @b{pragma} Export (C, GNAT_Version, "__gnat_version");
22153    --  This is the generated adafinal routine that performs
22154    --  finalization at the end of execution. In the case where
22155    --  Ada is the main program, this main program makes a call
22156    --  to adafinal at program termination.
22158    @b{procedure} adafinal;
22159    @b{pragma} Export (C, adafinal, "adafinal");
22161    --  This is the generated adainit routine that performs
22162    --  initialization at the start of execution. In the case
22163    --  where Ada is the main program, this main program makes
22164    --  a call to adainit at program startup.
22166    @b{procedure} adainit;
22167    @b{pragma} Export (C, adainit, "adainit");
22169    --  This routine is called at the start of execution. It is
22170    --  a dummy routine that is used by the debugger to breakpoint
22171    --  at the start of execution.
22173    @b{procedure} Break_Start;
22174    @b{pragma} Import (C, Break_Start, "__gnat_break_start");
22176    --  This is the actual generated main program (it would be
22177    --  suppressed if the no main program switch were used). As
22178    --  required by standard system conventions, this program has
22179    --  the external name main.
22181    @b{function} main
22182      (argc : Integer;
22183       argv : System.Address;
22184       envp : System.Address)
22185       @b{return} Integer;
22186    @b{pragma} Export (C, main, "main");
22188    --  The following set of constants give the version
22189    --  identification values for every unit in the bound
22190    --  partition. This identification is computed from all
22191    --  dependent semantic units, and corresponds to the
22192    --  string that would be returned by use of the
22193    --  Body_Version or Version attributes.
22195    @b{type} Version_32 @b{is} @b{mod} 2 ** 32;
22196    u00001 : @b{constant} Version_32 := 16#7880BEB3#;
22197    u00002 : @b{constant} Version_32 := 16#0D24CBD0#;
22198    u00003 : @b{constant} Version_32 := 16#3283DBEB#;
22199    u00004 : @b{constant} Version_32 := 16#2359F9ED#;
22200    u00005 : @b{constant} Version_32 := 16#664FB847#;
22201    u00006 : @b{constant} Version_32 := 16#68E803DF#;
22202    u00007 : @b{constant} Version_32 := 16#5572E604#;
22203    u00008 : @b{constant} Version_32 := 16#46B173D8#;
22204    u00009 : @b{constant} Version_32 := 16#156A40CF#;
22205    u00010 : @b{constant} Version_32 := 16#033DABE0#;
22206    u00011 : @b{constant} Version_32 := 16#6AB38FEA#;
22207    u00012 : @b{constant} Version_32 := 16#22B6217D#;
22208    u00013 : @b{constant} Version_32 := 16#68A22947#;
22209    u00014 : @b{constant} Version_32 := 16#18CC4A56#;
22210    u00015 : @b{constant} Version_32 := 16#08258E1B#;
22211    u00016 : @b{constant} Version_32 := 16#367D5222#;
22212    u00017 : @b{constant} Version_32 := 16#20C9ECA4#;
22213    u00018 : @b{constant} Version_32 := 16#50D32CB6#;
22214    u00019 : @b{constant} Version_32 := 16#39A8BB77#;
22215    u00020 : @b{constant} Version_32 := 16#5CF8FA2B#;
22216    u00021 : @b{constant} Version_32 := 16#2F1EB794#;
22217    u00022 : @b{constant} Version_32 := 16#31AB6444#;
22218    u00023 : @b{constant} Version_32 := 16#1574B6E9#;
22219    u00024 : @b{constant} Version_32 := 16#5109C189#;
22220    u00025 : @b{constant} Version_32 := 16#56D770CD#;
22221    u00026 : @b{constant} Version_32 := 16#02F9DE3D#;
22222    u00027 : @b{constant} Version_32 := 16#08AB6B2C#;
22223    u00028 : @b{constant} Version_32 := 16#3FA37670#;
22224    u00029 : @b{constant} Version_32 := 16#476457A0#;
22225    u00030 : @b{constant} Version_32 := 16#731E1B6E#;
22226    u00031 : @b{constant} Version_32 := 16#23C2E789#;
22227    u00032 : @b{constant} Version_32 := 16#0F1BD6A1#;
22228    u00033 : @b{constant} Version_32 := 16#7C25DE96#;
22229    u00034 : @b{constant} Version_32 := 16#39ADFFA2#;
22230    u00035 : @b{constant} Version_32 := 16#571DE3E7#;
22231    u00036 : @b{constant} Version_32 := 16#5EB646AB#;
22232    u00037 : @b{constant} Version_32 := 16#4249379B#;
22233    u00038 : @b{constant} Version_32 := 16#0357E00A#;
22234    u00039 : @b{constant} Version_32 := 16#3784FB72#;
22235    u00040 : @b{constant} Version_32 := 16#2E723019#;
22236    u00041 : @b{constant} Version_32 := 16#623358EA#;
22237    u00042 : @b{constant} Version_32 := 16#107F9465#;
22238    u00043 : @b{constant} Version_32 := 16#6843F68A#;
22239    u00044 : @b{constant} Version_32 := 16#63305874#;
22240    u00045 : @b{constant} Version_32 := 16#31E56CE1#;
22241    u00046 : @b{constant} Version_32 := 16#02917970#;
22242    u00047 : @b{constant} Version_32 := 16#6CCBA70E#;
22243    u00048 : @b{constant} Version_32 := 16#41CD4204#;
22244    u00049 : @b{constant} Version_32 := 16#572E3F58#;
22245    u00050 : @b{constant} Version_32 := 16#20729FF5#;
22246    u00051 : @b{constant} Version_32 := 16#1D4F93E8#;
22247    u00052 : @b{constant} Version_32 := 16#30B2EC3D#;
22248    u00053 : @b{constant} Version_32 := 16#34054F96#;
22249    u00054 : @b{constant} Version_32 := 16#5A199860#;
22250    u00055 : @b{constant} Version_32 := 16#0E7F912B#;
22251    u00056 : @b{constant} Version_32 := 16#5760634A#;
22252    u00057 : @b{constant} Version_32 := 16#5D851835#;
22254    --  The following Export pragmas export the version numbers
22255    --  with symbolic names ending in B (for body) or S
22256    --  (for spec) so that they can be located in a link. The
22257    --  information provided here is sufficient to track down
22258    --  the exact versions of units used in a given build.
22260    @b{pragma} Export (C, u00001, "helloB");
22261    @b{pragma} Export (C, u00002, "system__standard_libraryB");
22262    @b{pragma} Export (C, u00003, "system__standard_libraryS");
22263    @b{pragma} Export (C, u00004, "adaS");
22264    @b{pragma} Export (C, u00005, "ada__text_ioB");
22265    @b{pragma} Export (C, u00006, "ada__text_ioS");
22266    @b{pragma} Export (C, u00007, "ada__exceptionsB");
22267    @b{pragma} Export (C, u00008, "ada__exceptionsS");
22268    @b{pragma} Export (C, u00009, "gnatS");
22269    @b{pragma} Export (C, u00010, "gnat__heap_sort_aB");
22270    @b{pragma} Export (C, u00011, "gnat__heap_sort_aS");
22271    @b{pragma} Export (C, u00012, "systemS");
22272    @b{pragma} Export (C, u00013, "system__exception_tableB");
22273    @b{pragma} Export (C, u00014, "system__exception_tableS");
22274    @b{pragma} Export (C, u00015, "gnat__htableB");
22275    @b{pragma} Export (C, u00016, "gnat__htableS");
22276    @b{pragma} Export (C, u00017, "system__exceptionsS");
22277    @b{pragma} Export (C, u00018, "system__machine_state_operationsB");
22278    @b{pragma} Export (C, u00019, "system__machine_state_operationsS");
22279    @b{pragma} Export (C, u00020, "system__machine_codeS");
22280    @b{pragma} Export (C, u00021, "system__storage_elementsB");
22281    @b{pragma} Export (C, u00022, "system__storage_elementsS");
22282    @b{pragma} Export (C, u00023, "system__secondary_stackB");
22283    @b{pragma} Export (C, u00024, "system__secondary_stackS");
22284    @b{pragma} Export (C, u00025, "system__parametersB");
22285    @b{pragma} Export (C, u00026, "system__parametersS");
22286    @b{pragma} Export (C, u00027, "system__soft_linksB");
22287    @b{pragma} Export (C, u00028, "system__soft_linksS");
22288    @b{pragma} Export (C, u00029, "system__stack_checkingB");
22289    @b{pragma} Export (C, u00030, "system__stack_checkingS");
22290    @b{pragma} Export (C, u00031, "system__tracebackB");
22291    @b{pragma} Export (C, u00032, "system__tracebackS");
22292    @b{pragma} Export (C, u00033, "ada__streamsS");
22293    @b{pragma} Export (C, u00034, "ada__tagsB");
22294    @b{pragma} Export (C, u00035, "ada__tagsS");
22295    @b{pragma} Export (C, u00036, "system__string_opsB");
22296    @b{pragma} Export (C, u00037, "system__string_opsS");
22297    @b{pragma} Export (C, u00038, "interfacesS");
22298    @b{pragma} Export (C, u00039, "interfaces__c_streamsB");
22299    @b{pragma} Export (C, u00040, "interfaces__c_streamsS");
22300    @b{pragma} Export (C, u00041, "system__file_ioB");
22301    @b{pragma} Export (C, u00042, "system__file_ioS");
22302    @b{pragma} Export (C, u00043, "ada__finalizationB");
22303    @b{pragma} Export (C, u00044, "ada__finalizationS");
22304    @b{pragma} Export (C, u00045, "system__finalization_rootB");
22305    @b{pragma} Export (C, u00046, "system__finalization_rootS");
22306    @b{pragma} Export (C, u00047, "system__finalization_implementationB");
22307    @b{pragma} Export (C, u00048, "system__finalization_implementationS");
22308    @b{pragma} Export (C, u00049, "system__string_ops_concat_3B");
22309    @b{pragma} Export (C, u00050, "system__string_ops_concat_3S");
22310    @b{pragma} Export (C, u00051, "system__stream_attributesB");
22311    @b{pragma} Export (C, u00052, "system__stream_attributesS");
22312    @b{pragma} Export (C, u00053, "ada__io_exceptionsS");
22313    @b{pragma} Export (C, u00054, "system__unsigned_typesS");
22314    @b{pragma} Export (C, u00055, "system__file_control_blockS");
22315    @b{pragma} Export (C, u00056, "ada__finalization__list_controllerB");
22316    @b{pragma} Export (C, u00057, "ada__finalization__list_controllerS");
22318    -- BEGIN ELABORATION ORDER
22319    -- ada (spec)
22320    -- gnat (spec)
22321    -- gnat.heap_sort_a (spec)
22322    -- gnat.heap_sort_a (body)
22323    -- gnat.htable (spec)
22324    -- gnat.htable (body)
22325    -- interfaces (spec)
22326    -- system (spec)
22327    -- system.machine_code (spec)
22328    -- system.parameters (spec)
22329    -- system.parameters (body)
22330    -- interfaces.c_streams (spec)
22331    -- interfaces.c_streams (body)
22332    -- system.standard_library (spec)
22333    -- ada.exceptions (spec)
22334    -- system.exception_table (spec)
22335    -- system.exception_table (body)
22336    -- ada.io_exceptions (spec)
22337    -- system.exceptions (spec)
22338    -- system.storage_elements (spec)
22339    -- system.storage_elements (body)
22340    -- system.machine_state_operations (spec)
22341    -- system.machine_state_operations (body)
22342    -- system.secondary_stack (spec)
22343    -- system.stack_checking (spec)
22344    -- system.soft_links (spec)
22345    -- system.soft_links (body)
22346    -- system.stack_checking (body)
22347    -- system.secondary_stack (body)
22348    -- system.standard_library (body)
22349    -- system.string_ops (spec)
22350    -- system.string_ops (body)
22351    -- ada.tags (spec)
22352    -- ada.tags (body)
22353    -- ada.streams (spec)
22354    -- system.finalization_root (spec)
22355    -- system.finalization_root (body)
22356    -- system.string_ops_concat_3 (spec)
22357    -- system.string_ops_concat_3 (body)
22358    -- system.traceback (spec)
22359    -- system.traceback (body)
22360    -- ada.exceptions (body)
22361    -- system.unsigned_types (spec)
22362    -- system.stream_attributes (spec)
22363    -- system.stream_attributes (body)
22364    -- system.finalization_implementation (spec)
22365    -- system.finalization_implementation (body)
22366    -- ada.finalization (spec)
22367    -- ada.finalization (body)
22368    -- ada.finalization.list_controller (spec)
22369    -- ada.finalization.list_controller (body)
22370    -- system.file_control_block (spec)
22371    -- system.file_io (spec)
22372    -- system.file_io (body)
22373    -- ada.text_io (spec)
22374    -- ada.text_io (body)
22375    -- hello (body)
22376    -- END ELABORATION ORDER
22378 @b{end} ada_main;
22380 --  The following source file name pragmas allow the generated file
22381 --  names to be unique for different main programs. They are needed
22382 --  since the package name will always be Ada_Main.
22384 @b{pragma} Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22385 @b{pragma} Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22387 --  Generated package body for Ada_Main starts here
22389 @b{package} @b{body} ada_main @b{is}
22391    --  The actual finalization is performed by calling the
22392    --  library routine in System.Standard_Library.Adafinal
22394    @b{procedure} Do_Finalize;
22395    @b{pragma} Import (C, Do_Finalize, "system__standard_library__adafinal");
22397    -------------
22398    -- adainit --
22399    -------------
22401 @findex adainit
22402    @b{procedure} adainit @b{is}
22404       --  These booleans are set to True once the associated unit has
22405       --  been elaborated. It is also used to avoid elaborating the
22406       --  same unit twice.
22408       E040 : Boolean;
22409       @b{pragma} Import (Ada, E040, "interfaces__c_streams_E");
22411       E008 : Boolean;
22412       @b{pragma} Import (Ada, E008, "ada__exceptions_E");
22414       E014 : Boolean;
22415       @b{pragma} Import (Ada, E014, "system__exception_table_E");
22417       E053 : Boolean;
22418       @b{pragma} Import (Ada, E053, "ada__io_exceptions_E");
22420       E017 : Boolean;
22421       @b{pragma} Import (Ada, E017, "system__exceptions_E");
22423       E024 : Boolean;
22424       @b{pragma} Import (Ada, E024, "system__secondary_stack_E");
22426       E030 : Boolean;
22427       @b{pragma} Import (Ada, E030, "system__stack_checking_E");
22429       E028 : Boolean;
22430       @b{pragma} Import (Ada, E028, "system__soft_links_E");
22432       E035 : Boolean;
22433       @b{pragma} Import (Ada, E035, "ada__tags_E");
22435       E033 : Boolean;
22436       @b{pragma} Import (Ada, E033, "ada__streams_E");
22438       E046 : Boolean;
22439       @b{pragma} Import (Ada, E046, "system__finalization_root_E");
22441       E048 : Boolean;
22442       @b{pragma} Import (Ada, E048, "system__finalization_implementation_E");
22444       E044 : Boolean;
22445       @b{pragma} Import (Ada, E044, "ada__finalization_E");
22447       E057 : Boolean;
22448       @b{pragma} Import (Ada, E057, "ada__finalization__list_controller_E");
22450       E055 : Boolean;
22451       @b{pragma} Import (Ada, E055, "system__file_control_block_E");
22453       E042 : Boolean;
22454       @b{pragma} Import (Ada, E042, "system__file_io_E");
22456       E006 : Boolean;
22457       @b{pragma} Import (Ada, E006, "ada__text_io_E");
22459       --  Set_Globals is a library routine that stores away the
22460       --  value of the indicated set of global values in global
22461       --  variables within the library.
22463       @b{procedure} Set_Globals
22464         (Main_Priority            : Integer;
22465          Time_Slice_Value         : Integer;
22466          WC_Encoding              : Character;
22467          Locking_Policy           : Character;
22468          Queuing_Policy           : Character;
22469          Task_Dispatching_Policy  : Character;
22470          Adafinal                 : System.Address;
22471          Unreserve_All_Interrupts : Integer;
22472          Exception_Tracebacks     : Integer);
22473 @findex __gnat_set_globals
22474       @b{pragma} Import (C, Set_Globals, "__gnat_set_globals");
22476       --  SDP_Table_Build is a library routine used to build the
22477       --  exception tables. See unit Ada.Exceptions in files
22478       --  a-except.ads/adb for full details of how zero cost
22479       --  exception handling works. This procedure, the call to
22480       --  it, and the two following tables are all omitted if the
22481       --  build is in longjmp/setjmp exception mode.
22483 @findex SDP_Table_Build
22484 @findex Zero Cost Exceptions
22485       @b{procedure} SDP_Table_Build
22486         (SDP_Addresses   : System.Address;
22487          SDP_Count       : Natural;
22488          Elab_Addresses  : System.Address;
22489          Elab_Addr_Count : Natural);
22490       @b{pragma} Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22492       --  Table of Unit_Exception_Table addresses. Used for zero
22493       --  cost exception handling to build the top level table.
22495       ST : @b{aliased} @b{constant} @b{array} (1 .. 23) @b{of} System.Address := (
22496         Hello'UET_Address,
22497         Ada.Text_Io'UET_Address,
22498         Ada.Exceptions'UET_Address,
22499         Gnat.Heap_Sort_A'UET_Address,
22500         System.Exception_Table'UET_Address,
22501         System.Machine_State_Operations'UET_Address,
22502         System.Secondary_Stack'UET_Address,
22503         System.Parameters'UET_Address,
22504         System.Soft_Links'UET_Address,
22505         System.Stack_Checking'UET_Address,
22506         System.Traceback'UET_Address,
22507         Ada.Streams'UET_Address,
22508         Ada.Tags'UET_Address,
22509         System.String_Ops'UET_Address,
22510         Interfaces.C_Streams'UET_Address,
22511         System.File_Io'UET_Address,
22512         Ada.Finalization'UET_Address,
22513         System.Finalization_Root'UET_Address,
22514         System.Finalization_Implementation'UET_Address,
22515         System.String_Ops_Concat_3'UET_Address,
22516         System.Stream_Attributes'UET_Address,
22517         System.File_Control_Block'UET_Address,
22518         Ada.Finalization.List_Controller'UET_Address);
22520       --  Table of addresses of elaboration routines. Used for
22521       --  zero cost exception handling to make sure these
22522       --  addresses are included in the top level procedure
22523       --  address table.
22525       EA : @b{aliased} @b{constant} @b{array} (1 .. 23) @b{of} System.Address := (
22526         adainit'Code_Address,
22527         Do_Finalize'Code_Address,
22528         Ada.Exceptions'Elab_Spec'Address,
22529         System.Exceptions'Elab_Spec'Address,
22530         Interfaces.C_Streams'Elab_Spec'Address,
22531         System.Exception_Table'Elab_Body'Address,
22532         Ada.Io_Exceptions'Elab_Spec'Address,
22533         System.Stack_Checking'Elab_Spec'Address,
22534         System.Soft_Links'Elab_Body'Address,
22535         System.Secondary_Stack'Elab_Body'Address,
22536         Ada.Tags'Elab_Spec'Address,
22537         Ada.Tags'Elab_Body'Address,
22538         Ada.Streams'Elab_Spec'Address,
22539         System.Finalization_Root'Elab_Spec'Address,
22540         Ada.Exceptions'Elab_Body'Address,
22541         System.Finalization_Implementation'Elab_Spec'Address,
22542         System.Finalization_Implementation'Elab_Body'Address,
22543         Ada.Finalization'Elab_Spec'Address,
22544         Ada.Finalization.List_Controller'Elab_Spec'Address,
22545         System.File_Control_Block'Elab_Spec'Address,
22546         System.File_Io'Elab_Body'Address,
22547         Ada.Text_Io'Elab_Spec'Address,
22548         Ada.Text_Io'Elab_Body'Address);
22550    --  Start of processing for adainit
22552    @b{begin}
22554       --  Call SDP_Table_Build to build the top level procedure
22555       --  table for zero cost exception handling (omitted in
22556       --  longjmp/setjmp mode).
22558       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22560       --  Call Set_Globals to record various information for
22561       --  this partition.  The values are derived by the binder
22562       --  from information stored in the ali files by the compiler.
22564 @findex __gnat_set_globals
22565       Set_Globals
22566         (Main_Priority            => -1,
22567          --  Priority of main program, -1 if no pragma Priority used
22569          Time_Slice_Value         => -1,
22570          --  Time slice from Time_Slice pragma, -1 if none used
22572          WC_Encoding              => 'b',
22573          --  Wide_Character encoding used, default is brackets
22575          Locking_Policy           => ' ',
22576          --  Locking_Policy used, default of space means not
22577          --  specified, otherwise it is the first character of
22578          --  the policy name.
22580          Queuing_Policy           => ' ',
22581          --  Queuing_Policy used, default of space means not
22582          --  specified, otherwise it is the first character of
22583          --  the policy name.
22585          Task_Dispatching_Policy  => ' ',
22586          --  Task_Dispatching_Policy used, default of space means
22587          --  not specified, otherwise first character of the
22588          --  policy name.
22590          Adafinal                 => System.Null_Address,
22591          --  Address of Adafinal routine, not used anymore
22593          Unreserve_All_Interrupts => 0,
22594          --  Set true if pragma Unreserve_All_Interrupts was used
22596          Exception_Tracebacks     => 0);
22597          --  Indicates if exception tracebacks are enabled
22599       Elab_Final_Code := 1;
22601       --  Now we have the elaboration calls for all units in the partition.
22602       --  The Elab_Spec and Elab_Body attributes generate references to the
22603       --  implicit elaboration procedures generated by the compiler for
22604       --  each unit that requires elaboration.
22606       @b{if} @b{not} E040 @b{then}
22607          Interfaces.C_Streams'Elab_Spec;
22608       @b{end} @b{if};
22609       E040 := True;
22610       @b{if} @b{not} E008 @b{then}
22611          Ada.Exceptions'Elab_Spec;
22612       @b{end} @b{if};
22613       @b{if} @b{not} E014 @b{then}
22614          System.Exception_Table'Elab_Body;
22615          E014 := True;
22616       @b{end} @b{if};
22617       @b{if} @b{not} E053 @b{then}
22618          Ada.Io_Exceptions'Elab_Spec;
22619          E053 := True;
22620       @b{end} @b{if};
22621       @b{if} @b{not} E017 @b{then}
22622          System.Exceptions'Elab_Spec;
22623          E017 := True;
22624       @b{end} @b{if};
22625       @b{if} @b{not} E030 @b{then}
22626          System.Stack_Checking'Elab_Spec;
22627       @b{end} @b{if};
22628       @b{if} @b{not} E028 @b{then}
22629          System.Soft_Links'Elab_Body;
22630          E028 := True;
22631       @b{end} @b{if};
22632       E030 := True;
22633       @b{if} @b{not} E024 @b{then}
22634          System.Secondary_Stack'Elab_Body;
22635          E024 := True;
22636       @b{end} @b{if};
22637       @b{if} @b{not} E035 @b{then}
22638          Ada.Tags'Elab_Spec;
22639       @b{end} @b{if};
22640       @b{if} @b{not} E035 @b{then}
22641          Ada.Tags'Elab_Body;
22642          E035 := True;
22643       @b{end} @b{if};
22644       @b{if} @b{not} E033 @b{then}
22645          Ada.Streams'Elab_Spec;
22646          E033 := True;
22647       @b{end} @b{if};
22648       @b{if} @b{not} E046 @b{then}
22649          System.Finalization_Root'Elab_Spec;
22650       @b{end} @b{if};
22651       E046 := True;
22652       @b{if} @b{not} E008 @b{then}
22653          Ada.Exceptions'Elab_Body;
22654          E008 := True;
22655       @b{end} @b{if};
22656       @b{if} @b{not} E048 @b{then}
22657          System.Finalization_Implementation'Elab_Spec;
22658       @b{end} @b{if};
22659       @b{if} @b{not} E048 @b{then}
22660          System.Finalization_Implementation'Elab_Body;
22661          E048 := True;
22662       @b{end} @b{if};
22663       @b{if} @b{not} E044 @b{then}
22664          Ada.Finalization'Elab_Spec;
22665       @b{end} @b{if};
22666       E044 := True;
22667       @b{if} @b{not} E057 @b{then}
22668          Ada.Finalization.List_Controller'Elab_Spec;
22669       @b{end} @b{if};
22670       E057 := True;
22671       @b{if} @b{not} E055 @b{then}
22672          System.File_Control_Block'Elab_Spec;
22673          E055 := True;
22674       @b{end} @b{if};
22675       @b{if} @b{not} E042 @b{then}
22676          System.File_Io'Elab_Body;
22677          E042 := True;
22678       @b{end} @b{if};
22679       @b{if} @b{not} E006 @b{then}
22680          Ada.Text_Io'Elab_Spec;
22681       @b{end} @b{if};
22682       @b{if} @b{not} E006 @b{then}
22683          Ada.Text_Io'Elab_Body;
22684          E006 := True;
22685       @b{end} @b{if};
22687       Elab_Final_Code := 0;
22688    @b{end} adainit;
22690    --------------
22691    -- adafinal --
22692    --------------
22694 @findex adafinal
22695    @b{procedure} adafinal @b{is}
22696    @b{begin}
22697       Do_Finalize;
22698    @b{end} adafinal;
22700    ----------
22701    -- main --
22702    ----------
22704    --  main is actually a function, as in the ANSI C standard,
22705    --  defined to return the exit status. The three parameters
22706    --  are the argument count, argument values and environment
22707    --  pointer.
22709 @findex Main Program
22710    @b{function} main
22711      (argc : Integer;
22712       argv : System.Address;
22713       envp : System.Address)
22714       @b{return} Integer
22715    @b{is}
22716       --  The initialize routine performs low level system
22717       --  initialization using a standard library routine which
22718       --  sets up signal handling and performs any other
22719       --  required setup. The routine can be found in file
22720       --  a-init.c.
22722 @findex __gnat_initialize
22723       @b{procedure} initialize;
22724       @b{pragma} Import (C, initialize, "__gnat_initialize");
22726       --  The finalize routine performs low level system
22727       --  finalization using a standard library routine. The
22728       --  routine is found in file a-final.c and in the standard
22729       --  distribution is a dummy routine that does nothing, so
22730       --  really this is a hook for special user finalization.
22732 @findex __gnat_finalize
22733       @b{procedure} finalize;
22734       @b{pragma} Import (C, finalize, "__gnat_finalize");
22736       --  We get to the main program of the partition by using
22737       --  pragma Import because if we try to with the unit and
22738       --  call it Ada style, then not only do we waste time
22739       --  recompiling it, but also, we don't really know the right
22740       --  switches (e.g.@: identifier character set) to be used
22741       --  to compile it.
22743       @b{procedure} Ada_Main_Program;
22744       @b{pragma} Import (Ada, Ada_Main_Program, "_ada_hello");
22746    --  Start of processing for main
22748    @b{begin}
22749       --  Save global variables
22751       gnat_argc := argc;
22752       gnat_argv := argv;
22753       gnat_envp := envp;
22755       --  Call low level system initialization
22757       Initialize;
22759       --  Call our generated Ada initialization routine
22761       adainit;
22763       --  This is the point at which we want the debugger to get
22764       --  control
22766       Break_Start;
22768       --  Now we call the main program of the partition
22770       Ada_Main_Program;
22772       --  Perform Ada finalization
22774       adafinal;
22776       --  Perform low level system finalization
22778       Finalize;
22780       --  Return the proper exit status
22781       @b{return} (gnat_exit_status);
22782    @b{end};
22784 --  This section is entirely comments, so it has no effect on the
22785 --  compilation of the Ada_Main package. It provides the list of
22786 --  object files and linker options, as well as some standard
22787 --  libraries needed for the link. The gnatlink utility parses
22788 --  this b~hello.adb file to read these comment lines to generate
22789 --  the appropriate command line arguments for the call to the
22790 --  system linker. The BEGIN/END lines are used for sentinels for
22791 --  this parsing operation.
22793 --  The exact file names will of course depend on the environment,
22794 --  host/target and location of files on the host system.
22796 @findex Object file list
22797 -- BEGIN Object file/option list
22798    --   ./hello.o
22799    --   -L./
22800    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22801    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22802 -- END Object file/option list
22804 @b{end} ada_main;
22805 @end smallexample
22807 @noindent
22808 The Ada code in the above example is exactly what is generated by the
22809 binder. We have added comments to more clearly indicate the function
22810 of each part of the generated @code{Ada_Main} package.
22812 The code is standard Ada in all respects, and can be processed by any
22813 tools that handle Ada. In particular, it is possible to use the debugger
22814 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22815 suppose that for reasons that you do not understand, your program is crashing
22816 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22817 you can place a breakpoint on the call:
22819 @smallexample @c ada
22820 Ada.Text_Io'Elab_Body;
22821 @end smallexample
22823 @noindent
22824 and trace the elaboration routine for this package to find out where
22825 the problem might be (more usually of course you would be debugging
22826 elaboration code in your own application).
22828 @node Elaboration Order Handling in GNAT
22829 @appendix Elaboration Order Handling in GNAT
22830 @cindex Order of elaboration
22831 @cindex Elaboration control
22833 @menu
22834 * Elaboration Code::
22835 * Checking the Elaboration Order::
22836 * Controlling the Elaboration Order::
22837 * Controlling Elaboration in GNAT - Internal Calls::
22838 * Controlling Elaboration in GNAT - External Calls::
22839 * Default Behavior in GNAT - Ensuring Safety::
22840 * Treatment of Pragma Elaborate::
22841 * Elaboration Issues for Library Tasks::
22842 * Mixing Elaboration Models::
22843 * What to Do If the Default Elaboration Behavior Fails::
22844 * Elaboration for Indirect Calls::
22845 * Summary of Procedures for Elaboration Control::
22846 * Other Elaboration Order Considerations::
22847 * Determining the Chosen Elaboration Order::
22848 @end menu
22850 @noindent
22851 This chapter describes the handling of elaboration code in Ada and
22852 in GNAT, and discusses how the order of elaboration of program units can
22853 be controlled in GNAT, either automatically or with explicit programming
22854 features.
22856 @node Elaboration Code
22857 @section Elaboration Code
22859 @noindent
22860 Ada provides rather general mechanisms for executing code at elaboration
22861 time, that is to say before the main program starts executing. Such code arises
22862 in three contexts:
22864 @table @asis
22865 @item Initializers for variables.
22866 Variables declared at the library level, in package specs or bodies, can
22867 require initialization that is performed at elaboration time, as in:
22868 @smallexample @c ada
22869 @cartouche
22870 Sqrt_Half : Float := Sqrt (0.5);
22871 @end cartouche
22872 @end smallexample
22874 @item Package initialization code
22875 Code in a @code{BEGIN-END} section at the outer level of a package body is
22876 executed as part of the package body elaboration code.
22878 @item Library level task allocators
22879 Tasks that are declared using task allocators at the library level
22880 start executing immediately and hence can execute at elaboration time.
22881 @end table
22883 @noindent
22884 Subprogram calls are possible in any of these contexts, which means that
22885 any arbitrary part of the program may be executed as part of the elaboration
22886 code. It is even possible to write a program which does all its work at
22887 elaboration time, with a null main program, although stylistically this
22888 would usually be considered an inappropriate way to structure
22889 a program.
22891 An important concern arises in the context of elaboration code:
22892 we have to be sure that it is executed in an appropriate order. What we
22893 have is a series of elaboration code sections, potentially one section
22894 for each unit in the program. It is important that these execute
22895 in the correct order. Correctness here means that, taking the above
22896 example of the declaration of @code{Sqrt_Half},
22897 if some other piece of
22898 elaboration code references @code{Sqrt_Half},
22899 then it must run after the
22900 section of elaboration code that contains the declaration of
22901 @code{Sqrt_Half}.
22903 There would never be any order of elaboration problem if we made a rule
22904 that whenever you @code{with} a unit, you must elaborate both the spec and body
22905 of that unit before elaborating the unit doing the @code{with}'ing:
22907 @smallexample @c ada
22908 @group
22909 @cartouche
22910 @b{with} Unit_1;
22911 @b{package} Unit_2 @b{is} @dots{}
22912 @end cartouche
22913 @end group
22914 @end smallexample
22916 @noindent
22917 would require that both the body and spec of @code{Unit_1} be elaborated
22918 before the spec of @code{Unit_2}. However, a rule like that would be far too
22919 restrictive. In particular, it would make it impossible to have routines
22920 in separate packages that were mutually recursive.
22922 You might think that a clever enough compiler could look at the actual
22923 elaboration code and determine an appropriate correct order of elaboration,
22924 but in the general case, this is not possible. Consider the following
22925 example.
22927 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22928 that references
22929 the variable @code{Sqrt_1}, which is declared in the elaboration code
22930 of the body of @code{Unit_1}:
22932 @smallexample @c ada
22933 @cartouche
22934 Sqrt_1 : Float := Sqrt (0.1);
22935 @end cartouche
22936 @end smallexample
22938 @noindent
22939 The elaboration code of the body of @code{Unit_1} also contains:
22941 @smallexample @c ada
22942 @group
22943 @cartouche
22944 @b{if} expression_1 = 1 @b{then}
22945    Q := Unit_2.Func_2;
22946 @b{end} @b{if};
22947 @end cartouche
22948 @end group
22949 @end smallexample
22951 @noindent
22952 @code{Unit_2} is exactly parallel,
22953 it has a procedure @code{Func_2} that references
22954 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22955 the body @code{Unit_2}:
22957 @smallexample @c ada
22958 @cartouche
22959 Sqrt_2 : Float := Sqrt (0.1);
22960 @end cartouche
22961 @end smallexample
22963 @noindent
22964 The elaboration code of the body of @code{Unit_2} also contains:
22966 @smallexample @c ada
22967 @group
22968 @cartouche
22969 @b{if} expression_2 = 2 @b{then}
22970    Q := Unit_1.Func_1;
22971 @b{end} @b{if};
22972 @end cartouche
22973 @end group
22974 @end smallexample
22976 @noindent
22977 Now the question is, which of the following orders of elaboration is
22978 acceptable:
22980 @smallexample
22981 @group
22982 Spec of Unit_1
22983 Spec of Unit_2
22984 Body of Unit_1
22985 Body of Unit_2
22986 @end group
22987 @end smallexample
22989 @noindent
22992 @smallexample
22993 @group
22994 Spec of Unit_2
22995 Spec of Unit_1
22996 Body of Unit_2
22997 Body of Unit_1
22998 @end group
22999 @end smallexample
23001 @noindent
23002 If you carefully analyze the flow here, you will see that you cannot tell
23003 at compile time the answer to this question.
23004 If @code{expression_1} is not equal to 1,
23005 and @code{expression_2} is not equal to 2,
23006 then either order is acceptable, because neither of the function calls is
23007 executed. If both tests evaluate to true, then neither order is acceptable
23008 and in fact there is no correct order.
23010 If one of the two expressions is true, and the other is false, then one
23011 of the above orders is correct, and the other is incorrect. For example,
23012 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23013 then the call to @code{Func_1}
23014 will occur, but not the call to @code{Func_2.}
23015 This means that it is essential
23016 to elaborate the body of @code{Unit_1} before
23017 the body of @code{Unit_2}, so the first
23018 order of elaboration is correct and the second is wrong.
23020 By making @code{expression_1} and @code{expression_2}
23021 depend on input data, or perhaps
23022 the time of day, we can make it impossible for the compiler or binder
23023 to figure out which of these expressions will be true, and hence it
23024 is impossible to guarantee a safe order of elaboration at run time.
23026 @node Checking the Elaboration Order
23027 @section Checking the Elaboration Order
23029 @noindent
23030 In some languages that involve the same kind of elaboration problems,
23031 e.g.@: Java and C++, the programmer is expected to worry about these
23032 ordering problems himself, and it is common to
23033 write a program in which an incorrect elaboration order  gives
23034 surprising results, because it references variables before they
23035 are initialized.
23036 Ada is designed to be a safe language, and a programmer-beware approach is
23037 clearly not sufficient. Consequently, the language provides three lines
23038 of defense:
23040 @table @asis
23041 @item Standard rules
23042 Some standard rules restrict the possible choice of elaboration
23043 order. In particular, if you @code{with} a unit, then its spec is always
23044 elaborated before the unit doing the @code{with}. Similarly, a parent
23045 spec is always elaborated before the child spec, and finally
23046 a spec is always elaborated before its corresponding body.
23048 @item Dynamic elaboration checks
23049 @cindex Elaboration checks
23050 @cindex Checks, elaboration
23051 Dynamic checks are made at run time, so that if some entity is accessed
23052 before it is elaborated (typically  by means of a subprogram call)
23053 then the exception (@code{Program_Error}) is raised.
23055 @item Elaboration control
23056 Facilities are provided for the programmer to specify the desired order
23057 of elaboration.
23058 @end table
23060 Let's look at these facilities in more detail. First, the rules for
23061 dynamic checking. One possible rule would be simply to say that the
23062 exception is raised if you access a variable which has not yet been
23063 elaborated. The trouble with this approach is that it could require
23064 expensive checks on every variable reference. Instead Ada has two
23065 rules which are a little more restrictive, but easier to check, and
23066 easier to state:
23068 @table @asis
23069 @item Restrictions on calls
23070 A subprogram can only be called at elaboration time if its body
23071 has been elaborated. The rules for elaboration given above guarantee
23072 that the spec of the subprogram has been elaborated before the
23073 call, but not the body. If this rule is violated, then the
23074 exception @code{Program_Error} is raised.
23076 @item Restrictions on instantiations
23077 A generic unit can only be instantiated if the body of the generic
23078 unit has been elaborated. Again, the rules for elaboration given above
23079 guarantee that the spec of the generic unit has been elaborated
23080 before the instantiation, but not the body. If this rule is
23081 violated, then the exception @code{Program_Error} is raised.
23082 @end table
23084 @noindent
23085 The idea is that if the body has been elaborated, then any variables
23086 it references must have been elaborated; by checking for the body being
23087 elaborated we guarantee that none of its references causes any
23088 trouble. As we noted above, this is a little too restrictive, because a
23089 subprogram that has no non-local references in its body may in fact be safe
23090 to call. However, it really would be unsafe to rely on this, because
23091 it would mean that the caller was aware of details of the implementation
23092 in the body. This goes against the basic tenets of Ada.
23094 A plausible implementation can be described as follows.
23095 A Boolean variable is associated with each subprogram
23096 and each generic unit. This variable is initialized to False, and is set to
23097 True at the point body is elaborated. Every call or instantiation checks the
23098 variable, and raises @code{Program_Error} if the variable is False.
23100 Note that one might think that it would be good enough to have one Boolean
23101 variable for each package, but that would not deal with cases of trying
23102 to call a body in the same package as the call
23103 that has not been elaborated yet.
23104 Of course a compiler may be able to do enough analysis to optimize away
23105 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23106 does such optimizations, but still the easiest conceptual model is to
23107 think of there being one variable per subprogram.
23109 @node Controlling the Elaboration Order
23110 @section Controlling the Elaboration Order
23112 @noindent
23113 In the previous section we discussed the rules in Ada which ensure
23114 that @code{Program_Error} is raised if an incorrect elaboration order is
23115 chosen. This prevents erroneous executions, but we need mechanisms to
23116 specify a correct execution and avoid the exception altogether.
23117 To achieve this, Ada provides a number of features for controlling
23118 the order of elaboration. We discuss these features in this section.
23120 First, there are several ways of indicating to the compiler that a given
23121 unit has no elaboration problems:
23123 @table @asis
23124 @item packages that do not require a body
23125 A library package that does not require a body does not permit
23126 a body (this rule was introduced in Ada 95).
23127 Thus if we have a such a package, as in:
23129 @smallexample @c ada
23130 @group
23131 @cartouche
23132 @b{package} Definitions @b{is}
23133    @b{generic}
23134       @b{type} m @b{is} @b{new} integer;
23135    @b{package} Subp @b{is}
23136       @b{type} a @b{is} @b{array} (1 .. 10) @b{of} m;
23137       @b{type} b @b{is} @b{array} (1 .. 20) @b{of} m;
23138    @b{end} Subp;
23139 @b{end} Definitions;
23140 @end cartouche
23141 @end group
23142 @end smallexample
23144 @noindent
23145 A package that @code{with}'s @code{Definitions} may safely instantiate
23146 @code{Definitions.Subp} because the compiler can determine that there
23147 definitely is no package body to worry about in this case
23149 @item pragma Pure
23150 @cindex pragma Pure
23151 @findex Pure
23152 Places sufficient restrictions on a unit to guarantee that
23153 no call to any subprogram in the unit can result in an
23154 elaboration problem. This means that the compiler does not need
23155 to worry about the point of elaboration of such units, and in
23156 particular, does not need to check any calls to any subprograms
23157 in this unit.
23159 @item pragma Preelaborate
23160 @findex Preelaborate
23161 @cindex pragma Preelaborate
23162 This pragma places slightly less stringent restrictions on a unit than
23163 does pragma Pure,
23164 but these restrictions are still sufficient to ensure that there
23165 are no elaboration problems with any calls to the unit.
23167 @item pragma Elaborate_Body
23168 @findex Elaborate_Body
23169 @cindex pragma Elaborate_Body
23170 This pragma requires that the body of a unit be elaborated immediately
23171 after its spec. Suppose a unit @code{A} has such a pragma,
23172 and unit @code{B} does
23173 a @code{with} of unit @code{A}. Recall that the standard rules require
23174 the spec of unit @code{A}
23175 to be elaborated before the @code{with}'ing unit; given the pragma in
23176 @code{A}, we also know that the body of @code{A}
23177 will be elaborated before @code{B}, so
23178 that calls to @code{A} are safe and do not need a check.
23179 @end table
23181 @noindent
23182 Note that,
23183 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23184 the use of
23185 @code{Elaborate_Body} does not guarantee that the program is
23186 free of elaboration problems, because it may not be possible
23187 to satisfy the requested elaboration order.
23188 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23189 If a programmer
23190 marks @code{Unit_1} as @code{Elaborate_Body},
23191 and not @code{Unit_2,} then the order of
23192 elaboration will be:
23194 @smallexample
23195 @group
23196 Spec of Unit_2
23197 Spec of Unit_1
23198 Body of Unit_1
23199 Body of Unit_2
23200 @end group
23201 @end smallexample
23203 @noindent
23204 Now that means that the call to @code{Func_1} in @code{Unit_2}
23205 need not be checked,
23206 it must be safe. But the call to @code{Func_2} in
23207 @code{Unit_1} may still fail if
23208 @code{Expression_1} is equal to 1,
23209 and the programmer must still take
23210 responsibility for this not being the case.
23212 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23213 eliminated, except for calls entirely within a body, which are
23214 in any case fully under programmer control. However, using the pragma
23215 everywhere is not always possible.
23216 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23217 we marked both of them as having pragma @code{Elaborate_Body}, then
23218 clearly there would be no possible elaboration order.
23220 The above pragmas allow a server to guarantee safe use by clients, and
23221 clearly this is the preferable approach. Consequently a good rule
23222 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23223 and if this is not possible,
23224 mark them as @code{Elaborate_Body} if possible.
23225 As we have seen, there are situations where neither of these
23226 three pragmas can be used.
23227 So we also provide methods for clients to control the
23228 order of elaboration of the servers on which they depend:
23230 @table @asis
23231 @item pragma Elaborate (unit)
23232 @findex Elaborate
23233 @cindex pragma Elaborate
23234 This pragma is placed in the context clause, after a @code{with} clause,
23235 and it requires that the body of the named unit be elaborated before
23236 the unit in which the pragma occurs. The idea is to use this pragma
23237 if the current unit calls at elaboration time, directly or indirectly,
23238 some subprogram in the named unit.
23240 @item pragma Elaborate_All (unit)
23241 @findex Elaborate_All
23242 @cindex pragma Elaborate_All
23243 This is a stronger version of the Elaborate pragma. Consider the
23244 following example:
23246 @smallexample
23247 Unit A @code{with}'s unit B and calls B.Func in elab code
23248 Unit B @code{with}'s unit C, and B.Func calls C.Func
23249 @end smallexample
23251 @noindent
23252 Now if we put a pragma @code{Elaborate (B)}
23253 in unit @code{A}, this ensures that the
23254 body of @code{B} is elaborated before the call, but not the
23255 body of @code{C}, so
23256 the call to @code{C.Func} could still cause @code{Program_Error} to
23257 be raised.
23259 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23260 not only that the body of the named unit be elaborated before the
23261 unit doing the @code{with}, but also the bodies of all units that the
23262 named unit uses, following @code{with} links transitively. For example,
23263 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23264 then it requires
23265 not only that the body of @code{B} be elaborated before @code{A},
23266 but also the
23267 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23268 @end table
23270 @noindent
23271 We are now in a position to give a usage rule in Ada for avoiding
23272 elaboration problems, at least if dynamic dispatching and access to
23273 subprogram values are not used. We will handle these cases separately
23274 later.
23276 The rule is simple. If a unit has elaboration code that can directly or
23277 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23278 a generic package in a @code{with}'ed unit,
23279 then if the @code{with}'ed unit does not have
23280 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23281 a pragma @code{Elaborate_All}
23282 for the @code{with}'ed unit. By following this rule a client is
23283 assured that calls can be made without risk of an exception.
23285 For generic subprogram instantiations, the rule can be relaxed to
23286 require only a pragma @code{Elaborate} since elaborating the body
23287 of a subprogram cannot cause any transitive elaboration (we are
23288 not calling the subprogram in this case, just elaborating its
23289 declaration).
23291 If this rule is not followed, then a program may be in one of four
23292 states:
23294 @table @asis
23295 @item No order exists
23296 No order of elaboration exists which follows the rules, taking into
23297 account any @code{Elaborate}, @code{Elaborate_All},
23298 or @code{Elaborate_Body} pragmas. In
23299 this case, an Ada compiler must diagnose the situation at bind
23300 time, and refuse to build an executable program.
23302 @item One or more orders exist, all incorrect
23303 One or more acceptable elaboration orders exist, and all of them
23304 generate an elaboration order problem. In this case, the binder
23305 can build an executable program, but @code{Program_Error} will be raised
23306 when the program is run.
23308 @item Several orders exist, some right, some incorrect
23309 One or more acceptable elaboration orders exists, and some of them
23310 work, and some do not. The programmer has not controlled
23311 the order of elaboration, so the binder may or may not pick one of
23312 the correct orders, and the program may or may not raise an
23313 exception when it is run. This is the worst case, because it means
23314 that the program may fail when moved to another compiler, or even
23315 another version of the same compiler.
23317 @item One or more orders exists, all correct
23318 One ore more acceptable elaboration orders exist, and all of them
23319 work. In this case the program runs successfully. This state of
23320 affairs can be guaranteed by following the rule we gave above, but
23321 may be true even if the rule is not followed.
23322 @end table
23324 @noindent
23325 Note that one additional advantage of following our rules on the use
23326 of @code{Elaborate} and @code{Elaborate_All}
23327 is that the program continues to stay in the ideal (all orders OK) state
23328 even if maintenance
23329 changes some bodies of some units. Conversely, if a program that does
23330 not follow this rule happens to be safe at some point, this state of affairs
23331 may deteriorate silently as a result of maintenance changes.
23333 You may have noticed that the above discussion did not mention
23334 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23335 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23336 code in the body makes calls to some other unit, so it is still necessary
23337 to use @code{Elaborate_All} on such units.
23339 @node Controlling Elaboration in GNAT - Internal Calls
23340 @section Controlling Elaboration in GNAT - Internal Calls
23342 @noindent
23343 In the case of internal calls, i.e., calls within a single package, the
23344 programmer has full control over the order of elaboration, and it is up
23345 to the programmer to elaborate declarations in an appropriate order. For
23346 example writing:
23348 @smallexample @c ada
23349 @group
23350 @cartouche
23351 @b{function} One @b{return} Float;
23353 Q : Float := One;
23355 @b{function} One @b{return} Float @b{is}
23356 @b{begin}
23357      @b{return} 1.0;
23358 @b{end} One;
23359 @end cartouche
23360 @end group
23361 @end smallexample
23363 @noindent
23364 will obviously raise @code{Program_Error} at run time, because function
23365 One will be called before its body is elaborated. In this case GNAT will
23366 generate a warning that the call will raise @code{Program_Error}:
23368 @smallexample
23369 @group
23370 @cartouche
23371  1. procedure y is
23372  2.    function One return Float;
23373  3.
23374  4.    Q : Float := One;
23375                     |
23376     >>> warning: cannot call "One" before body is elaborated
23377     >>> warning: Program_Error will be raised at run time
23379  5.
23380  6.    function One return Float is
23381  7.    begin
23382  8.         return 1.0;
23383  9.    end One;
23385 11. begin
23386 12.    null;
23387 13. end;
23388 @end cartouche
23389 @end group
23390 @end smallexample
23392 @noindent
23393 Note that in this particular case, it is likely that the call is safe, because
23394 the function @code{One} does not access any global variables.
23395 Nevertheless in Ada, we do not want the validity of the check to depend on
23396 the contents of the body (think about the separate compilation case), so this
23397 is still wrong, as we discussed in the previous sections.
23399 The error is easily corrected by rearranging the declarations so that the
23400 body of @code{One} appears before the declaration containing the call
23401 (note that in Ada 95 and Ada 2005,
23402 declarations can appear in any order, so there is no restriction that
23403 would prevent this reordering, and if we write:
23405 @smallexample @c ada
23406 @group
23407 @cartouche
23408 @b{function} One @b{return} Float;
23410 @b{function} One @b{return} Float @b{is}
23411 @b{begin}
23412      @b{return} 1.0;
23413 @b{end} One;
23415 Q : Float := One;
23416 @end cartouche
23417 @end group
23418 @end smallexample
23420 @noindent
23421 then all is well, no warning is generated, and no
23422 @code{Program_Error} exception
23423 will be raised.
23424 Things are more complicated when a chain of subprograms is executed:
23426 @smallexample @c ada
23427 @group
23428 @cartouche
23429 @b{function} A @b{return} Integer;
23430 @b{function} B @b{return} Integer;
23431 @b{function} C @b{return} Integer;
23433 @b{function} B @b{return} Integer @b{is} @b{begin} @b{return} A; @b{end};
23434 @b{function} C @b{return} Integer @b{is} @b{begin} @b{return} B; @b{end};
23436 X : Integer := C;
23438 @b{function} A @b{return} Integer @b{is} @b{begin} @b{return} 1; @b{end};
23439 @end cartouche
23440 @end group
23441 @end smallexample
23443 @noindent
23444 Now the call to @code{C}
23445 at elaboration time in the declaration of @code{X} is correct, because
23446 the body of @code{C} is already elaborated,
23447 and the call to @code{B} within the body of
23448 @code{C} is correct, but the call
23449 to @code{A} within the body of @code{B} is incorrect, because the body
23450 of @code{A} has not been elaborated, so @code{Program_Error}
23451 will be raised on the call to @code{A}.
23452 In this case GNAT will generate a
23453 warning that @code{Program_Error} may be
23454 raised at the point of the call. Let's look at the warning:
23456 @smallexample
23457 @group
23458 @cartouche
23459  1. procedure x is
23460  2.    function A return Integer;
23461  3.    function B return Integer;
23462  4.    function C return Integer;
23463  5.
23464  6.    function B return Integer is begin return A; end;
23465                                                     |
23466     >>> warning: call to "A" before body is elaborated may
23467                  raise Program_Error
23468     >>> warning: "B" called at line 7
23469     >>> warning: "C" called at line 9
23471  7.    function C return Integer is begin return B; end;
23472  8.
23473  9.    X : Integer := C;
23475 11.    function A return Integer is begin return 1; end;
23477 13. begin
23478 14.    null;
23479 15. end;
23480 @end cartouche
23481 @end group
23482 @end smallexample
23484 @noindent
23485 Note that the message here says ``may raise'', instead of the direct case,
23486 where the message says ``will be raised''. That's because whether
23487 @code{A} is
23488 actually called depends in general on run-time flow of control.
23489 For example, if the body of @code{B} said
23491 @smallexample @c ada
23492 @group
23493 @cartouche
23494 @b{function} B @b{return} Integer @b{is}
23495 @b{begin}
23496    @b{if} some-condition-depending-on-input-data @b{then}
23497       @b{return} A;
23498    @b{else}
23499       @b{return} 1;
23500    @b{end} @b{if};
23501 @b{end} B;
23502 @end cartouche
23503 @end group
23504 @end smallexample
23506 @noindent
23507 then we could not know until run time whether the incorrect call to A would
23508 actually occur, so @code{Program_Error} might
23509 or might not be raised. It is possible for a compiler to
23510 do a better job of analyzing bodies, to
23511 determine whether or not @code{Program_Error}
23512 might be raised, but it certainly
23513 couldn't do a perfect job (that would require solving the halting problem
23514 and is provably impossible), and because this is a warning anyway, it does
23515 not seem worth the effort to do the analysis. Cases in which it
23516 would be relevant are rare.
23518 In practice, warnings of either of the forms given
23519 above will usually correspond to
23520 real errors, and should be examined carefully and eliminated.
23521 In the rare case where a warning is bogus, it can be suppressed by any of
23522 the following methods:
23524 @itemize @bullet
23525 @item
23526 Compile with the @option{-gnatws} switch set
23528 @item
23529 Suppress @code{Elaboration_Check} for the called subprogram
23531 @item
23532 Use pragma @code{Warnings_Off} to turn warnings off for the call
23533 @end itemize
23535 @noindent
23536 For the internal elaboration check case,
23537 GNAT by default generates the
23538 necessary run-time checks to ensure
23539 that @code{Program_Error} is raised if any
23540 call fails an elaboration check. Of course this can only happen if a
23541 warning has been issued as described above. The use of pragma
23542 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23543 some of these checks, meaning that it may be possible (but is not
23544 guaranteed) for a program to be able to call a subprogram whose body
23545 is not yet elaborated, without raising a @code{Program_Error} exception.
23547 @node Controlling Elaboration in GNAT - External Calls
23548 @section Controlling Elaboration in GNAT - External Calls
23550 @noindent
23551 The previous section discussed the case in which the execution of a
23552 particular thread of elaboration code occurred entirely within a
23553 single unit. This is the easy case to handle, because a programmer
23554 has direct and total control over the order of elaboration, and
23555 furthermore, checks need only be generated in cases which are rare
23556 and which the compiler can easily detect.
23557 The situation is more complex when separate compilation is taken into account.
23558 Consider the following:
23560 @smallexample @c ada
23561 @cartouche
23562 @group
23563 @b{package} Math @b{is}
23564    @b{function} Sqrt (Arg : Float) @b{return} Float;
23565 @b{end} Math;
23567 @b{package} @b{body} Math @b{is}
23568    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
23569    @b{begin}
23570          @dots{}
23571    @b{end} Sqrt;
23572 @b{end} Math;
23573 @end group
23574 @group
23575 @b{with} Math;
23576 @b{package} Stuff @b{is}
23577    X : Float := Math.Sqrt (0.5);
23578 @b{end} Stuff;
23580 @b{with} Stuff;
23581 @b{procedure} Main @b{is}
23582 @b{begin}
23583    @dots{}
23584 @b{end} Main;
23585 @end group
23586 @end cartouche
23587 @end smallexample
23589 @noindent
23590 where @code{Main} is the main program. When this program is executed, the
23591 elaboration code must first be executed, and one of the jobs of the
23592 binder is to determine the order in which the units of a program are
23593 to be elaborated. In this case we have four units: the spec and body
23594 of @code{Math},
23595 the spec of @code{Stuff} and the body of @code{Main}).
23596 In what order should the four separate sections of elaboration code
23597 be executed?
23599 There are some restrictions in the order of elaboration that the binder
23600 can choose. In particular, if unit U has a @code{with}
23601 for a package @code{X}, then you
23602 are assured that the spec of @code{X}
23603 is elaborated before U , but you are
23604 not assured that the body of @code{X}
23605 is elaborated before U.
23606 This means that in the above case, the binder is allowed to choose the
23607 order:
23609 @smallexample
23610 spec of Math
23611 spec of Stuff
23612 body of Math
23613 body of Main
23614 @end smallexample
23616 @noindent
23617 but that's not good, because now the call to @code{Math.Sqrt}
23618 that happens during
23619 the elaboration of the @code{Stuff}
23620 spec happens before the body of @code{Math.Sqrt} is
23621 elaborated, and hence causes @code{Program_Error} exception to be raised.
23622 At first glance, one might say that the binder is misbehaving, because
23623 obviously you want to elaborate the body of something you @code{with}
23624 first, but
23625 that is not a general rule that can be followed in all cases. Consider
23627 @smallexample @c ada
23628 @group
23629 @cartouche
23630 @b{package} X @b{is} @dots{}
23632 @b{package} Y @b{is} @dots{}
23634 @b{with} X;
23635 @b{package} @b{body} Y @b{is} @dots{}
23637 @b{with} Y;
23638 @b{package} @b{body} X @b{is} @dots{}
23639 @end cartouche
23640 @end group
23641 @end smallexample
23643 @noindent
23644 This is a common arrangement, and, apart from the order of elaboration
23645 problems that might arise in connection with elaboration code, this works fine.
23646 A rule that says that you must first elaborate the body of anything you
23647 @code{with} cannot work in this case:
23648 the body of @code{X} @code{with}'s @code{Y},
23649 which means you would have to
23650 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23651 which means
23652 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23653 loop that cannot be broken.
23655 It is true that the binder can in many cases guess an order of elaboration
23656 that is unlikely to cause a @code{Program_Error}
23657 exception to be raised, and it tries to do so (in the
23658 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23659 by default
23660 elaborate the body of @code{Math} right after its spec, so all will be well).
23662 However, a program that blindly relies on the binder to be helpful can
23663 get into trouble, as we discussed in the previous sections, so
23664 GNAT
23665 provides a number of facilities for assisting the programmer in
23666 developing programs that are robust with respect to elaboration order.
23668 @node Default Behavior in GNAT - Ensuring Safety
23669 @section Default Behavior in GNAT - Ensuring Safety
23671 @noindent
23672 The default behavior in GNAT ensures elaboration safety. In its
23673 default mode GNAT implements the
23674 rule we previously described as the right approach. Let's restate it:
23676 @itemize
23677 @item
23678 @emph{If a unit has elaboration code that can directly or indirectly make a
23679 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23680 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23681 does not have pragma @code{Pure} or
23682 @code{Preelaborate}, then the client should have an
23683 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23685 @emph{In the case of instantiating a generic subprogram, it is always
23686 sufficient to have only an @code{Elaborate} pragma for the
23687 @code{with}'ed unit.}
23688 @end itemize
23690 @noindent
23691 By following this rule a client is assured that calls and instantiations
23692 can be made without risk of an exception.
23694 In this mode GNAT traces all calls that are potentially made from
23695 elaboration code, and puts in any missing implicit @code{Elaborate}
23696 and @code{Elaborate_All} pragmas.
23697 The advantage of this approach is that no elaboration problems
23698 are possible if the binder can find an elaboration order that is
23699 consistent with these implicit @code{Elaborate} and
23700 @code{Elaborate_All} pragmas. The
23701 disadvantage of this approach is that no such order may exist.
23703 If the binder does not generate any diagnostics, then it means that it has
23704 found an elaboration order that is guaranteed to be safe. However, the binder
23705 may still be relying on implicitly generated @code{Elaborate} and
23706 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23707 guaranteed.
23709 If it is important to guarantee portability, then the compilations should
23710 use the
23711 @option{-gnatel}
23712 (info messages for elaboration prag mas) switch. This will cause info messages
23713 to be generated indicating the missing @code{Elaborate} and
23714 @code{Elaborate_All} pragmas.
23715 Consider the following source program:
23717 @smallexample @c ada
23718 @group
23719 @cartouche
23720 @b{with} k;
23721 @b{package} j @b{is}
23722   m : integer := k.r;
23723 @b{end};
23724 @end cartouche
23725 @end group
23726 @end smallexample
23728 @noindent
23729 where it is clear that there
23730 should be a pragma @code{Elaborate_All}
23731 for unit @code{k}. An implicit pragma will be generated, and it is
23732 likely that the binder will be able to honor it. However, if you want
23733 to port this program to some other Ada compiler than GNAT.
23734 it is safer to include the pragma explicitly in the source. If this
23735 unit is compiled with the
23736 @option{-gnatel}
23737 switch, then the compiler outputs an information message:
23739 @smallexample
23740 @group
23741 @cartouche
23742 1. with k;
23743 2. package j is
23744 3.   m : integer := k.r;
23745                      |
23746    >>> info: call to "r" may raise Program_Error
23747    >>> info: missing pragma Elaborate_All for "k"
23749 4. end;
23750 @end cartouche
23751 @end group
23752 @end smallexample
23754 @noindent
23755 and these messages can be used as a guide for supplying manually
23756 the missing pragmas. It is usually a bad idea to use this
23757 option during development. That's because it will tell you when
23758 you need to put in a pragma, but cannot tell you when it is time
23759 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23760 unnecessary dependencies and even false circularities.
23762 This default mode is more restrictive than the Ada Reference
23763 Manual, and it is possible to construct programs which will compile
23764 using the dynamic model described there, but will run into a
23765 circularity using the safer static model we have described.
23767 Of course any Ada compiler must be able to operate in a mode
23768 consistent with the requirements of the Ada Reference Manual,
23769 and in particular must have the capability of implementing the
23770 standard dynamic model of elaboration with run-time checks.
23772 In GNAT, this standard mode can be achieved either by the use of
23773 the @option{-gnatE} switch on the compiler (@command{gcc} or
23774 @command{gnatmake}) command, or by the use of the configuration pragma:
23776 @smallexample @c ada
23777 @b{pragma} Elaboration_Checks (DYNAMIC);
23778 @end smallexample
23780 @noindent
23781 Either approach will cause the unit affected to be compiled using the
23782 standard dynamic run-time elaboration checks described in the Ada
23783 Reference Manual. The static model is generally preferable, since it
23784 is clearly safer to rely on compile and link time checks rather than
23785 run-time checks. However, in the case of legacy code, it may be
23786 difficult to meet the requirements of the static model. This
23787 issue is further discussed in
23788 @ref{What to Do If the Default Elaboration Behavior Fails}.
23790 Note that the static model provides a strict subset of the allowed
23791 behavior and programs of the Ada Reference Manual, so if you do
23792 adhere to the static model and no circularities exist,
23793 then you are assured that your program will
23794 work using the dynamic model, providing that you remove any
23795 pragma Elaborate statements from the source.
23797 @node Treatment of Pragma Elaborate
23798 @section Treatment of Pragma Elaborate
23799 @cindex Pragma Elaborate
23801 @noindent
23802 The use of @code{pragma Elaborate}
23803 should generally be avoided in Ada 95 and Ada 2005 programs,
23804 since there is no guarantee that transitive calls
23805 will be properly handled. Indeed at one point, this pragma was placed
23806 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23808 Now that's a bit restrictive. In practice, the case in which
23809 @code{pragma Elaborate} is useful is when the caller knows that there
23810 are no transitive calls, or that the called unit contains all necessary
23811 transitive @code{pragma Elaborate} statements, and legacy code often
23812 contains such uses.
23814 Strictly speaking the static mode in GNAT should ignore such pragmas,
23815 since there is no assurance at compile time that the necessary safety
23816 conditions are met. In practice, this would cause GNAT to be incompatible
23817 with correctly written Ada 83 code that had all necessary
23818 @code{pragma Elaborate} statements in place. Consequently, we made the
23819 decision that GNAT in its default mode will believe that if it encounters
23820 a @code{pragma Elaborate} then the programmer knows what they are doing,
23821 and it will trust that no elaboration errors can occur.
23823 The result of this decision is two-fold. First to be safe using the
23824 static mode, you should remove all @code{pragma Elaborate} statements.
23825 Second, when fixing circularities in existing code, you can selectively
23826 use @code{pragma Elaborate} statements to convince the static mode of
23827 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23828 statement.
23830 When using the static mode with @option{-gnatwl}, any use of
23831 @code{pragma Elaborate} will generate a warning about possible
23832 problems.
23834 @node Elaboration Issues for Library Tasks
23835 @section Elaboration Issues for Library Tasks
23836 @cindex Library tasks, elaboration issues
23837 @cindex Elaboration of library tasks
23839 @noindent
23840 In this section we examine special elaboration issues that arise for
23841 programs that declare library level tasks.
23843 Generally the model of execution of an Ada program is that all units are
23844 elaborated, and then execution of the program starts. However, the
23845 declaration of library tasks definitely does not fit this model. The
23846 reason for this is that library tasks start as soon as they are declared
23847 (more precisely, as soon as the statement part of the enclosing package
23848 body is reached), that is to say before elaboration
23849 of the program is complete. This means that if such a task calls a
23850 subprogram, or an entry in another task, the callee may or may not be
23851 elaborated yet, and in the standard
23852 Reference Manual model of dynamic elaboration checks, you can even
23853 get timing dependent Program_Error exceptions, since there can be
23854 a race between the elaboration code and the task code.
23856 The static model of elaboration in GNAT seeks to avoid all such
23857 dynamic behavior, by being conservative, and the conservative
23858 approach in this particular case is to assume that all the code
23859 in a task body is potentially executed at elaboration time if
23860 a task is declared at the library level.
23862 This can definitely result in unexpected circularities. Consider
23863 the following example
23865 @smallexample @c ada
23866 @b{package} Decls @b{is}
23867   @b{task} Lib_Task @b{is}
23868      @b{entry} Start;
23869   @b{end} Lib_Task;
23871   @b{type} My_Int @b{is} @b{new} Integer;
23873   @b{function} Ident (M : My_Int) @b{return} My_Int;
23874 @b{end} Decls;
23876 @b{with} Utils;
23877 @b{package} @b{body} Decls @b{is}
23878   @b{task} @b{body} Lib_Task @b{is}
23879   @b{begin}
23880      @b{accept} Start;
23881      Utils.Put_Val (2);
23882   @b{end} Lib_Task;
23884   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
23885   @b{begin}
23886      @b{return} M;
23887   @b{end} Ident;
23888 @b{end} Decls;
23890 @b{with} Decls;
23891 @b{package} Utils @b{is}
23892   @b{procedure} Put_Val (Arg : Decls.My_Int);
23893 @b{end} Utils;
23895 @b{with} Text_IO;
23896 @b{package} @b{body} Utils @b{is}
23897   @b{procedure} Put_Val (Arg : Decls.My_Int) @b{is}
23898   @b{begin}
23899      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23900   @b{end} Put_Val;
23901 @b{end} Utils;
23903 @b{with} Decls;
23904 @b{procedure} Main @b{is}
23905 @b{begin}
23906    Decls.Lib_Task.Start;
23907 @b{end};
23908 @end smallexample
23910 @noindent
23911 If the above example is compiled in the default static elaboration
23912 mode, then a circularity occurs. The circularity comes from the call
23913 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23914 this call occurs in elaboration code, we need an implicit pragma
23915 @code{Elaborate_All} for @code{Utils}. This means that not only must
23916 the spec and body of @code{Utils} be elaborated before the body
23917 of @code{Decls}, but also the spec and body of any unit that is
23918 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23919 the body of @code{Decls}. This is the transitive implication of
23920 pragma @code{Elaborate_All} and it makes sense, because in general
23921 the body of @code{Put_Val} might have a call to something in a
23922 @code{with'ed} unit.
23924 In this case, the body of Utils (actually its spec) @code{with's}
23925 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23926 must be elaborated before itself, in case there is a call from the
23927 body of @code{Utils}.
23929 Here is the exact chain of events we are worrying about:
23931 @enumerate
23932 @item
23933 In the body of @code{Decls} a call is made from within the body of a library
23934 task to a subprogram in the package @code{Utils}. Since this call may
23935 occur at elaboration time (given that the task is activated at elaboration
23936 time), we have to assume the worst, i.e., that the
23937 call does happen at elaboration time.
23939 @item
23940 This means that the body and spec of @code{Util} must be elaborated before
23941 the body of @code{Decls} so that this call does not cause an access before
23942 elaboration.
23944 @item
23945 Within the body of @code{Util}, specifically within the body of
23946 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23947 by this package.
23949 @item
23950 One such @code{with}'ed package is package @code{Decls}, so there
23951 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23952 In fact there is such a call in this example, but we would have to
23953 assume that there was such a call even if it were not there, since
23954 we are not supposed to write the body of @code{Decls} knowing what
23955 is in the body of @code{Utils}; certainly in the case of the
23956 static elaboration model, the compiler does not know what is in
23957 other bodies and must assume the worst.
23959 @item
23960 This means that the spec and body of @code{Decls} must also be
23961 elaborated before we elaborate the unit containing the call, but
23962 that unit is @code{Decls}! This means that the body of @code{Decls}
23963 must be elaborated before itself, and that's a circularity.
23964 @end enumerate
23966 @noindent
23967 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23968 the body of @code{Decls} you will get a true Ada Reference Manual
23969 circularity that makes the program illegal.
23971 In practice, we have found that problems with the static model of
23972 elaboration in existing code often arise from library tasks, so
23973 we must address this particular situation.
23975 Note that if we compile and run the program above, using the dynamic model of
23976 elaboration (that is to say use the @option{-gnatE} switch),
23977 then it compiles, binds,
23978 links, and runs, printing the expected result of 2. Therefore in some sense
23979 the circularity here is only apparent, and we need to capture
23980 the properties of this program that  distinguish it from other library-level
23981 tasks that have real elaboration problems.
23983 We have four possible answers to this question:
23985 @itemize @bullet
23987 @item
23988 Use the dynamic model of elaboration.
23990 If we use the @option{-gnatE} switch, then as noted above, the program works.
23991 Why is this? If we examine the task body, it is apparent that the task cannot
23992 proceed past the
23993 @code{accept} statement until after elaboration has been completed, because
23994 the corresponding entry call comes from the main program, not earlier.
23995 This is why the dynamic model works here. But that's really giving
23996 up on a precise analysis, and we prefer to take this approach only if we cannot
23997 solve the
23998 problem in any other manner. So let us examine two ways to reorganize
23999 the program to avoid the potential elaboration problem.
24001 @item
24002 Split library tasks into separate packages.
24004 Write separate packages, so that library tasks are isolated from
24005 other declarations as much as possible. Let us look at a variation on
24006 the above program.
24008 @smallexample @c ada
24009 @b{package} Decls1 @b{is}
24010   @b{task} Lib_Task @b{is}
24011      @b{entry} Start;
24012   @b{end} Lib_Task;
24013 @b{end} Decls1;
24015 @b{with} Utils;
24016 @b{package} @b{body} Decls1 @b{is}
24017   @b{task} @b{body} Lib_Task @b{is}
24018   @b{begin}
24019      @b{accept} Start;
24020      Utils.Put_Val (2);
24021   @b{end} Lib_Task;
24022 @b{end} Decls1;
24024 @b{package} Decls2 @b{is}
24025   @b{type} My_Int @b{is} @b{new} Integer;
24026   @b{function} Ident (M : My_Int) @b{return} My_Int;
24027 @b{end} Decls2;
24029 @b{with} Utils;
24030 @b{package} @b{body} Decls2 @b{is}
24031   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24032   @b{begin}
24033      @b{return} M;
24034   @b{end} Ident;
24035 @b{end} Decls2;
24037 @b{with} Decls2;
24038 @b{package} Utils @b{is}
24039   @b{procedure} Put_Val (Arg : Decls2.My_Int);
24040 @b{end} Utils;
24042 @b{with} Text_IO;
24043 @b{package} @b{body} Utils @b{is}
24044   @b{procedure} Put_Val (Arg : Decls2.My_Int) @b{is}
24045   @b{begin}
24046      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24047   @b{end} Put_Val;
24048 @b{end} Utils;
24050 @b{with} Decls1;
24051 @b{procedure} Main @b{is}
24052 @b{begin}
24053    Decls1.Lib_Task.Start;
24054 @b{end};
24055 @end smallexample
24057 @noindent
24058 All we have done is to split @code{Decls} into two packages, one
24059 containing the library task, and one containing everything else. Now
24060 there is no cycle, and the program compiles, binds, links and executes
24061 using the default static model of elaboration.
24063 @item
24064 Declare separate task types.
24066 A significant part of the problem arises because of the use of the
24067 single task declaration form. This means that the elaboration of
24068 the task type, and the elaboration of the task itself (i.e.@: the
24069 creation of the task) happen at the same time. A good rule
24070 of style in Ada is to always create explicit task types. By
24071 following the additional step of placing task objects in separate
24072 packages from the task type declaration, many elaboration problems
24073 are avoided. Here is another modified example of the example program:
24075 @smallexample @c ada
24076 @b{package} Decls @b{is}
24077   @b{task} @b{type} Lib_Task_Type @b{is}
24078      @b{entry} Start;
24079   @b{end} Lib_Task_Type;
24081   @b{type} My_Int @b{is} @b{new} Integer;
24083   @b{function} Ident (M : My_Int) @b{return} My_Int;
24084 @b{end} Decls;
24086 @b{with} Utils;
24087 @b{package} @b{body} Decls @b{is}
24088   @b{task} @b{body} Lib_Task_Type @b{is}
24089   @b{begin}
24090      @b{accept} Start;
24091      Utils.Put_Val (2);
24092   @b{end} Lib_Task_Type;
24094   @b{function} Ident (M : My_Int) @b{return} My_Int @b{is}
24095   @b{begin}
24096      @b{return} M;
24097   @b{end} Ident;
24098 @b{end} Decls;
24100 @b{with} Decls;
24101 @b{package} Utils @b{is}
24102   @b{procedure} Put_Val (Arg : Decls.My_Int);
24103 @b{end} Utils;
24105 @b{with} Text_IO;
24106 @b{package} @b{body} Utils @b{is}
24107   @b{procedure} Put_Val (Arg : Decls.My_Int) @b{is}
24108   @b{begin}
24109      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24110   @b{end} Put_Val;
24111 @b{end} Utils;
24113 @b{with} Decls;
24114 @b{package} Declst @b{is}
24115    Lib_Task : Decls.Lib_Task_Type;
24116 @b{end} Declst;
24118 @b{with} Declst;
24119 @b{procedure} Main @b{is}
24120 @b{begin}
24121    Declst.Lib_Task.Start;
24122 @b{end};
24123 @end smallexample
24125 @noindent
24126 What we have done here is to replace the @code{task} declaration in
24127 package @code{Decls} with a @code{task type} declaration. Then we
24128 introduce a separate package @code{Declst} to contain the actual
24129 task object. This separates the elaboration issues for
24130 the @code{task type}
24131 declaration, which causes no trouble, from the elaboration issues
24132 of the task object, which is also unproblematic, since it is now independent
24133 of the elaboration of  @code{Utils}.
24134 This separation of concerns also corresponds to
24135 a generally sound engineering principle of separating declarations
24136 from instances. This version of the program also compiles, binds, links,
24137 and executes, generating the expected output.
24139 @item
24140 Use No_Entry_Calls_In_Elaboration_Code restriction.
24141 @cindex No_Entry_Calls_In_Elaboration_Code
24143 The previous two approaches described how a program can be restructured
24144 to avoid the special problems caused by library task bodies. in practice,
24145 however, such restructuring may be difficult to apply to existing legacy code,
24146 so we must consider solutions that do not require massive rewriting.
24148 Let us consider more carefully why our original sample program works
24149 under the dynamic model of elaboration. The reason is that the code
24150 in the task body blocks immediately on the @code{accept}
24151 statement. Now of course there is nothing to prohibit elaboration
24152 code from making entry calls (for example from another library level task),
24153 so we cannot tell in isolation that
24154 the task will not execute the accept statement  during elaboration.
24156 However, in practice it is very unusual to see elaboration code
24157 make any entry calls, and the pattern of tasks starting
24158 at elaboration time and then immediately blocking on @code{accept} or
24159 @code{select} statements is very common. What this means is that
24160 the compiler is being too pessimistic when it analyzes the
24161 whole package body as though it might be executed at elaboration
24162 time.
24164 If we know that the elaboration code contains no entry calls, (a very safe
24165 assumption most of the time, that could almost be made the default
24166 behavior), then we can compile all units of the program under control
24167 of the following configuration pragma:
24169 @smallexample
24170 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24171 @end smallexample
24173 @noindent
24174 This pragma can be placed in the @file{gnat.adc} file in the usual
24175 manner. If we take our original unmodified program and compile it
24176 in the presence of a @file{gnat.adc} containing the above pragma,
24177 then once again, we can compile, bind, link, and execute, obtaining
24178 the expected result. In the presence of this pragma, the compiler does
24179 not trace calls in a task body, that appear after the first @code{accept}
24180 or @code{select} statement, and therefore does not report a potential
24181 circularity in the original program.
24183 The compiler will check to the extent it can that the above
24184 restriction is not violated, but it is not always possible to do a
24185 complete check at compile time, so it is important to use this
24186 pragma only if the stated restriction is in fact met, that is to say
24187 no task receives an entry call before elaboration of all units is completed.
24189 @end itemize
24191 @node Mixing Elaboration Models
24192 @section Mixing Elaboration Models
24193 @noindent
24194 So far, we have assumed that the entire program is either compiled
24195 using the dynamic model or static model, ensuring consistency. It
24196 is possible to mix the two models, but rules have to be followed
24197 if this mixing is done to ensure that elaboration checks are not
24198 omitted.
24200 The basic rule is that @emph{a unit compiled with the static model cannot
24201 be @code{with'ed} by a unit compiled with the dynamic model}. The
24202 reason for this is that in the static model, a unit assumes that
24203 its clients guarantee to use (the equivalent of) pragma
24204 @code{Elaborate_All} so that no elaboration checks are required
24205 in inner subprograms, and this assumption is violated if the
24206 client is compiled with dynamic checks.
24208 The precise rule is as follows. A unit that is compiled with dynamic
24209 checks can only @code{with} a unit that meets at least one of the
24210 following criteria:
24212 @itemize @bullet
24214 @item
24215 The @code{with'ed} unit is itself compiled with dynamic elaboration
24216 checks (that is with the @option{-gnatE} switch.
24218 @item
24219 The @code{with'ed} unit is an internal GNAT implementation unit from
24220 the System, Interfaces, Ada, or GNAT hierarchies.
24222 @item
24223 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24225 @item
24226 The @code{with'ing} unit (that is the client) has an explicit pragma
24227 @code{Elaborate_All} for the @code{with'ed} unit.
24229 @end itemize
24231 @noindent
24232 If this rule is violated, that is if a unit with dynamic elaboration
24233 checks @code{with's} a unit that does not meet one of the above four
24234 criteria, then the binder (@code{gnatbind}) will issue a warning
24235 similar to that in the following example:
24237 @smallexample
24238 warning: "x.ads" has dynamic elaboration checks and with's
24239 warning:   "y.ads" which has static elaboration checks
24240 @end smallexample
24242 @noindent
24243 These warnings indicate that the rule has been violated, and that as a result
24244 elaboration checks may be missed in the resulting executable file.
24245 This warning may be suppressed using the @option{-ws} binder switch
24246 in the usual manner.
24248 One useful application of this mixing rule is in the case of a subsystem
24249 which does not itself @code{with} units from the remainder of the
24250 application. In this case, the entire subsystem can be compiled with
24251 dynamic checks to resolve a circularity in the subsystem, while
24252 allowing the main application that uses this subsystem to be compiled
24253 using the more reliable default static model.
24255 @node What to Do If the Default Elaboration Behavior Fails
24256 @section What to Do If the Default Elaboration Behavior Fails
24258 @noindent
24259 If the binder cannot find an acceptable order, it outputs detailed
24260 diagnostics. For example:
24261 @smallexample
24262 @group
24263 @iftex
24264 @leftskip=0cm
24265 @end iftex
24266 error: elaboration circularity detected
24267 info:   "proc (body)" must be elaborated before "pack (body)"
24268 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24269 info:     recompile "pack (body)" with -gnatel
24270 info:                             for full details
24271 info:       "proc (body)"
24272 info:         is needed by its spec:
24273 info:       "proc (spec)"
24274 info:         which is withed by:
24275 info:       "pack (body)"
24276 info:  "pack (body)" must be elaborated before "proc (body)"
24277 info:     reason: pragma Elaborate in unit "proc (body)"
24278 @end group
24280 @end smallexample
24282 @noindent
24283 In this case we have a cycle that the binder cannot break. On the one
24284 hand, there is an explicit pragma Elaborate in @code{proc} for
24285 @code{pack}. This means that the body of @code{pack} must be elaborated
24286 before the body of @code{proc}. On the other hand, there is elaboration
24287 code in @code{pack} that calls a subprogram in @code{proc}. This means
24288 that for maximum safety, there should really be a pragma
24289 Elaborate_All in @code{pack} for @code{proc} which would require that
24290 the body of @code{proc} be elaborated before the body of
24291 @code{pack}. Clearly both requirements cannot be satisfied.
24292 Faced with a circularity of this kind, you have three different options.
24294 @table @asis
24295 @item Fix the program
24296 The most desirable option from the point of view of long-term maintenance
24297 is to rearrange the program so that the elaboration problems are avoided.
24298 One useful technique is to place the elaboration code into separate
24299 child packages. Another is to move some of the initialization code to
24300 explicitly called subprograms, where the program controls the order
24301 of initialization explicitly. Although this is the most desirable option,
24302 it may be impractical and involve too much modification, especially in
24303 the case of complex legacy code.
24305 @item Perform dynamic checks
24306 If the compilations are done using the
24307 @option{-gnatE}
24308 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24309 manner. Dynamic checks are generated for all calls that could possibly result
24310 in raising an exception. With this switch, the compiler does not generate
24311 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24312 exactly as specified in the @cite{Ada Reference Manual}.
24313 The binder will generate
24314 an executable program that may or may not raise @code{Program_Error}, and then
24315 it is the programmer's job to ensure that it does not raise an exception. Note
24316 that it is important to compile all units with the switch, it cannot be used
24317 selectively.
24319 @item Suppress checks
24320 The drawback of dynamic checks is that they generate a
24321 significant overhead at run time, both in space and time. If you
24322 are absolutely sure that your program cannot raise any elaboration
24323 exceptions, and you still want to use the dynamic elaboration model,
24324 then you can use the configuration pragma
24325 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24326 example this pragma could be placed in the @file{gnat.adc} file.
24328 @item Suppress checks selectively
24329 When you know that certain calls or instantiations in elaboration code cannot
24330 possibly lead to an elaboration error, and the binder nevertheless complains
24331 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24332 elaboration circularities, it is possible to remove those warnings locally and
24333 obtain a program that will bind. Clearly this can be unsafe, and it is the
24334 responsibility of the programmer to make sure that the resulting program has no
24335 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24336 used with different granularity to suppress warnings and break elaboration
24337 circularities:
24339 @itemize @bullet
24340 @item
24341 Place the pragma that names the called subprogram in the declarative part
24342 that contains the call.
24344 @item
24345 Place the pragma in the declarative part, without naming an entity. This
24346 disables warnings on all calls in the corresponding  declarative region.
24348 @item
24349 Place the pragma in the package spec that declares the called subprogram,
24350 and name the subprogram. This disables warnings on all elaboration calls to
24351 that subprogram.
24353 @item
24354 Place the pragma in the package spec that declares the called subprogram,
24355 without naming any entity. This disables warnings on all elaboration calls to
24356 all subprograms declared in this spec.
24358 @item Use Pragma Elaborate
24359 As previously described in section @xref{Treatment of Pragma Elaborate},
24360 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24361 that no elaboration checks are required on calls to the designated unit.
24362 There may be cases in which the caller knows that no transitive calls
24363 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24364 case where @code{pragma Elaborate_All} would cause a circularity.
24365 @end itemize
24367 @noindent
24368 These five cases are listed in order of decreasing safety, and therefore
24369 require increasing programmer care in their application. Consider the
24370 following program:
24372 @smallexample @c adanocomment
24373 @b{package} Pack1 @b{is}
24374   @b{function} F1 @b{return} Integer;
24375   X1 : Integer;
24376 @b{end} Pack1;
24378 @b{package} Pack2 @b{is}
24379   @b{function} F2 @b{return} Integer;
24380   @b{function} Pure (x : integer) @b{return} integer;
24381   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24382   --  pragma Suppress (Elaboration_Check);              -- (4)
24383 @b{end} Pack2;
24385 @b{with} Pack2;
24386 @b{package} @b{body} Pack1 @b{is}
24387   @b{function} F1 @b{return} Integer @b{is}
24388   @b{begin}
24389     @b{return} 100;
24390   @b{end} F1;
24391   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24392 @b{begin}
24393   @b{declare}
24394     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24395     --  pragma Suppress(Elaboration_Check);             -- (2)
24396   @b{begin}
24397     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24398   @b{end};
24399 @b{end} Pack1;
24401 @b{with} Pack1;
24402 @b{package} @b{body} Pack2 @b{is}
24403   @b{function} F2 @b{return} Integer @b{is}
24404   @b{begin}
24405      @b{return} Pack1.F1;
24406   @b{end} F2;
24407   @b{function} Pure (x : integer) @b{return} integer @b{is}
24408   @b{begin}
24409      @b{return} x ** 3 - 3 * x;
24410   @b{end};
24411 @b{end} Pack2;
24413 @b{with} Pack1, Ada.Text_IO;
24414 @b{procedure} Proc3 @b{is}
24415 @b{begin}
24416   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24417 @b{end} Proc3;
24418 @end smallexample
24419 In the absence of any pragmas, an attempt to bind this program produces
24420 the following diagnostics:
24421 @smallexample
24422 @group
24423 @iftex
24424 @leftskip=.5cm
24425 @end iftex
24426 error: elaboration circularity detected
24427 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24428 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24429 info:       recompile "pack1 (body)" with -gnatel for full details
24430 info:          "pack1 (body)"
24431 info:             must be elaborated along with its spec:
24432 info:          "pack1 (spec)"
24433 info:             which is withed by:
24434 info:          "pack2 (body)"
24435 info:             which must be elaborated along with its spec:
24436 info:          "pack2 (spec)"
24437 info:             which is withed by:
24438 info:          "pack1 (body)"
24439 @end group
24440 @end smallexample
24441 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24442 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24443 F2 is safe, even though F2 calls F1, because the call appears after the
24444 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24445 remove the warning on the call. It is also possible to use pragma (2)
24446 because there are no other potentially unsafe calls in the block.
24448 @noindent
24449 The call to @code{Pure} is safe because this function does not depend on the
24450 state of @code{Pack2}. Therefore any call to this function is safe, and it
24451 is correct to place pragma (3) in the corresponding package spec.
24453 @noindent
24454 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24455 warnings on all calls to functions declared therein. Note that this is not
24456 necessarily safe, and requires more detailed examination of the subprogram
24457 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24458 be already elaborated.
24459 @end table
24461 @noindent
24462 It is hard to generalize on which of these four approaches should be
24463 taken. Obviously if it is possible to fix the program so that the default
24464 treatment works, this is preferable, but this may not always be practical.
24465 It is certainly simple enough to use
24466 @option{-gnatE}
24467 but the danger in this case is that, even if the GNAT binder
24468 finds a correct elaboration order, it may not always do so,
24469 and certainly a binder from another Ada compiler might not. A
24470 combination of testing and analysis (for which the
24471 information messages generated with the
24472 @option{-gnatel}
24473 switch can be useful) must be used to ensure that the program is free
24474 of errors. One switch that is useful in this testing is the
24475 @option{-p (pessimistic elaboration order)}
24476 switch for
24477 @code{gnatbind}.
24478 Normally the binder tries to find an order that has the best chance
24479 of avoiding elaboration problems. However, if this switch is used, the binder
24480 plays a devil's advocate role, and tries to choose the order that
24481 has the best chance of failing. If your program works even with this
24482 switch, then it has a better chance of being error free, but this is still
24483 not a guarantee.
24485 For an example of this approach in action, consider the C-tests (executable
24486 tests) from the ACVC suite. If these are compiled and run with the default
24487 treatment, then all but one of them succeed without generating any error
24488 diagnostics from the binder. However, there is one test that fails, and
24489 this is not surprising, because the whole point of this test is to ensure
24490 that the compiler can handle cases where it is impossible to determine
24491 a correct order statically, and it checks that an exception is indeed
24492 raised at run time.
24494 This one test must be compiled and run using the
24495 @option{-gnatE}
24496 switch, and then it passes. Alternatively, the entire suite can
24497 be run using this switch. It is never wrong to run with the dynamic
24498 elaboration switch if your code is correct, and we assume that the
24499 C-tests are indeed correct (it is less efficient, but efficiency is
24500 not a factor in running the ACVC tests.)
24502 @node Elaboration for Indirect Calls
24503 @section Elaboration for Indirect Calls
24504 @cindex Dispatching calls
24505 @cindex Indirect calls
24507 @noindent
24508 In rare cases, the static elaboration model fails to prevent
24509 dispatching calls to not-yet-elaborated subprograms. In such cases, we
24510 fall back to run-time checks; premature calls to any primitive
24511 operation of a tagged type before the body of the operation has been
24512 elaborated will raise @code{Program_Error}.
24514 Access-to-subprogram types, however, are handled conservatively, and
24515 do not require run-time checks. This was not true in earlier versions
24516 of the compiler; you can use the @option{-gnatd.U} debug switch to
24517 revert to the old behavior if the new conservative behavior causes
24518 elaboration cycles. Here, ``conservative'' means that if you do
24519 @code{P'Access} during elaboration, the compiler will assume that you
24520 might call @code{P} indirectly during elaboration, so it adds an
24521 implicit @code{pragma Elaborate_All} on the library unit containing
24522 @code{P}. The @option{-gnatd.U} switch is safe if you know there are
24523 no such calls. If the program worked before, it will continue to work
24524 with @option{-gnatd.U}. But beware that code modifications such as
24525 adding an indirect call can cause erroneous behavior in the presence
24526 of @option{-gnatd.U}.
24528 @node Summary of Procedures for Elaboration Control
24529 @section Summary of Procedures for Elaboration Control
24530 @cindex Elaboration control
24532 @noindent
24533 First, compile your program with the default options, using none of
24534 the special elaboration control switches. If the binder successfully
24535 binds your program, then you can be confident that, apart from issues
24536 raised by the use of access-to-subprogram types and dynamic dispatching,
24537 the program is free of elaboration errors. If it is important that the
24538 program be portable to other compilers than GNAT, then use the
24539 @option{-gnatel}
24540 switch to generate messages about missing @code{Elaborate} or
24541 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24543 If the program fails to bind using the default static elaboration
24544 handling, then you can fix the program to eliminate the binder
24545 message, or recompile the entire program with the
24546 @option{-gnatE} switch to generate dynamic elaboration checks,
24547 and, if you are sure there really are no elaboration problems,
24548 use a global pragma @code{Suppress (Elaboration_Check)}.
24550 @node Other Elaboration Order Considerations
24551 @section Other Elaboration Order Considerations
24552 @noindent
24553 This section has been entirely concerned with the issue of finding a valid
24554 elaboration order, as defined by the Ada Reference Manual. In a case
24555 where several elaboration orders are valid, the task is to find one
24556 of the possible valid elaboration orders (and the static model in GNAT
24557 will ensure that this is achieved).
24559 The purpose of the elaboration rules in the Ada Reference Manual is to
24560 make sure that no entity is accessed before it has been elaborated. For
24561 a subprogram, this means that the spec and body must have been elaborated
24562 before the subprogram is called. For an object, this means that the object
24563 must have been elaborated before its value is read or written. A violation
24564 of either of these two requirements is an access before elaboration order,
24565 and this section has been all about avoiding such errors.
24567 In the case where more than one order of elaboration is possible, in the
24568 sense that access before elaboration errors are avoided, then any one of
24569 the orders is ``correct'' in the sense that it meets the requirements of
24570 the Ada Reference Manual, and no such error occurs.
24572 However, it may be the case for a given program, that there are
24573 constraints on the order of elaboration that come not from consideration
24574 of avoiding elaboration errors, but rather from extra-lingual logic
24575 requirements. Consider this example:
24577 @smallexample @c ada
24578 @b{with} Init_Constants;
24579 @b{package} Constants @b{is}
24580    X : Integer := 0;
24581    Y : Integer := 0;
24582 @b{end} Constants;
24584 @b{package} Init_Constants @b{is}
24585    @b{procedure} P; --@i{ require a body}
24586 @b{end} Init_Constants;
24588 @b{with} Constants;
24589 @b{package} @b{body} Init_Constants @b{is}
24590    @b{procedure} P @b{is} @b{begin} @b{null}; @b{end};
24591 @b{begin}
24592    Constants.X := 3;
24593    Constants.Y := 4;
24594 @b{end} Init_Constants;
24596 @b{with} Constants;
24597 @b{package} Calc @b{is}
24598    Z : Integer := Constants.X + Constants.Y;
24599 @b{end} Calc;
24601 @b{with} Calc;
24602 @b{with} Text_IO; @b{use} Text_IO;
24603 @b{procedure} Main @b{is}
24604 @b{begin}
24605    Put_Line (Calc.Z'Img);
24606 @b{end} Main;
24607 @end smallexample
24609 @noindent
24610 In this example, there is more than one valid order of elaboration. For
24611 example both the following are correct orders:
24613 @smallexample
24614 Init_Constants spec
24615 Constants spec
24616 Calc spec
24617 Init_Constants body
24618 Main body
24620   and
24622 Init_Constants spec
24623 Init_Constants body
24624 Constants spec
24625 Calc spec
24626 Main body
24627 @end smallexample
24629 @noindent
24630 There is no language rule to prefer one or the other, both are correct
24631 from an order of elaboration point of view. But the programmatic effects
24632 of the two orders are very different. In the first, the elaboration routine
24633 of @code{Calc} initializes @code{Z} to zero, and then the main program
24634 runs with this value of zero. But in the second order, the elaboration
24635 routine of @code{Calc} runs after the body of Init_Constants has set
24636 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24637 runs.
24639 One could perhaps by applying pretty clever non-artificial intelligence
24640 to the situation guess that it is more likely that the second order of
24641 elaboration is the one desired, but there is no formal linguistic reason
24642 to prefer one over the other. In fact in this particular case, GNAT will
24643 prefer the second order, because of the rule that bodies are elaborated
24644 as soon as possible, but it's just luck that this is what was wanted
24645 (if indeed the second order was preferred).
24647 If the program cares about the order of elaboration routines in a case like
24648 this, it is important to specify the order required. In this particular
24649 case, that could have been achieved by adding to the spec of Calc:
24651 @smallexample @c ada
24652 @b{pragma} Elaborate_All (Constants);
24653 @end smallexample
24655 @noindent
24656 which requires that the body (if any) and spec of @code{Constants},
24657 as well as the body and spec of any unit @code{with}'ed by
24658 @code{Constants} be elaborated before @code{Calc} is elaborated.
24660 Clearly no automatic method can always guess which alternative you require,
24661 and if you are working with legacy code that had constraints of this kind
24662 which were not properly specified by adding @code{Elaborate} or
24663 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24664 compilers can choose different orders.
24666 However, GNAT does attempt to diagnose the common situation where there
24667 are uninitialized variables in the visible part of a package spec, and the
24668 corresponding package body has an elaboration block that directly or
24669 indirectly initialized one or more of these variables. This is the situation
24670 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24671 a warning that suggests this addition if it detects this situation.
24673 The @code{gnatbind}
24674 @option{-p} switch may be useful in smoking
24675 out problems. This switch causes bodies to be elaborated as late as possible
24676 instead of as early as possible. In the example above, it would have forced
24677 the choice of the first elaboration order. If you get different results
24678 when using this switch, and particularly if one set of results is right,
24679 and one is wrong as far as you are concerned, it shows that you have some
24680 missing @code{Elaborate} pragmas. For the example above, we have the
24681 following output:
24683 @smallexample
24684 gnatmake -f -q main
24685 main
24687 gnatmake -f -q main -bargs -p
24688 main
24690 @end smallexample
24692 @noindent
24693 It is of course quite unlikely that both these results are correct, so
24694 it is up to you in a case like this to investigate the source of the
24695 difference, by looking at the two elaboration orders that are chosen,
24696 and figuring out which is correct, and then adding the necessary
24697 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24699 @node Determining the Chosen Elaboration Order
24700 @section Determining the Chosen Elaboration Order
24701 @noindent
24703 To see the elaboration order that the binder chooses, you can look at
24704 the last part of the b~xxx.adb binder output file. Here is an example:
24706 @smallexample @c ada
24707 System.Soft_Links'Elab_Body;
24708 E14 := True;
24709 System.Secondary_Stack'Elab_Body;
24710 E18 := True;
24711 System.Exception_Table'Elab_Body;
24712 E24 := True;
24713 Ada.Io_Exceptions'Elab_Spec;
24714 E67 := True;
24715 Ada.Tags'Elab_Spec;
24716 Ada.Streams'Elab_Spec;
24717 E43 := True;
24718 Interfaces.C'Elab_Spec;
24719 E69 := True;
24720 System.Finalization_Root'Elab_Spec;
24721 E60 := True;
24722 System.Os_Lib'Elab_Body;
24723 E71 := True;
24724 System.Finalization_Implementation'Elab_Spec;
24725 System.Finalization_Implementation'Elab_Body;
24726 E62 := True;
24727 Ada.Finalization'Elab_Spec;
24728 E58 := True;
24729 Ada.Finalization.List_Controller'Elab_Spec;
24730 E76 := True;
24731 System.File_Control_Block'Elab_Spec;
24732 E74 := True;
24733 System.File_Io'Elab_Body;
24734 E56 := True;
24735 Ada.Tags'Elab_Body;
24736 E45 := True;
24737 Ada.Text_Io'Elab_Spec;
24738 Ada.Text_Io'Elab_Body;
24739 E07 := True;
24740 @end smallexample
24742 @noindent
24743 Here Elab_Spec elaborates the spec
24744 and Elab_Body elaborates the body. The assignments to the Exx flags
24745 flag that the corresponding body is now elaborated.
24747 You can also ask the binder to generate a more
24748 readable list of the elaboration order using the
24749 @code{-l} switch when invoking the binder. Here is
24750 an example of the output generated by this switch:
24752 @smallexample
24753 ada (spec)
24754 interfaces (spec)
24755 system (spec)
24756 system.case_util (spec)
24757 system.case_util (body)
24758 system.concat_2 (spec)
24759 system.concat_2 (body)
24760 system.concat_3 (spec)
24761 system.concat_3 (body)
24762 system.htable (spec)
24763 system.parameters (spec)
24764 system.parameters (body)
24765 system.crtl (spec)
24766 interfaces.c_streams (spec)
24767 interfaces.c_streams (body)
24768 system.restrictions (spec)
24769 system.restrictions (body)
24770 system.standard_library (spec)
24771 system.exceptions (spec)
24772 system.exceptions (body)
24773 system.storage_elements (spec)
24774 system.storage_elements (body)
24775 system.secondary_stack (spec)
24776 system.stack_checking (spec)
24777 system.stack_checking (body)
24778 system.string_hash (spec)
24779 system.string_hash (body)
24780 system.htable (body)
24781 system.strings (spec)
24782 system.strings (body)
24783 system.traceback (spec)
24784 system.traceback (body)
24785 system.traceback_entries (spec)
24786 system.traceback_entries (body)
24787 ada.exceptions (spec)
24788 ada.exceptions.last_chance_handler (spec)
24789 system.soft_links (spec)
24790 system.soft_links (body)
24791 ada.exceptions.last_chance_handler (body)
24792 system.secondary_stack (body)
24793 system.exception_table (spec)
24794 system.exception_table (body)
24795 ada.io_exceptions (spec)
24796 ada.tags (spec)
24797 ada.streams (spec)
24798 interfaces.c (spec)
24799 interfaces.c (body)
24800 system.finalization_root (spec)
24801 system.finalization_root (body)
24802 system.memory (spec)
24803 system.memory (body)
24804 system.standard_library (body)
24805 system.os_lib (spec)
24806 system.os_lib (body)
24807 system.unsigned_types (spec)
24808 system.stream_attributes (spec)
24809 system.stream_attributes (body)
24810 system.finalization_implementation (spec)
24811 system.finalization_implementation (body)
24812 ada.finalization (spec)
24813 ada.finalization (body)
24814 ada.finalization.list_controller (spec)
24815 ada.finalization.list_controller (body)
24816 system.file_control_block (spec)
24817 system.file_io (spec)
24818 system.file_io (body)
24819 system.val_uns (spec)
24820 system.val_util (spec)
24821 system.val_util (body)
24822 system.val_uns (body)
24823 system.wch_con (spec)
24824 system.wch_con (body)
24825 system.wch_cnv (spec)
24826 system.wch_jis (spec)
24827 system.wch_jis (body)
24828 system.wch_cnv (body)
24829 system.wch_stw (spec)
24830 system.wch_stw (body)
24831 ada.tags (body)
24832 ada.exceptions (body)
24833 ada.text_io (spec)
24834 ada.text_io (body)
24835 text_io (spec)
24836 gdbstr (body)
24837 @end smallexample
24839 @c **********************************
24840 @node Overflow Check Handling in GNAT
24841 @appendix Overflow Check Handling in GNAT
24842 @cindex Overflow checks
24843 @cindex Checks (overflow)
24844 @c **********************************
24846 @menu
24847 * Background::
24848 * Overflow Checking Modes in GNAT::
24849 * Specifying the Desired Mode::
24850 * Default Settings::
24851 * Implementation Notes::
24852 @end menu
24855 @node Background
24856 @section Background
24858 @noindent
24859 Overflow checks are checks that the compiler may make to ensure
24860 that intermediate results are not out of range. For example:
24862 @smallexample @c ada
24863    A : Integer;
24864    ...
24865    A := A + 1;
24866 @end smallexample
24868 @noindent
24869 if @code{A} has the value @code{Integer'Last}, then the addition may cause
24870 overflow since the result is out of range of the type @code{Integer}.
24871 In this case @code{Constraint_Error} will be raised if checks are
24872 enabled.
24874 A trickier situation arises in examples like the following:
24876 @smallexample @c ada
24877   A, C : Integer;
24878   ...
24879   A := (A + 1) + C;
24880 @end smallexample
24882 @noindent
24883 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
24884 Now the final result of the expression on the right hand side is
24885 @code{Integer'Last} which is in range, but the question arises whether the
24886 intermediate addition of @code{(A + 1)} raises an overflow error.
24888 The (perhaps surprising) answer is that the Ada language
24889 definition does not answer this question. Instead it leaves
24890 it up to the implementation to do one of two things if overflow
24891 checks are enabled.
24893 @itemize @bullet
24894 @item
24895 raise an exception (@code{Constraint_Error}), or
24897 @item
24898 yield the correct mathematical result which is then used in
24899 subsequent operations.
24900 @end itemize
24902 @noindent
24903 If the compiler chooses the first approach, then the assignment of this
24904 example will indeed raise @code{Constraint_Error} if overflow checking is
24905 enabled, or result in erroneous execution if overflow checks are suppressed.
24907 But if the compiler
24908 chooses the second approach, then it can perform both additions yielding
24909 the correct mathematical result, which is in range, so no exception
24910 will be raised, and the right result is obtained, regardless of whether
24911 overflow checks are suppressed.
24913 Note that in the first example an
24914 exception will be raised in either case, since if the compiler
24915 gives the correct mathematical result for the addition, it will
24916 be out of range of the target type of the assignment, and thus
24917 fails the range check.
24919 This lack of specified behavior in the handling of overflow for
24920 intermediate results is a source of non-portability, and can thus
24921 be problematic when programs are ported. Most typically this arises
24922 in a situation where the original compiler did not raise an exception,
24923 and then the application is moved to a compiler where the check is
24924 performed on the intermediate result and an unexpected exception is
24925 raised.
24927 Furthermore, when using Ada 2012's preconditions and other
24928 assertion forms, another issue arises. Consider:
24930 @smallexample @c ada
24931      @b{procedure} P (A, B : Integer) @b{with}
24932        Pre => A + B <= Integer'Last;
24933 @end smallexample
24935 @noindent
24936 One often wants to regard arithmetic in a context like this from
24937 a mathematical point of view. So for example, if the two actual parameters
24938 for a call to @code{P} are both @code{Integer'Last}, then
24939 the precondition should be regarded as False. If we are executing
24940 in a mode with run-time checks enabled for preconditions, then we would
24941 like this precondition to fail, rather than raising an exception
24942 because of the intermediate overflow.
24944 However, the language definition leaves the specification of
24945 whether the above condition fails (raising @code{Assert_Error}) or
24946 causes an intermediate overflow (raising @code{Constraint_Error})
24947 up to the implementation.
24949 The situation is worse in a case such as the following:
24951 @smallexample @c ada
24952      @b{procedure} Q (A, B, C : Integer) @b{with}
24953        Pre => A + B + C <= Integer'Last;
24954 @end smallexample
24956 @noindent
24957 Consider the call
24959 @smallexample @c ada
24960      Q (A => Integer'Last, B => 1, C => -1);
24961 @end smallexample
24963 @noindent
24964 From a mathematical point of view the precondition
24965 is True, but at run time we may (but are not guaranteed to) get an
24966 exception raised because of the intermediate overflow (and we really
24967 would prefer this precondition to be considered True at run time).
24969 @node Overflow Checking Modes in GNAT
24970 @section Overflow Checking Modes in GNAT
24972 @noindent
24973 To deal with the portability issue, and with the problem of
24974 mathematical versus run-time interpretation of the expressions in
24975 assertions, GNAT provides comprehensive control over the handling
24976 of intermediate overflow. GNAT can operate in three modes, and
24977 furthemore, permits separate selection of operating modes for
24978 the expressions within assertions (here the term ``assertions''
24979 is used in the technical sense, which includes preconditions and so forth)
24980 and for expressions appearing outside assertions.
24982 The three modes are:
24984 @itemize @bullet
24985 @item   @i{Use base type for intermediate operations} (@code{STRICT})
24987      In this mode, all intermediate results for predefined arithmetic
24988      operators are computed using the base type, and the result must
24989      be in range of the base type. If this is not the
24990      case then either an exception is raised (if overflow checks are
24991      enabled) or the execution is erroneous (if overflow checks are suppressed).
24992      This is the normal default mode.
24994 @item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
24996      In this mode, the compiler attempts to avoid intermediate overflows by
24997      using a larger integer type, typically @code{Long_Long_Integer},
24998      as the type in which arithmetic is
24999      performed for predefined arithmetic operators. This may be slightly more
25000      expensive at
25001      run time (compared to suppressing intermediate overflow checks), though
25002      the cost is negligible on modern 64-bit machines. For the examples given
25003      earlier, no intermediate overflows would have resulted in exceptions,
25004      since the intermediate results are all in the range of
25005      @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
25006      of GNAT). In addition, if checks are enabled, this reduces the number of
25007      checks that must be made, so this choice may actually result in an
25008      improvement in space and time behavior.
25010      However, there are cases where @code{Long_Long_Integer} is not large
25011      enough, consider the following example:
25013 @smallexample @c ada
25014        @b{procedure} R (A, B, C, D : Integer) @b{with}
25015          Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
25016 @end smallexample
25018      where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
25019      Now the intermediate results are
25020      out of the range of @code{Long_Long_Integer} even though the final result
25021      is in range and the precondition is True (from a mathematical point
25022      of view). In such a case, operating in this mode, an overflow occurs
25023      for the intermediate computation (which is why this mode
25024      says @i{most} intermediate overflows are avoided). In this case,
25025      an exception is raised if overflow checks are enabled, and the
25026      execution is erroneous if overflow checks are suppressed.
25028 @item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
25030      In this mode, the compiler  avoids all intermediate overflows
25031      by using arbitrary precision arithmetic as required. In this
25032      mode, the above example with @code{A**2 * B**2} would
25033      not cause intermediate overflow, because the intermediate result
25034      would be evaluated using sufficient precision, and the result
25035      of evaluating the precondition would be True.
25037      This mode has the advantage of avoiding any intermediate
25038      overflows, but at the expense of significant run-time overhead,
25039      including the use of a library (included automatically in this
25040      mode) for multiple-precision arithmetic.
25042      This mode provides cleaner semantics for assertions, since now
25043      the run-time behavior emulates true arithmetic behavior for the
25044      predefined arithmetic operators, meaning that there is never a
25045      conflict between the mathematical view of the assertion, and its
25046      run-time behavior.
25048      Note that in this mode, the behavior is unaffected by whether or
25049      not overflow checks are suppressed, since overflow does not occur.
25050      It is possible for gigantic intermediate expressions to raise
25051      @code{Storage_Error} as a result of attempting to compute the
25052      results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
25053      but overflow is impossible.
25056 @end itemize
25058 @noindent
25059   Note that these modes apply only to the evaluation of predefined
25060   arithmetic, membership, and comparison operators for signed integer
25061   aritmetic.
25063   For fixed-point arithmetic, checks can be suppressed. But if checks
25064   are enabled
25065   then fixed-point values are always checked for overflow against the
25066   base type for intermediate expressions (that is such checks always
25067   operate in the equivalent of @code{STRICT} mode).
25069   For floating-point, on nearly all architectures, @code{Machine_Overflows}
25070   is False, and IEEE infinities are generated, so overflow exceptions
25071   are never raised. If you want to avoid infinities, and check that
25072   final results of expressions are in range, then you can declare a
25073   constrained floating-point type, and range checks will be carried
25074   out in the normal manner (with infinite values always failing all
25075   range checks).
25078 @c -------------------------
25079 @node Specifying the Desired Mode
25080 @section Specifying the Desired Mode
25082 @noindent
25083 The desired mode of for handling intermediate overflow can be specified using
25084 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
25085 The pragma has the form
25086 @cindex pragma @code{Overflow_Mode}
25088 @smallexample @c ada
25089     @b{pragma} Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
25090 @end smallexample
25092 @noindent
25093 where @code{MODE} is one of
25095 @itemize @bullet
25096 @item   @code{STRICT}:  intermediate overflows checked (using base type)
25097 @item   @code{MINIMIZED}: minimize intermediate overflows
25098 @item   @code{ELIMINATED}: eliminate intermediate overflows
25099 @end itemize
25101 @noindent
25102 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
25103 @code{minimized} all have the same effect.
25105 If only the @code{General} parameter is present, then the given @code{MODE}
25106 applies
25107 to expressions both within and outside assertions. If both arguments
25108 are present, then @code{General} applies to expressions outside assertions,
25109 and @code{Assertions} applies to expressions within assertions. For example:
25111 @smallexample @c ada
25112    @b{pragma} Overflow_Mode
25113      (General => Minimized, Assertions => Eliminated);
25114 @end smallexample
25116 @noindent
25117 specifies that general expressions outside assertions be evaluated
25118 in ``minimize intermediate overflows'' mode, and expressions within
25119 assertions be evaluated in ``eliminate intermediate overflows'' mode.
25120 This is often a reasonable choice, avoiding excessive overhead
25121 outside assertions, but assuring a high degree of portability
25122 when importing code from another compiler, while incurring
25123 the extra overhead for assertion expressions to ensure that
25124 the behavior at run time matches the expected mathematical
25125 behavior.
25127 The @code{Overflow_Mode} pragma has the same scoping and placement
25128 rules as pragma @code{Suppress}, so it can occur either as a
25129 configuration pragma, specifying a default for the whole
25130 program, or in a declarative scope, where it applies to the
25131 remaining declarations and statements in that scope.
25133 Note that pragma @code{Overflow_Mode} does not affect whether
25134 overflow checks are enabled or suppressed. It only controls the
25135 method used to compute intermediate values. To control whether
25136 overflow checking is enabled or suppressed, use pragma @code{Suppress}
25137 or @code{Unsuppress} in the usual manner
25139 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
25140 can be used to control the checking mode default (which can be subsequently
25141 overridden using pragmas).
25142 @cindex @option{-gnato?} (gcc)
25143 @cindex @option{-gnato??} (gcc)
25145 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
25147 @itemize @bullet
25148 @item   @code{1}:
25149 use base type for intermediate operations (@code{STRICT})
25150 @item   @code{2}:
25151 minimize intermediate overflows (@code{MINIMIZED})
25152 @item   @code{3}:
25153 eliminate intermediate overflows (@code{ELIMINATED})
25154 @end itemize
25156 @noindent
25157 As with the pragma, if only one digit appears then it applies to all
25158 cases; if two digits are given, then the first applies outside
25159 assertions, and the second within assertions. Thus the equivalent
25160 of the example pragma above would be
25161 @option{-gnato23}.
25163 If no digits follow the @option{-gnato}, then it is equivalent to
25164 @option{-gnato11},
25165 causing all intermediate operations to be computed using the base
25166 type (@code{STRICT} mode).
25168 In addition to setting the mode used for computation of intermediate
25169 results, the @code{-gnato} switch also enables overflow checking (which
25170 is suppressed by default). It thus combines the effect of using
25171 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
25174 @c -------------------------
25175 @node Default Settings
25176 @section Default Settings
25178 The default mode for overflow checks is
25180 @smallexample
25181    General => Strict
25182 @end smallexample
25184 @noindent
25185 which causes all computations both inside and outside assertions to use
25186 the base type. In addition overflow checks are suppressed.
25188 This retains compatibility with previous versions of
25189 GNAT which suppressed overflow checks by default and always
25190 used the base type for computation of intermediate results.
25192 The switch @option{-gnato} (with no digits following) is equivalent to
25193 @cindex @option{-gnato} (gcc)
25195 @smallexample
25196    General => Strict
25197 @end smallexample
25199 @noindent
25200 which causes overflow checking of all intermediate overflows
25201 both inside and outside assertions against the base type.
25202 This provides compatibility
25203 with this switch as implemented in previous versions of GNAT.
25205 The pragma @code{Suppress (Overflow_Check)} disables overflow
25206 checking, but it has no effect on the method used for computing
25207 intermediate results.
25209 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
25210 checking, but it has no effect on the method used for computing
25211 intermediate results.
25213 @c -------------------------
25214 @node Implementation Notes
25215 @section Implementation Notes
25217 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
25218 reasonably efficient, and can be generally used. It also helps
25219 to ensure compatibility with code imported from some other
25220 compiler to GNAT.
25222 Setting all intermediate overflows checking (@code{CHECKED} mode)
25223 makes sense if you want to
25224 make sure that your code is compatible with any other possible
25225 Ada implementation. This may be useful in ensuring portability
25226 for code that is to be exported to some other compiler than GNAT.
25229 The Ada standard allows the reassociation of expressions at
25230 the same precedence level if no parentheses are present. For
25231 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
25232 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
25233 introducing or eliminating an overflow exception. The GNAT
25234 compiler never takes advantage of this freedom, and the
25235 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
25236 If you need the other order, you can write the parentheses
25237 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
25239 The use of @code{ELIMINATED} mode will cause the compiler to
25240 automatically include an appropriate arbitrary precision
25241 integer arithmetic package. The compiler will make calls
25242 to this package, though only in cases where it cannot be
25243 sure that @code{Long_Long_Integer} is sufficient to guard against
25244 intermediate overflows. This package does not use dynamic
25245 alllocation, but it does use the secondary stack, so an
25246 appropriate secondary stack package must be present (this
25247 is always true for standard full Ada, but may require
25248 specific steps for restricted run times such as ZFP).
25250 Although @code{ELIMINATED} mode causes expressions to use arbitrary
25251 precision arithmetic, avoiding overflow, the final result
25252 must be in an appropriate range. This is true even if the
25253 final result is of type @code{[Long_[Long_]]Integer'Base}, which
25254 still has the same bounds as its associated constrained
25255 type at run-time.
25257 Currently, the @code{ELIMINATED} mode is only available on target
25258 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
25259 platforms).
25261 @c *******************************
25262 @node Conditional Compilation
25263 @appendix Conditional Compilation
25264 @c *******************************
25265 @cindex Conditional compilation
25267 @noindent
25268 It is often necessary to arrange for a single source program
25269 to serve multiple purposes, where it is compiled in different
25270 ways to achieve these different goals. Some examples of the
25271 need for this feature are
25273 @itemize @bullet
25274 @item  Adapting a program to a different hardware environment
25275 @item  Adapting a program to a different target architecture
25276 @item  Turning debugging features on and off
25277 @item  Arranging for a program to compile with different compilers
25278 @end itemize
25280 @noindent
25281 In C, or C++, the typical approach would be to use the preprocessor
25282 that is defined as part of the language. The Ada language does not
25283 contain such a feature. This is not an oversight, but rather a very
25284 deliberate design decision, based on the experience that overuse of
25285 the preprocessing features in C and C++ can result in programs that
25286 are extremely difficult to maintain. For example, if we have ten
25287 switches that can be on or off, this means that there are a thousand
25288 separate programs, any one of which might not even be syntactically
25289 correct, and even if syntactically correct, the resulting program
25290 might not work correctly. Testing all combinations can quickly become
25291 impossible.
25293 Nevertheless, the need to tailor programs certainly exists, and in
25294 this Appendix we will discuss how this can
25295 be achieved using Ada in general, and GNAT in particular.
25297 @menu
25298 * Use of Boolean Constants::
25299 * Debugging - A Special Case::
25300 * Conditionalizing Declarations::
25301 * Use of Alternative Implementations::
25302 * Preprocessing::
25303 @end menu
25305 @node Use of Boolean Constants
25306 @section Use of Boolean Constants
25308 @noindent
25309 In the case where the difference is simply which code
25310 sequence is executed, the cleanest solution is to use Boolean
25311 constants to control which code is executed.
25313 @smallexample @c ada
25314 @group
25315 FP_Initialize_Required : @b{constant} Boolean := True;
25316 @dots{}
25317 @b{if} FP_Initialize_Required @b{then}
25318 @dots{}
25319 @b{end} @b{if};
25320 @end group
25321 @end smallexample
25323 @noindent
25324 Not only will the code inside the @code{if} statement not be executed if
25325 the constant Boolean is @code{False}, but it will also be completely
25326 deleted from the program.
25327 However, the code is only deleted after the @code{if} statement
25328 has been checked for syntactic and semantic correctness.
25329 (In contrast, with preprocessors the code is deleted before the
25330 compiler ever gets to see it, so it is not checked until the switch
25331 is turned on.)
25332 @cindex Preprocessors (contrasted with conditional compilation)
25334 Typically the Boolean constants will be in a separate package,
25335 something like:
25337 @smallexample @c ada
25338 @group
25339 @b{package} Config @b{is}
25340    FP_Initialize_Required : @b{constant} Boolean := True;
25341    Reset_Available        : @b{constant} Boolean := False;
25342    @dots{}
25343 @b{end} Config;
25344 @end group
25345 @end smallexample
25347 @noindent
25348 The @code{Config} package exists in multiple forms for the various targets,
25349 with an appropriate script selecting the version of @code{Config} needed.
25350 Then any other unit requiring conditional compilation can do a @code{with}
25351 of @code{Config} to make the constants visible.
25354 @node Debugging - A Special Case
25355 @section Debugging - A Special Case
25357 @noindent
25358 A common use of conditional code is to execute statements (for example
25359 dynamic checks, or output of intermediate results) under control of a
25360 debug switch, so that the debugging behavior can be turned on and off.
25361 This can be done using a Boolean constant to control whether the code
25362 is active:
25364 @smallexample @c ada
25365 @group
25366 @b{if} Debugging @b{then}
25367    Put_Line ("got to the first stage!");
25368 @b{end} @b{if};
25369 @end group
25370 @end smallexample
25372 @noindent
25375 @smallexample @c ada
25376 @group
25377 @b{if} Debugging @b{and} @b{then} Temperature > 999.0 @b{then}
25378    @b{raise} Temperature_Crazy;
25379 @b{end} @b{if};
25380 @end group
25381 @end smallexample
25383 @noindent
25384 Since this is a common case, there are special features to deal with
25385 this in a convenient manner. For the case of tests, Ada 2005 has added
25386 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25387 @cindex pragma @code{Assert}
25388 on the @code{Assert} pragma that has always been available in GNAT, so this
25389 feature may be used with GNAT even if you are not using Ada 2005 features.
25390 The use of pragma @code{Assert} is described in
25391 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25392 example, the last test could be written:
25394 @smallexample @c ada
25395 @b{pragma} Assert (Temperature <= 999.0, "Temperature Crazy");
25396 @end smallexample
25398 @noindent
25399 or simply
25401 @smallexample @c ada
25402 @b{pragma} Assert (Temperature <= 999.0);
25403 @end smallexample
25405 @noindent
25406 In both cases, if assertions are active and the temperature is excessive,
25407 the exception @code{Assert_Failure} will be raised, with the given string in
25408 the first case or a string indicating the location of the pragma in the second
25409 case used as the exception message.
25411 You can turn assertions on and off by using the @code{Assertion_Policy}
25412 pragma.
25413 @cindex pragma @code{Assertion_Policy}
25414 This is an Ada 2005 pragma which is implemented in all modes by
25415 GNAT, but only in the latest versions of GNAT which include Ada 2005
25416 capability. Alternatively, you can use the @option{-gnata} switch
25417 @cindex @option{-gnata} switch
25418 to enable assertions from the command line (this is recognized by all versions
25419 of GNAT).
25421 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25422 @code{Debug} can be used:
25423 @cindex pragma @code{Debug}
25425 @smallexample @c ada
25426 @b{pragma} Debug (Put_Line ("got to the first stage!"));
25427 @end smallexample
25429 @noindent
25430 If debug pragmas are enabled, the argument, which must be of the form of
25431 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25432 Only one call can be present, but of course a special debugging procedure
25433 containing any code you like can be included in the program and then
25434 called in a pragma @code{Debug} argument as needed.
25436 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25437 construct is that pragma @code{Debug} can appear in declarative contexts,
25438 such as at the very beginning of a procedure, before local declarations have
25439 been elaborated.
25441 Debug pragmas are enabled using either the @option{-gnata} switch that also
25442 controls assertions, or with a separate Debug_Policy pragma.
25443 @cindex pragma @code{Debug_Policy}
25444 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25445 in Ada 95 and Ada 83 programs as well), and is analogous to
25446 pragma @code{Assertion_Policy} to control assertions.
25448 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25449 and thus they can appear in @file{gnat.adc} if you are not using a
25450 project file, or in the file designated to contain configuration pragmas
25451 in a project file.
25452 They then apply to all subsequent compilations. In practice the use of
25453 the @option{-gnata} switch is often the most convenient method of controlling
25454 the status of these pragmas.
25456 Note that a pragma is not a statement, so in contexts where a statement
25457 sequence is required, you can't just write a pragma on its own. You have
25458 to add a @code{null} statement.
25460 @smallexample @c ada
25461 @group
25462 @b{if} @dots{} @b{then}
25463    @dots{} -- some statements
25464 @b{else}
25465    @b{pragma} Assert (Num_Cases < 10);
25466    @b{null};
25467 @b{end} @b{if};
25468 @end group
25469 @end smallexample
25472 @node Conditionalizing Declarations
25473 @section Conditionalizing Declarations
25475 @noindent
25476 In some cases, it may be necessary to conditionalize declarations to meet
25477 different requirements. For example we might want a bit string whose length
25478 is set to meet some hardware message requirement.
25480 In some cases, it may be possible to do this using declare blocks controlled
25481 by conditional constants:
25483 @smallexample @c ada
25484 @group
25485 @b{if} Small_Machine @b{then}
25486    @b{declare}
25487       X : Bit_String (1 .. 10);
25488    @b{begin}
25489       @dots{}
25490    @b{end};
25491 @b{else}
25492    @b{declare}
25493       X : Large_Bit_String (1 .. 1000);
25494    @b{begin}
25495       @dots{}
25496    @b{end};
25497 @b{end} @b{if};
25498 @end group
25499 @end smallexample
25501 @noindent
25502 Note that in this approach, both declarations are analyzed by the
25503 compiler so this can only be used where both declarations are legal,
25504 even though one of them will not be used.
25506 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25507 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25508 that are parameterized by these constants. For example
25510 @smallexample @c ada
25511 @group
25512 @b{for} Rec @b{use}
25513   Field1 @b{at} 0 @b{range} Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25514 @b{end} @b{record};
25515 @end group
25516 @end smallexample
25518 @noindent
25519 If @code{Bits_Per_Word} is set to 32, this generates either
25521 @smallexample @c ada
25522 @group
25523 @b{for} Rec @b{use}
25524   Field1 @b{at} 0 @b{range} 0 .. 32;
25525 @b{end} @b{record};
25526 @end group
25527 @end smallexample
25529 @noindent
25530 for the big endian case, or
25532 @smallexample @c ada
25533 @group
25534 @b{for} Rec @b{use} @b{record}
25535   Field1 @b{at} 0 @b{range} 10 .. 32;
25536 @b{end} @b{record};
25537 @end group
25538 @end smallexample
25540 @noindent
25541 for the little endian case. Since a powerful subset of Ada expression
25542 notation is usable for creating static constants, clever use of this
25543 feature can often solve quite difficult problems in conditionalizing
25544 compilation (note incidentally that in Ada 95, the little endian
25545 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25546 need to define this one yourself).
25549 @node Use of Alternative Implementations
25550 @section Use of Alternative Implementations
25552 @noindent
25553 In some cases, none of the approaches described above are adequate. This
25554 can occur for example if the set of declarations required is radically
25555 different for two different configurations.
25557 In this situation, the official Ada way of dealing with conditionalizing
25558 such code is to write separate units for the different cases. As long as
25559 this does not result in excessive duplication of code, this can be done
25560 without creating maintenance problems. The approach is to share common
25561 code as far as possible, and then isolate the code and declarations
25562 that are different. Subunits are often a convenient method for breaking
25563 out a piece of a unit that is to be conditionalized, with separate files
25564 for different versions of the subunit for different targets, where the
25565 build script selects the right one to give to the compiler.
25566 @cindex Subunits (and conditional compilation)
25568 As an example, consider a situation where a new feature in Ada 2005
25569 allows something to be done in a really nice way. But your code must be able
25570 to compile with an Ada 95 compiler. Conceptually you want to say:
25572 @smallexample @c ada
25573 @group
25574 @b{if} Ada_2005 @b{then}
25575    @dots{} neat Ada 2005 code
25576 @b{else}
25577    @dots{} not quite as neat Ada 95 code
25578 @b{end} @b{if};
25579 @end group
25580 @end smallexample
25582 @noindent
25583 where @code{Ada_2005} is a Boolean constant.
25585 But this won't work when @code{Ada_2005} is set to @code{False},
25586 since the @code{then} clause will be illegal for an Ada 95 compiler.
25587 (Recall that although such unreachable code would eventually be deleted
25588 by the compiler, it still needs to be legal.  If it uses features
25589 introduced in Ada 2005, it will be illegal in Ada 95.)
25591 So instead we write
25593 @smallexample @c ada
25594 @b{procedure} Insert @b{is} @b{separate};
25595 @end smallexample
25597 @noindent
25598 Then we have two files for the subunit @code{Insert}, with the two sets of
25599 code.
25600 If the package containing this is called @code{File_Queries}, then we might
25601 have two files
25603 @itemize @bullet
25604 @item    @file{file_queries-insert-2005.adb}
25605 @item    @file{file_queries-insert-95.adb}
25606 @end itemize
25608 @noindent
25609 and the build script renames the appropriate file to
25611 @smallexample
25612 file_queries-insert.adb
25613 @end smallexample
25615 @noindent
25616 and then carries out the compilation.
25618 This can also be done with project files' naming schemes. For example:
25620 @smallexample @c project
25621 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25622 @end smallexample
25624 @noindent
25625 Note also that with project files it is desirable to use a different extension
25626 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25627 conflict may arise through another commonly used feature: to declare as part
25628 of the project a set of directories containing all the sources obeying the
25629 default naming scheme.
25631 The use of alternative units is certainly feasible in all situations,
25632 and for example the Ada part of the GNAT run-time is conditionalized
25633 based on the target architecture using this approach. As a specific example,
25634 consider the implementation of the AST feature in VMS. There is one
25635 spec:
25637 @smallexample
25638 s-asthan.ads
25639 @end smallexample
25641 @noindent
25642 which is the same for all architectures, and three bodies:
25644 @table @file
25645 @item    s-asthan.adb
25646 used for all non-VMS operating systems
25647 @item    s-asthan-vms-alpha.adb
25648 used for VMS on the Alpha
25649 @item    s-asthan-vms-ia64.adb
25650 used for VMS on the ia64
25651 @end table
25653 @noindent
25654 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25655 this operating system feature is not available, and the two remaining
25656 versions interface with the corresponding versions of VMS to provide
25657 VMS-compatible AST handling. The GNAT build script knows the architecture
25658 and operating system, and automatically selects the right version,
25659 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25661 Another style for arranging alternative implementations is through Ada's
25662 access-to-subprogram facility.
25663 In case some functionality is to be conditionally included,
25664 you can declare an access-to-procedure variable @code{Ref} that is initialized
25665 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25666 when appropriate.
25667 In some library package, set @code{Ref} to @code{Proc'Access} for some
25668 procedure @code{Proc} that performs the relevant processing.
25669 The initialization only occurs if the library package is included in the
25670 program.
25671 The same idea can also be implemented using tagged types and dispatching
25672 calls.
25675 @node Preprocessing
25676 @section Preprocessing
25677 @cindex Preprocessing
25679 @noindent
25680 Although it is quite possible to conditionalize code without the use of
25681 C-style preprocessing, as described earlier in this section, it is
25682 nevertheless convenient in some cases to use the C approach. Moreover,
25683 older Ada compilers have often provided some preprocessing capability,
25684 so legacy code may depend on this approach, even though it is not
25685 standard.
25687 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25688 extent on the various preprocessors that have been used
25689 with legacy code on other compilers, to enable easier transition).
25691 The preprocessor may be used in two separate modes. It can be used quite
25692 separately from the compiler, to generate a separate output source file
25693 that is then fed to the compiler as a separate step. This is the
25694 @code{gnatprep} utility, whose use is fully described in
25695 @ref{Preprocessing with gnatprep}.
25696 @cindex @code{gnatprep}
25698 The preprocessing language allows such constructs as
25700 @smallexample
25701 @group
25702 #if DEBUG or else (PRIORITY > 4) then
25703    bunch of declarations
25704 #else
25705    completely different bunch of declarations
25706 #end if;
25707 @end group
25708 @end smallexample
25710 @noindent
25711 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25712 defined either on the command line or in a separate file.
25714 The other way of running the preprocessor is even closer to the C style and
25715 often more convenient. In this approach the preprocessing is integrated into
25716 the compilation process. The compiler is fed the preprocessor input which
25717 includes @code{#if} lines etc, and then the compiler carries out the
25718 preprocessing internally and processes the resulting output.
25719 For more details on this approach, see @ref{Integrated Preprocessing}.
25722 @c *******************************
25723 @node Inline Assembler
25724 @appendix Inline Assembler
25725 @c *******************************
25727 @noindent
25728 If you need to write low-level software that interacts directly
25729 with the hardware, Ada provides two ways to incorporate assembly
25730 language code into your program.  First, you can import and invoke
25731 external routines written in assembly language, an Ada feature fully
25732 supported by GNAT@.  However, for small sections of code it may be simpler
25733 or more efficient to include assembly language statements directly
25734 in your Ada source program, using the facilities of the implementation-defined
25735 package @code{System.Machine_Code}, which incorporates the gcc
25736 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25737 including the following:
25739 @itemize @bullet
25740 @item No need to use non-Ada tools
25741 @item Consistent interface over different targets
25742 @item Automatic usage of the proper calling conventions
25743 @item Access to Ada constants and variables
25744 @item Definition of intrinsic routines
25745 @item Possibility of inlining a subprogram comprising assembler code
25746 @item Code optimizer can take Inline Assembler code into account
25747 @end itemize
25749 This chapter presents a series of examples to show you how to use
25750 the Inline Assembler.  Although it focuses on the Intel x86,
25751 the general approach applies also to other processors.
25752 It is assumed that you are familiar with Ada
25753 and with assembly language programming.
25755 @menu
25756 * Basic Assembler Syntax::
25757 * A Simple Example of Inline Assembler::
25758 * Output Variables in Inline Assembler::
25759 * Input Variables in Inline Assembler::
25760 * Inlining Inline Assembler Code::
25761 * Other Asm Functionality::
25762 @end menu
25764 @c ---------------------------------------------------------------------------
25765 @node Basic Assembler Syntax
25766 @section Basic Assembler Syntax
25768 @noindent
25769 The assembler used by GNAT and gcc is based not on the Intel assembly
25770 language, but rather on a language that descends from the AT&T Unix
25771 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25772 The following table summarizes the main features of @emph{as} syntax
25773 and points out the differences from the Intel conventions.
25774 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25775 pre-processor) documentation for further information.
25777 @table @asis
25778 @item Register names
25779 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25781 Intel: No extra punctuation; for example @code{eax}
25783 @item Immediate operand
25784 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25786 Intel: No extra punctuation; for example @code{4}
25788 @item Address
25789 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25791 Intel: No extra punctuation; for example @code{loc}
25793 @item Memory contents
25794 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25796 Intel: Square brackets; for example @code{[loc]}
25798 @item Register contents
25799 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25801 Intel: Square brackets; for example @code{[eax]}
25803 @item Hexadecimal numbers
25804 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25806 Intel: Trailing ``h''; for example @code{A0h}
25808 @item Operand size
25809 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25810 a 16-bit word
25812 Intel: Implicit, deduced by assembler; for example @code{mov}
25814 @item Instruction repetition
25815 gcc / @emph{as}: Split into two lines; for example
25817 @code{rep}
25819 @code{stosl}
25821 Intel: Keep on one line; for example @code{rep stosl}
25823 @item Order of operands
25824 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25826 Intel: Destination first; for example @code{mov eax, 4}
25827 @end table
25829 @c ---------------------------------------------------------------------------
25830 @node A Simple Example of Inline Assembler
25831 @section A Simple Example of Inline Assembler
25833 @noindent
25834 The following example will generate a single assembly language statement,
25835 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25836 the example will be useful in illustrating the basics of
25837 the Inline Assembler facility.
25839 @smallexample @c ada
25840 @group
25841 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
25842 @b{procedure} Nothing @b{is}
25843 @b{begin}
25844    Asm ("nop");
25845 @b{end} Nothing;
25846 @end group
25847 @end smallexample
25849 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25850 here it takes one parameter, a @emph{template string} that must be a static
25851 expression and that will form the generated instruction.
25852 @code{Asm} may be regarded as a compile-time procedure that parses
25853 the template string and additional parameters (none here),
25854 from which it generates a sequence of assembly language instructions.
25856 The examples in this chapter will illustrate several of the forms
25857 for invoking @code{Asm}; a complete specification of the syntax
25858 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25859 Manual}.
25861 Under the standard GNAT conventions, the @code{Nothing} procedure
25862 should be in a file named @file{nothing.adb}.
25863 You can build the executable in the usual way:
25864 @smallexample
25865 gnatmake nothing
25866 @end smallexample
25867 However, the interesting aspect of this example is not its run-time behavior
25868 but rather the generated assembly code.
25869 To see this output, invoke the compiler as follows:
25870 @smallexample
25871    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25872 @end smallexample
25873 where the options are:
25875 @table @code
25876 @item -c
25877 compile only (no bind or link)
25878 @item -S
25879 generate assembler listing
25880 @item -fomit-frame-pointer
25881 do not set up separate stack frames
25882 @item -gnatp
25883 do not add runtime checks
25884 @end table
25886 This gives a human-readable assembler version of the code. The resulting
25887 file will have the same name as the Ada source file, but with a @code{.s}
25888 extension. In our example, the file @file{nothing.s} has the following
25889 contents:
25891 @smallexample
25892 @group
25893 .file "nothing.adb"
25894 gcc2_compiled.:
25895 ___gnu_compiled_ada:
25896 .text
25897    .align 4
25898 .globl __ada_nothing
25899 __ada_nothing:
25900 #APP
25901    nop
25902 #NO_APP
25903    jmp L1
25904    .align 2,0x90
25906    ret
25907 @end group
25908 @end smallexample
25910 The assembly code you included is clearly indicated by
25911 the compiler, between the @code{#APP} and @code{#NO_APP}
25912 delimiters. The character before the 'APP' and 'NOAPP'
25913 can differ on different targets. For example, GNU/Linux uses '#APP' while
25914 on NT you will see '/APP'.
25916 If you make a mistake in your assembler code (such as using the
25917 wrong size modifier, or using a wrong operand for the instruction) GNAT
25918 will report this error in a temporary file, which will be deleted when
25919 the compilation is finished.  Generating an assembler file will help
25920 in such cases, since you can assemble this file separately using the
25921 @emph{as} assembler that comes with gcc.
25923 Assembling the file using the command
25925 @smallexample
25926 as @file{nothing.s}
25927 @end smallexample
25928 @noindent
25929 will give you error messages whose lines correspond to the assembler
25930 input file, so you can easily find and correct any mistakes you made.
25931 If there are no errors, @emph{as} will generate an object file
25932 @file{nothing.out}.
25934 @c ---------------------------------------------------------------------------
25935 @node Output Variables in Inline Assembler
25936 @section Output Variables in Inline Assembler
25938 @noindent
25939 The examples in this section, showing how to access the processor flags,
25940 illustrate how to specify the destination operands for assembly language
25941 statements.
25943 @smallexample @c ada
25944 @group
25945 @b{with} Interfaces; @b{use} Interfaces;
25946 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
25947 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
25948 @b{procedure} Get_Flags @b{is}
25949    Flags : Unsigned_32;
25950    @b{use} ASCII;
25951 @b{begin}
25952    Asm ("pushfl"          & LF & HT & --@i{ push flags on stack}
25953         "popl %%eax"      & LF & HT & --@i{ load eax with flags}
25954         "movl %%eax, %0",             --@i{ store flags in variable}
25955         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25956    Put_Line ("Flags register:" & Flags'Img);
25957 @b{end} Get_Flags;
25958 @end group
25959 @end smallexample
25961 In order to have a nicely aligned assembly listing, we have separated
25962 multiple assembler statements in the Asm template string with linefeed
25963 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25964 The resulting section of the assembly output file is:
25966 @smallexample
25967 @group
25968 #APP
25969    pushfl
25970    popl %eax
25971    movl %eax, -40(%ebp)
25972 #NO_APP
25973 @end group
25974 @end smallexample
25976 It would have been legal to write the Asm invocation as:
25978 @smallexample
25979 Asm ("pushfl popl %%eax movl %%eax, %0")
25980 @end smallexample
25982 but in the generated assembler file, this would come out as:
25984 @smallexample
25985 #APP
25986    pushfl popl %eax movl %eax, -40(%ebp)
25987 #NO_APP
25988 @end smallexample
25990 which is not so convenient for the human reader.
25992 We use Ada comments
25993 at the end of each line to explain what the assembler instructions
25994 actually do.  This is a useful convention.
25996 When writing Inline Assembler instructions, you need to precede each register
25997 and variable name with a percent sign.  Since the assembler already requires
25998 a percent sign at the beginning of a register name, you need two consecutive
25999 percent signs for such names in the Asm template string, thus @code{%%eax}.
26000 In the generated assembly code, one of the percent signs will be stripped off.
26002 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
26003 variables: operands you later define using @code{Input} or @code{Output}
26004 parameters to @code{Asm}.
26005 An output variable is illustrated in
26006 the third statement in the Asm template string:
26007 @smallexample
26008 movl %%eax, %0
26009 @end smallexample
26010 The intent is to store the contents of the eax register in a variable that can
26011 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
26012 necessarily work, since the compiler might optimize by using a register
26013 to hold Flags, and the expansion of the @code{movl} instruction would not be
26014 aware of this optimization.  The solution is not to store the result directly
26015 but rather to advise the compiler to choose the correct operand form;
26016 that is the purpose of the @code{%0} output variable.
26018 Information about the output variable is supplied in the @code{Outputs}
26019 parameter to @code{Asm}:
26020 @smallexample
26021 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26022 @end smallexample
26024 The output is defined by the @code{Asm_Output} attribute of the target type;
26025 the general format is
26026 @smallexample
26027 Type'Asm_Output (constraint_string, variable_name)
26028 @end smallexample
26030 The constraint string directs the compiler how
26031 to store/access the associated variable.  In the example
26032 @smallexample
26033 Unsigned_32'Asm_Output ("=m", Flags);
26034 @end smallexample
26035 the @code{"m"} (memory) constraint tells the compiler that the variable
26036 @code{Flags} should be stored in a memory variable, thus preventing
26037 the optimizer from keeping it in a register.  In contrast,
26038 @smallexample
26039 Unsigned_32'Asm_Output ("=r", Flags);
26040 @end smallexample
26041 uses the @code{"r"} (register) constraint, telling the compiler to
26042 store the variable in a register.
26044 If the constraint is preceded by the equal character (@strong{=}), it tells
26045 the compiler that the variable will be used to store data into it.
26047 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
26048 allowing the optimizer to choose whatever it deems best.
26050 There are a fairly large number of constraints, but the ones that are
26051 most useful (for the Intel x86 processor) are the following:
26053 @table @code
26054 @item =
26055 output constraint
26056 @item g
26057 global (i.e.@: can be stored anywhere)
26058 @item m
26059 in memory
26060 @item I
26061 a constant
26062 @item a
26063 use eax
26064 @item b
26065 use ebx
26066 @item c
26067 use ecx
26068 @item d
26069 use edx
26070 @item S
26071 use esi
26072 @item D
26073 use edi
26074 @item r
26075 use one of eax, ebx, ecx or edx
26076 @item q
26077 use one of eax, ebx, ecx, edx, esi or edi
26078 @end table
26080 The full set of constraints is described in the gcc and @emph{as}
26081 documentation; note that it is possible to combine certain constraints
26082 in one constraint string.
26084 You specify the association of an output variable with an assembler operand
26085 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
26086 integer.  Thus in
26087 @smallexample @c ada
26088 @group
26089 Asm ("pushfl"          & LF & HT & --@i{ push flags on stack}
26090      "popl %%eax"      & LF & HT & --@i{ load eax with flags}
26091      "movl %%eax, %0",             --@i{ store flags in variable}
26092      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26093 @end group
26094 @end smallexample
26095 @noindent
26096 @code{%0} will be replaced in the expanded code by the appropriate operand,
26097 whatever
26098 the compiler decided for the @code{Flags} variable.
26100 In general, you may have any number of output variables:
26101 @itemize @bullet
26102 @item
26103 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26104 @item
26105 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26106 of @code{Asm_Output} attributes
26107 @end itemize
26109 For example:
26110 @smallexample @c ada
26111 @group
26112 Asm ("movl %%eax, %0" & LF & HT &
26113      "movl %%ebx, %1" & LF & HT &
26114      "movl %%ecx, %2",
26115      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --@i{  %0 = Var_A}
26116                  Unsigned_32'Asm_Output ("=g", Var_B),   --@i{  %1 = Var_B}
26117                  Unsigned_32'Asm_Output ("=g", Var_C))); --@i{  %2 = Var_C}
26118 @end group
26119 @end smallexample
26120 @noindent
26121 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26122 in the Ada program.
26124 As a variation on the @code{Get_Flags} example, we can use the constraints
26125 string to direct the compiler to store the eax register into the @code{Flags}
26126 variable, instead of including the store instruction explicitly in the
26127 @code{Asm} template string:
26129 @smallexample @c ada
26130 @group
26131 @b{with} Interfaces; @b{use} Interfaces;
26132 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26133 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26134 @b{procedure} Get_Flags_2 @b{is}
26135    Flags : Unsigned_32;
26136    @b{use} ASCII;
26137 @b{begin}
26138    Asm ("pushfl"      & LF & HT & --@i{ push flags on stack}
26139         "popl %%eax",             --@i{ save flags in eax}
26140         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26141    Put_Line ("Flags register:" & Flags'Img);
26142 @b{end} Get_Flags_2;
26143 @end group
26144 @end smallexample
26146 @noindent
26147 The @code{"a"} constraint tells the compiler that the @code{Flags}
26148 variable will come from the eax register. Here is the resulting code:
26150 @smallexample
26151 @group
26152 #APP
26153    pushfl
26154    popl %eax
26155 #NO_APP
26156    movl %eax,-40(%ebp)
26157 @end group
26158 @end smallexample
26160 @noindent
26161 The compiler generated the store of eax into Flags after
26162 expanding the assembler code.
26164 Actually, there was no need to pop the flags into the eax register;
26165 more simply, we could just pop the flags directly into the program variable:
26167 @smallexample @c ada
26168 @group
26169 @b{with} Interfaces; @b{use} Interfaces;
26170 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26171 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26172 @b{procedure} Get_Flags_3 @b{is}
26173    Flags : Unsigned_32;
26174    @b{use} ASCII;
26175 @b{begin}
26176    Asm ("pushfl"  & LF & HT & --@i{ push flags on stack}
26177         "pop %0",             --@i{ save flags in Flags}
26178         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26179    Put_Line ("Flags register:" & Flags'Img);
26180 @b{end} Get_Flags_3;
26181 @end group
26182 @end smallexample
26184 @c ---------------------------------------------------------------------------
26185 @node Input Variables in Inline Assembler
26186 @section Input Variables in Inline Assembler
26188 @noindent
26189 The example in this section illustrates how to specify the source operands
26190 for assembly language statements.
26191 The program simply increments its input value by 1:
26193 @smallexample @c ada
26194 @group
26195 @b{with} Interfaces; @b{use} Interfaces;
26196 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26197 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26198 @b{procedure} Increment @b{is}
26200    @b{function} Incr (Value : Unsigned_32) @b{return} Unsigned_32 @b{is}
26201       Result : Unsigned_32;
26202    @b{begin}
26203       Asm ("incl %0",
26204            Outputs => Unsigned_32'Asm_Output ("=a", Result),
26205            Inputs  => Unsigned_32'Asm_Input ("a", Value));
26206       @b{return} Result;
26207    @b{end} Incr;
26209    Value : Unsigned_32;
26211 @b{begin}
26212    Value := 5;
26213    Put_Line ("Value before is" & Value'Img);
26214    Value := Incr (Value);
26215    Put_Line ("Value after is" & Value'Img);
26216 @b{end} Increment;
26217 @end group
26218 @end smallexample
26220 The @code{Outputs} parameter to @code{Asm} specifies
26221 that the result will be in the eax register and that it is to be stored
26222 in the @code{Result} variable.
26224 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26225 but with an @code{Asm_Input} attribute.
26226 The @code{"="} constraint, indicating an output value, is not present.
26228 You can have multiple input variables, in the same way that you can have more
26229 than one output variable.
26231 The parameter count (%0, %1) etc, still starts at the first output statement,
26232 and continues with the input statements.
26234 Just as the @code{Outputs} parameter causes the register to be stored into the
26235 target variable after execution of the assembler statements, so does the
26236 @code{Inputs} parameter cause its variable to be loaded into the register
26237 before execution of the assembler statements.
26239 Thus the effect of the @code{Asm} invocation is:
26240 @enumerate
26241 @item load the 32-bit value of @code{Value} into eax
26242 @item execute the @code{incl %eax} instruction
26243 @item store the contents of eax into the @code{Result} variable
26244 @end enumerate
26246 The resulting assembler file (with @option{-O2} optimization) contains:
26247 @smallexample
26248 @group
26249 _increment__incr.1:
26250    subl $4,%esp
26251    movl 8(%esp),%eax
26252 #APP
26253    incl %eax
26254 #NO_APP
26255    movl %eax,%edx
26256    movl %ecx,(%esp)
26257    addl $4,%esp
26258    ret
26259 @end group
26260 @end smallexample
26262 @c ---------------------------------------------------------------------------
26263 @node Inlining Inline Assembler Code
26264 @section Inlining Inline Assembler Code
26266 @noindent
26267 For a short subprogram such as the @code{Incr} function in the previous
26268 section, the overhead of the call and return (creating / deleting the stack
26269 frame) can be significant, compared to the amount of code in the subprogram
26270 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26271 which directs the compiler to expand invocations of the subprogram at the
26272 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26273 Here is the resulting program:
26275 @smallexample @c ada
26276 @group
26277 @b{with} Interfaces; @b{use} Interfaces;
26278 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
26279 @b{with} System.Machine_Code; @b{use} System.Machine_Code;
26280 @b{procedure} Increment_2 @b{is}
26282    @b{function} Incr (Value : Unsigned_32) @b{return} Unsigned_32 @b{is}
26283       Result : Unsigned_32;
26284    @b{begin}
26285       Asm ("incl %0",
26286            Outputs => Unsigned_32'Asm_Output ("=a", Result),
26287            Inputs  => Unsigned_32'Asm_Input ("a", Value));
26288       @b{return} Result;
26289    @b{end} Incr;
26290    @b{pragma} Inline (Increment);
26292    Value : Unsigned_32;
26294 @b{begin}
26295    Value := 5;
26296    Put_Line ("Value before is" & Value'Img);
26297    Value := Increment (Value);
26298    Put_Line ("Value after is" & Value'Img);
26299 @b{end} Increment_2;
26300 @end group
26301 @end smallexample
26303 Compile the program with both optimization (@option{-O2}) and inlining
26304 (@option{-gnatn}) enabled.
26306 The @code{Incr} function is still compiled as usual, but at the
26307 point in @code{Increment} where our function used to be called:
26309 @smallexample
26310 @group
26311 pushl %edi
26312 call _increment__incr.1
26313 @end group
26314 @end smallexample
26316 @noindent
26317 the code for the function body directly appears:
26319 @smallexample
26320 @group
26321 movl %esi,%eax
26322 #APP
26323    incl %eax
26324 #NO_APP
26325    movl %eax,%edx
26326 @end group
26327 @end smallexample
26329 @noindent
26330 thus saving the overhead of stack frame setup and an out-of-line call.
26332 @c ---------------------------------------------------------------------------
26333 @node Other Asm Functionality
26334 @section Other @code{Asm} Functionality
26336 @noindent
26337 This section describes two important parameters to the @code{Asm}
26338 procedure: @code{Clobber}, which identifies register usage;
26339 and @code{Volatile}, which inhibits unwanted optimizations.
26341 @menu
26342 * The Clobber Parameter::
26343 * The Volatile Parameter::
26344 @end menu
26346 @c ---------------------------------------------------------------------------
26347 @node The Clobber Parameter
26348 @subsection The @code{Clobber} Parameter
26350 @noindent
26351 One of the dangers of intermixing assembly language and a compiled language
26352 such as Ada is that the compiler needs to be aware of which registers are
26353 being used by the assembly code.  In some cases, such as the earlier examples,
26354 the constraint string is sufficient to indicate register usage (e.g.,
26355 @code{"a"} for
26356 the eax register).  But more generally, the compiler needs an explicit
26357 identification of the registers that are used by the Inline Assembly
26358 statements.
26360 Using a register that the compiler doesn't know about
26361 could be a side effect of an instruction (like @code{mull}
26362 storing its result in both eax and edx).
26363 It can also arise from explicit register usage in your
26364 assembly code; for example:
26365 @smallexample
26366 @group
26367 Asm ("movl %0, %%ebx" & LF & HT &
26368      "movl %%ebx, %1",
26369      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26370      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
26371 @end group
26372 @end smallexample
26373 @noindent
26374 where the compiler (since it does not analyze the @code{Asm} template string)
26375 does not know you are using the ebx register.
26377 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26378 to identify the registers that will be used by your assembly code:
26380 @smallexample
26381 @group
26382 Asm ("movl %0, %%ebx" & LF & HT &
26383      "movl %%ebx, %1",
26384      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26385      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26386      Clobber => "ebx");
26387 @end group
26388 @end smallexample
26390 The Clobber parameter is a static string expression specifying the
26391 register(s) you are using.  Note that register names are @emph{not} prefixed
26392 by a percent sign. Also, if more than one register is used then their names
26393 are separated by commas; e.g., @code{"eax, ebx"}
26395 The @code{Clobber} parameter has several additional uses:
26396 @enumerate
26397 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26398 @item Use ``register'' name @code{memory} if you changed a memory location
26399 @end enumerate
26401 @c ---------------------------------------------------------------------------
26402 @node The Volatile Parameter
26403 @subsection The @code{Volatile} Parameter
26404 @cindex Volatile parameter
26406 @noindent
26407 Compiler optimizations in the presence of Inline Assembler may sometimes have
26408 unwanted effects.  For example, when an @code{Asm} invocation with an input
26409 variable is inside a loop, the compiler might move the loading of the input
26410 variable outside the loop, regarding it as a one-time initialization.
26412 If this effect is not desired, you can disable such optimizations by setting
26413 the @code{Volatile} parameter to @code{True}; for example:
26415 @smallexample @c ada
26416 @group
26417 Asm ("movl %0, %%ebx" & LF & HT &
26418      "movl %%ebx, %1",
26419      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26420      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26421      Clobber  => "ebx",
26422      Volatile => True);
26423 @end group
26424 @end smallexample
26426 By default, @code{Volatile} is set to @code{False} unless there is no
26427 @code{Outputs} parameter.
26429 Although setting @code{Volatile} to @code{True} prevents unwanted
26430 optimizations, it will also disable other optimizations that might be
26431 important for efficiency. In general, you should set @code{Volatile}
26432 to @code{True} only if the compiler's optimizations have created
26433 problems.
26434 @c END OF INLINE ASSEMBLER CHAPTER
26435 @c ===============================
26438 @c *****************************************
26439 @c Writing Portable Fixed-Point Declarations
26440 @c *****************************************
26441 @node Writing Portable Fixed-Point Declarations
26442 @appendix Writing Portable Fixed-Point Declarations
26443 @cindex Fixed-point types (writing portable declarations)
26445 @noindent
26446 The Ada Reference Manual gives an implementation freedom to choose bounds
26447 that are narrower by @code{Small} from the given bounds.
26448 For example, if we write
26450 @smallexample @c ada
26451    type F1 is delta 1.0 range -128.0 .. +128.0;
26452 @end smallexample
26454 @noindent
26455 then the implementation is allowed to choose -128.0 .. +127.0 if it
26456 likes, but is not required to do so.
26458 This leads to possible portability problems, so let's have a closer
26459 look at this, and figure out how to avoid these problems.
26461 First, why does this freedom exist, and why would an implementation
26462 take advantage of it? To answer this, take a closer look at the type
26463 declaration for @code{F1} above. If the compiler uses the given bounds,
26464 it would need 9 bits to hold the largest positive value (and typically
26465 that means 16 bits on all machines). But if the implementation chooses
26466 the +127.0 bound then it can fit values of the type in 8 bits.
26468 Why not make the user write +127.0 if that's what is wanted?
26469 The rationale is that if you are thinking of fixed point
26470 as a kind of ``poor man's floating-point'', then you don't want
26471 to be thinking about the scaled integers that are used in its
26472 representation. Let's take another example:
26474 @smallexample @c ada
26475    type F2 is delta 2.0**(-15) range -1.0 .. +1.0;
26476 @end smallexample
26478 @noindent
26479 Looking at this declaration, it seems casually as though
26480 it should fit in 16 bits, but again that extra positive value
26481 +1.0 has the scaled integer equivalent of 2**15 which is one too
26482 big for signed 16 bits. The implementation can treat this as:
26484 @smallexample @c ada
26485    type F2 is delta 2.0**(-15) range -1.0 .. +1.0-(2.0**(-15));
26486 @end smallexample
26488 @noindent
26489 and the Ada language design team felt that this was too annoying
26490 to require. We don't need to debate this decision at this point,
26491 since it is well established (the rule about narrowing the ranges
26492 dates to Ada 83).
26494 But the important point is that an implementation is not required
26495 to do this narrowing, so we have a potential portability problem.
26496 We could imagine three types of implementation:
26498 @enumerate a
26499 @item
26500 those that narrow the range automatically if they can figure
26501 out that the narrower range will allow storage in a smaller machine unit,
26503 @item
26504 those that will narrow only if forced to by a @code{'Size} clause, and
26506 @item
26507 those that will never narrow.
26508 @end enumerate
26510 @noindent
26511 Now if we are language theoreticians, we can imagine a fourth
26512 approach: is to narrow all the time, e.g. to treat
26514 @smallexample @c ada
26515    type F3 is delta 1.0 range -10.0 .. +23.0;
26516 @end smallexample
26518 @noindent
26519 as though it had been written:
26521 @smallexample @c ada
26522    type F3 is delta 1.0 range -9.0 .. +22.0;
26523 @end smallexample
26525 @noindent
26526 But although technically allowed, such a behavior would be hostile and silly,
26527 and no real compiler would do this. All real compilers will fall into one of
26528 the categories (a), (b) or (c) above.
26530 So, how do you get the compiler to do what you want? The answer is give the
26531 actual bounds you want, and then use a @code{'Small} clause and a
26532 @code{'Size} clause to absolutely pin down what the compiler does.
26533 E.g., for @code{F2} above, we will write:
26535 @smallexample @c ada
26536 @group
26537    My_Small : constant := 2.0**(-15);
26538    My_First : constant := -1.0;
26539    My_Last  : constant := +1.0 - My_Small;
26541    type F2 is delta My_Small range My_First .. My_Last;
26542 @end group
26543 @end smallexample
26545 @noindent
26546 and then add
26548 @smallexample @c ada
26549 @group
26550    for F2'Small use my_Small;
26551    for F2'Size  use 16;
26552 @end group
26553 @end smallexample
26555 @noindent
26556 In practice all compilers will do the same thing here and will give you
26557 what you want, so the above declarations are fully portable. If you really
26558 want to play language lawyer and guard against ludicrous behavior by the
26559 compiler you could add
26561 @smallexample @c ada
26562 @group
26563    Test1 : constant := 1 / Boolean'Pos (F2'First = My_First);
26564    Test2 : constant := 1 / Boolean'Pos (F2'Last  = My_Last);
26565 @end group
26566 @end smallexample
26568 @noindent
26569 One or other or both are allowed to be illegal if the compiler is
26570 behaving in a silly manner, but at least the silly compiler will not
26571 get away with silently messing with your (very clear) intentions.
26573 If you follow this scheme you will be guaranteed that your fixed-point
26574 types will be portable.
26577 @c ***********************************
26578 @c * Compatibility and Porting Guide *
26579 @c ***********************************
26580 @node Compatibility and Porting Guide
26581 @appendix Compatibility and Porting Guide
26583 @noindent
26584 This chapter describes the compatibility issues that may arise between
26585 GNAT and other Ada compilation systems (including those for Ada 83),
26586 and shows how GNAT can expedite porting
26587 applications developed in other Ada environments.
26589 @menu
26590 * Compatibility with Ada 83::
26591 * Compatibility between Ada 95 and Ada 2005::
26592 * Implementation-dependent characteristics::
26593 * Compatibility with Other Ada Systems::
26594 * Representation Clauses::
26595 @c Brief section is only in non-VMS version
26596 @c Full chapter is in VMS version
26597 * Compatibility with HP Ada 83::
26598 @end menu
26600 @node Compatibility with Ada 83
26601 @section Compatibility with Ada 83
26602 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26604 @noindent
26605 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
26606 particular, the design intention was that the difficulties associated
26607 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26608 that occur when moving from one Ada 83 system to another.
26610 However, there are a number of points at which there are minor
26611 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26612 full details of these issues,
26613 and should be consulted for a complete treatment.
26614 In practice the
26615 following subsections treat the most likely issues to be encountered.
26617 @menu
26618 * Legal Ada 83 programs that are illegal in Ada 95::
26619 * More deterministic semantics::
26620 * Changed semantics::
26621 * Other language compatibility issues::
26622 @end menu
26624 @node Legal Ada 83 programs that are illegal in Ada 95
26625 @subsection Legal Ada 83 programs that are illegal in Ada 95
26627 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26628 Ada 95 and thus also in Ada 2005:
26630 @table @emph
26631 @item Character literals
26632 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26633 @code{Wide_Character} as a new predefined character type, some uses of
26634 character literals that were legal in Ada 83 are illegal in Ada 95.
26635 For example:
26636 @smallexample @c ada
26637    @b{for} Char @b{in} 'A' .. 'Z' @b{loop} @dots{} @b{end} @b{loop};
26638 @end smallexample
26640 @noindent
26641 The problem is that @code{'A'} and @code{'Z'} could be from either
26642 @code{Character} or @code{Wide_Character}.  The simplest correction
26643 is to make the type explicit; e.g.:
26644 @smallexample @c ada
26645    @b{for} Char @b{in} Character @b{range} 'A' .. 'Z' @b{loop} @dots{} @b{end} @b{loop};
26646 @end smallexample
26648 @item New reserved words
26649 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26650 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26651 Existing Ada 83 code using any of these identifiers must be edited to
26652 use some alternative name.
26654 @item Freezing rules
26655 The rules in Ada 95 are slightly different with regard to the point at
26656 which entities are frozen, and representation pragmas and clauses are
26657 not permitted past the freeze point.  This shows up most typically in
26658 the form of an error message complaining that a representation item
26659 appears too late, and the appropriate corrective action is to move
26660 the item nearer to the declaration of the entity to which it refers.
26662 A particular case is that representation pragmas
26663 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26664 declaration must be introduced to which the pragma can be applied.
26666 @item Optional bodies for library packages
26667 In Ada 83, a package that did not require a package body was nevertheless
26668 allowed to have one.  This lead to certain surprises in compiling large
26669 systems (situations in which the body could be unexpectedly ignored by the
26670 binder).  In Ada 95, if a package does not require a body then it is not
26671 permitted to have a body.  To fix this problem, simply remove a redundant
26672 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26673 into the spec that makes the body required.  One approach is to add a private
26674 part to the package declaration (if necessary), and define a parameterless
26675 procedure called @code{Requires_Body}, which must then be given a dummy
26676 procedure body in the package body, which then becomes required.
26677 Another approach (assuming that this does not introduce elaboration
26678 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26679 since one effect of this pragma is to require the presence of a package body.
26681 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26682 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26683 @code{Constraint_Error}.
26684 This means that it is illegal to have separate exception handlers for
26685 the two exceptions.  The fix is simply to remove the handler for the
26686 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26687 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26689 @item Indefinite subtypes in generics
26690 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26691 as the actual for a generic formal private type, but then the instantiation
26692 would be illegal if there were any instances of declarations of variables
26693 of this type in the generic body.  In Ada 95, to avoid this clear violation
26694 of the methodological principle known as the ``contract model'',
26695 the generic declaration explicitly indicates whether
26696 or not such instantiations are permitted.  If a generic formal parameter
26697 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26698 subtype name, then it can be instantiated with indefinite types, but no
26699 stand-alone variables can be declared of this type.  Any attempt to declare
26700 such a variable will result in an illegality at the time the generic is
26701 declared.  If the @code{(<>)} notation is not used, then it is illegal
26702 to instantiate the generic with an indefinite type.
26703 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26704 It will show up as a compile time error, and
26705 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26706 @end table
26708 @node More deterministic semantics
26709 @subsection More deterministic semantics
26711 @table @emph
26712 @item Conversions
26713 Conversions from real types to integer types round away from 0.  In Ada 83
26714 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26715 implementation freedom was intended to support unbiased rounding in
26716 statistical applications, but in practice it interfered with portability.
26717 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26718 is required.  Numeric code may be affected by this change in semantics.
26719 Note, though, that this issue is no worse than already existed in Ada 83
26720 when porting code from one vendor to another.
26722 @item Tasking
26723 The Real-Time Annex introduces a set of policies that define the behavior of
26724 features that were implementation dependent in Ada 83, such as the order in
26725 which open select branches are executed.
26726 @end table
26728 @node Changed semantics
26729 @subsection Changed semantics
26731 @noindent
26732 The worst kind of incompatibility is one where a program that is legal in
26733 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26734 possible in Ada 83.  Fortunately this is extremely rare, but the one
26735 situation that you should be alert to is the change in the predefined type
26736 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26738 @table @emph
26739 @item Range of type @code{Character}
26740 The range of @code{Standard.Character} is now the full 256 characters
26741 of Latin-1, whereas in most Ada 83 implementations it was restricted
26742 to 128 characters. Although some of the effects of
26743 this change will be manifest in compile-time rejection of legal
26744 Ada 83 programs it is possible for a working Ada 83 program to have
26745 a different effect in Ada 95, one that was not permitted in Ada 83.
26746 As an example, the expression
26747 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26748 delivers @code{255} as its value.
26749 In general, you should look at the logic of any
26750 character-processing Ada 83 program and see whether it needs to be adapted
26751 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26752 character handling package that may be relevant if code needs to be adapted
26753 to account for the additional Latin-1 elements.
26754 The desirable fix is to
26755 modify the program to accommodate the full character set, but in some cases
26756 it may be convenient to define a subtype or derived type of Character that
26757 covers only the restricted range.
26758 @cindex Latin-1
26759 @end table
26761 @node Other language compatibility issues
26762 @subsection Other language compatibility issues
26764 @table @emph
26765 @item @option{-gnat83} switch
26766 All implementations of GNAT provide a switch that causes GNAT to operate
26767 in Ada 83 mode.  In this mode, some but not all compatibility problems
26768 of the type described above are handled automatically.  For example, the
26769 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26770 as identifiers as in Ada 83.
26771 However,
26772 in practice, it is usually advisable to make the necessary modifications
26773 to the program to remove the need for using this switch.
26774 See @ref{Compiling Different Versions of Ada}.
26776 @item Support for removed Ada 83 pragmas and attributes
26777 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26778 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26779 compilers are allowed, but not required, to implement these missing
26780 elements.  In contrast with some other compilers, GNAT implements all
26781 such pragmas and attributes, eliminating this compatibility concern.  These
26782 include @code{pragma Interface} and the floating point type attributes
26783 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26784 @end table
26787 @node Compatibility between Ada 95 and Ada 2005
26788 @section Compatibility between Ada 95 and Ada 2005
26789 @cindex Compatibility between Ada 95 and Ada 2005
26791 @noindent
26792 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26793 a number of incompatibilities. Several are enumerated below;
26794 for a complete description please see the
26795 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26796 @cite{Rationale for Ada 2005}.
26798 @table @emph
26799 @item New reserved words.
26800 The words @code{interface}, @code{overriding} and @code{synchronized} are
26801 reserved in Ada 2005.
26802 A pre-Ada 2005 program that uses any of these as an identifier will be
26803 illegal.
26805 @item New declarations in predefined packages.
26806 A number of packages in the predefined environment contain new declarations:
26807 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26808 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26809 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26810 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26811 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26812 If an Ada 95 program does a @code{with} and @code{use} of any of these
26813 packages, the new declarations may cause name clashes.
26815 @item Access parameters.
26816 A nondispatching subprogram with an access parameter cannot be renamed
26817 as a dispatching operation.  This was permitted in Ada 95.
26819 @item Access types, discriminants, and constraints.
26820 Rule changes in this area have led to some incompatibilities; for example,
26821 constrained subtypes of some access types are not permitted in Ada 2005.
26823 @item Aggregates for limited types.
26824 The allowance of aggregates for limited types in Ada 2005 raises the
26825 possibility of ambiguities in legal Ada 95 programs, since additional types
26826 now need to be considered in expression resolution.
26828 @item Fixed-point multiplication and division.
26829 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26830 were legal in Ada 95 and invoked the predefined versions of these operations,
26831 are now ambiguous.
26832 The ambiguity may be resolved either by applying a type conversion to the
26833 expression, or by explicitly invoking the operation from package
26834 @code{Standard}.
26836 @item Return-by-reference types.
26837 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26838 can declare a function returning a value from an anonymous access type.
26839 @end table
26842 @node Implementation-dependent characteristics
26843 @section Implementation-dependent characteristics
26844 @noindent
26845 Although the Ada language defines the semantics of each construct as
26846 precisely as practical, in some situations (for example for reasons of
26847 efficiency, or where the effect is heavily dependent on the host or target
26848 platform) the implementation is allowed some freedom.  In porting Ada 83
26849 code to GNAT, you need to be aware of whether / how the existing code
26850 exercised such implementation dependencies.  Such characteristics fall into
26851 several categories, and GNAT offers specific support in assisting the
26852 transition from certain Ada 83 compilers.
26854 @menu
26855 * Implementation-defined pragmas::
26856 * Implementation-defined attributes::
26857 * Libraries::
26858 * Elaboration order::
26859 * Target-specific aspects::
26860 @end menu
26862 @node Implementation-defined pragmas
26863 @subsection Implementation-defined pragmas
26865 @noindent
26866 Ada compilers are allowed to supplement the language-defined pragmas, and
26867 these are a potential source of non-portability.  All GNAT-defined pragmas
26868 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26869 Reference Manual}, and these include several that are specifically
26870 intended to correspond to other vendors' Ada 83 pragmas.
26871 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26872 For compatibility with HP Ada 83, GNAT supplies the pragmas
26873 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26874 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26875 and @code{Volatile}.
26876 Other relevant pragmas include @code{External} and @code{Link_With}.
26877 Some vendor-specific
26878 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26879 recognized, thus
26880 avoiding compiler rejection of units that contain such pragmas; they are not
26881 relevant in a GNAT context and hence are not otherwise implemented.
26883 @node Implementation-defined attributes
26884 @subsection Implementation-defined attributes
26886 Analogous to pragmas, the set of attributes may be extended by an
26887 implementation.  All GNAT-defined attributes are described in
26888 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26889 Manual}, and these include several that are specifically intended
26890 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26891 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26892 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26893 @code{Type_Class}.
26895 @node Libraries
26896 @subsection Libraries
26897 @noindent
26898 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26899 code uses vendor-specific libraries then there are several ways to manage
26900 this in Ada 95 or Ada 2005:
26901 @enumerate
26902 @item
26903 If the source code for the libraries (specs and bodies) are
26904 available, then the libraries can be migrated in the same way as the
26905 application.
26906 @item
26907 If the source code for the specs but not the bodies are
26908 available, then you can reimplement the bodies.
26909 @item
26910 Some features introduced by Ada 95 obviate the need for library support.  For
26911 example most Ada 83 vendors supplied a package for unsigned integers.  The
26912 Ada 95 modular type feature is the preferred way to handle this need, so
26913 instead of migrating or reimplementing the unsigned integer package it may
26914 be preferable to retrofit the application using modular types.
26915 @end enumerate
26917 @node Elaboration order
26918 @subsection Elaboration order
26919 @noindent
26920 The implementation can choose any elaboration order consistent with the unit
26921 dependency relationship.  This freedom means that some orders can result in
26922 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26923 to invoke a subprogram its body has been elaborated, or to instantiate a
26924 generic before the generic body has been elaborated.  By default GNAT
26925 attempts to choose a safe order (one that will not encounter access before
26926 elaboration problems) by implicitly inserting @code{Elaborate} or
26927 @code{Elaborate_All} pragmas where
26928 needed.  However, this can lead to the creation of elaboration circularities
26929 and a resulting rejection of the program by gnatbind.  This issue is
26930 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26931 In brief, there are several
26932 ways to deal with this situation:
26934 @itemize @bullet
26935 @item
26936 Modify the program to eliminate the circularities, e.g.@: by moving
26937 elaboration-time code into explicitly-invoked procedures
26938 @item
26939 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26940 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26941 @code{Elaborate_All}
26942 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26943 (by selectively suppressing elaboration checks via pragma
26944 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26945 @end itemize
26947 @node Target-specific aspects
26948 @subsection Target-specific aspects
26949 @noindent
26950 Low-level applications need to deal with machine addresses, data
26951 representations, interfacing with assembler code, and similar issues.  If
26952 such an Ada 83 application is being ported to different target hardware (for
26953 example where the byte endianness has changed) then you will need to
26954 carefully examine the program logic; the porting effort will heavily depend
26955 on the robustness of the original design.  Moreover, Ada 95 (and thus
26956 Ada 2005) are sometimes
26957 incompatible with typical Ada 83 compiler practices regarding implicit
26958 packing, the meaning of the Size attribute, and the size of access values.
26959 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26961 @node Compatibility with Other Ada Systems
26962 @section Compatibility with Other Ada Systems
26964 @noindent
26965 If programs avoid the use of implementation dependent and
26966 implementation defined features, as documented in the @cite{Ada
26967 Reference Manual}, there should be a high degree of portability between
26968 GNAT and other Ada systems.  The following are specific items which
26969 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26970 compilers, but do not affect porting code to GNAT@.
26971 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26972 the following issues may or may not arise for Ada 2005 programs
26973 when other compilers appear.)
26975 @table @emph
26976 @item Ada 83 Pragmas and Attributes
26977 Ada 95 compilers are allowed, but not required, to implement the missing
26978 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26979 GNAT implements all such pragmas and attributes, eliminating this as
26980 a compatibility concern, but some other Ada 95 compilers reject these
26981 pragmas and attributes.
26983 @item Specialized Needs Annexes
26984 GNAT implements the full set of special needs annexes.  At the
26985 current time, it is the only Ada 95 compiler to do so.  This means that
26986 programs making use of these features may not be portable to other Ada
26987 95 compilation systems.
26989 @item Representation Clauses
26990 Some other Ada 95 compilers implement only the minimal set of
26991 representation clauses required by the Ada 95 reference manual.  GNAT goes
26992 far beyond this minimal set, as described in the next section.
26993 @end table
26995 @node Representation Clauses
26996 @section Representation Clauses
26998 @noindent
26999 The Ada 83 reference manual was quite vague in describing both the minimal
27000 required implementation of representation clauses, and also their precise
27001 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
27002 minimal set of capabilities required is still quite limited.
27004 GNAT implements the full required set of capabilities in
27005 Ada 95 and Ada 2005, but also goes much further, and in particular
27006 an effort has been made to be compatible with existing Ada 83 usage to the
27007 greatest extent possible.
27009 A few cases exist in which Ada 83 compiler behavior is incompatible with
27010 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
27011 intentional or accidental dependence on specific implementation dependent
27012 characteristics of these Ada 83 compilers.  The following is a list of
27013 the cases most likely to arise in existing Ada 83 code.
27015 @table @emph
27016 @item Implicit Packing
27017 Some Ada 83 compilers allowed a Size specification to cause implicit
27018 packing of an array or record.  This could cause expensive implicit
27019 conversions for change of representation in the presence of derived
27020 types, and the Ada design intends to avoid this possibility.
27021 Subsequent AI's were issued to make it clear that such implicit
27022 change of representation in response to a Size clause is inadvisable,
27023 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
27024 Reference Manuals as implementation advice that is followed by GNAT@.
27025 The problem will show up as an error
27026 message rejecting the size clause.  The fix is simply to provide
27027 the explicit pragma @code{Pack}, or for more fine tuned control, provide
27028 a Component_Size clause.
27030 @item Meaning of Size Attribute
27031 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
27032 the minimal number of bits required to hold values of the type.  For example,
27033 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
27034 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
27035 some 32 in this situation.  This problem will usually show up as a compile
27036 time error, but not always.  It is a good idea to check all uses of the
27037 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
27038 Object_Size can provide a useful way of duplicating the behavior of
27039 some Ada 83 compiler systems.
27041 @item Size of Access Types
27042 A common assumption in Ada 83 code is that an access type is in fact a pointer,
27043 and that therefore it will be the same size as a System.Address value.  This
27044 assumption is true for GNAT in most cases with one exception.  For the case of
27045 a pointer to an unconstrained array type (where the bounds may vary from one
27046 value of the access type to another), the default is to use a ``fat pointer'',
27047 which is represented as two separate pointers, one to the bounds, and one to
27048 the array.  This representation has a number of advantages, including improved
27049 efficiency.  However, it may cause some difficulties in porting existing Ada 83
27050 code which makes the assumption that, for example, pointers fit in 32 bits on
27051 a machine with 32-bit addressing.
27053 To get around this problem, GNAT also permits the use of ``thin pointers'' for
27054 access types in this case (where the designated type is an unconstrained array
27055 type).  These thin pointers are indeed the same size as a System.Address value.
27056 To specify a thin pointer, use a size clause for the type, for example:
27058 @smallexample @c ada
27059 @b{type} X @b{is} @b{access} @b{all} String;
27060 @b{for} X'Size @b{use} Standard'Address_Size;
27061 @end smallexample
27063 @noindent
27064 which will cause the type X to be represented using a single pointer.
27065 When using this representation, the bounds are right behind the array.
27066 This representation is slightly less efficient, and does not allow quite
27067 such flexibility in the use of foreign pointers or in using the
27068 Unrestricted_Access attribute to create pointers to non-aliased objects.
27069 But for any standard portable use of the access type it will work in
27070 a functionally correct manner and allow porting of existing code.
27071 Note that another way of forcing a thin pointer representation
27072 is to use a component size clause for the element size in an array,
27073 or a record representation clause for an access field in a record.
27075 See the documentation of Unrestricted_Access in the GNAT RM for a
27076 full discussion of possible problems using this attribute in conjunction
27077 with thin pointers.
27078 @end table
27080 @c This brief section is only in the non-VMS version
27081 @c The complete chapter on HP Ada is in the VMS version
27082 @node Compatibility with HP Ada 83
27083 @section Compatibility with HP Ada 83
27085 @noindent
27086 The VMS version of GNAT fully implements all the pragmas and attributes
27087 provided by HP Ada 83, as well as providing the standard HP Ada 83
27088 libraries, including Starlet.  In addition, data layouts and parameter
27089 passing conventions are highly compatible.  This means that porting
27090 existing HP Ada 83 code to GNAT in VMS systems should be easier than
27091 most other porting efforts.  The following are some of the most
27092 significant differences between GNAT and HP Ada 83.
27094 @table @emph
27095 @item Default floating-point representation
27096 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
27097 it is VMS format.  GNAT does implement the necessary pragmas
27098 (Long_Float, Float_Representation) for changing this default.
27100 @item System
27101 The package System in GNAT exactly corresponds to the definition in the
27102 Ada 95 reference manual, which means that it excludes many of the
27103 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
27104 that contains the additional definitions, and a special pragma,
27105 Extend_System allows this package to be treated transparently as an
27106 extension of package System.
27108 @item To_Address
27109 The definitions provided by Aux_DEC are exactly compatible with those
27110 in the HP Ada 83 version of System, with one exception.
27111 HP Ada provides the following declarations:
27113 @smallexample @c ada
27114 TO_ADDRESS (INTEGER)
27115 TO_ADDRESS (UNSIGNED_LONGWORD)
27116 TO_ADDRESS (@i{universal_integer})
27117 @end smallexample
27119 @noindent
27120 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
27121 an extension to Ada 83 not strictly compatible with the reference manual.
27122 In GNAT, we are constrained to be exactly compatible with the standard,
27123 and this means we cannot provide this capability.  In HP Ada 83, the
27124 point of this definition is to deal with a call like:
27126 @smallexample @c ada
27127 TO_ADDRESS (16#12777#);
27128 @end smallexample
27130 @noindent
27131 Normally, according to the Ada 83 standard, one would expect this to be
27132 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
27133 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
27134 definition using @i{universal_integer} takes precedence.
27136 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
27137 is not possible to be 100% compatible.  Since there are many programs using
27138 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
27139 to change the name of the function in the UNSIGNED_LONGWORD case, so the
27140 declarations provided in the GNAT version of AUX_Dec are:
27142 @smallexample @c ada
27143 @b{function} To_Address (X : Integer) @b{return} Address;
27144 @b{pragma} Pure_Function (To_Address);
27146 @b{function} To_Address_Long (X : Unsigned_Longword)
27147  @b{return} Address;
27148 @b{pragma} Pure_Function (To_Address_Long);
27149 @end smallexample
27151 @noindent
27152 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
27153 change the name to TO_ADDRESS_LONG@.
27155 @item Task_Id values
27156 The Task_Id values assigned will be different in the two systems, and GNAT
27157 does not provide a specified value for the Task_Id of the environment task,
27158 which in GNAT is treated like any other declared task.
27159 @end table
27161 @noindent
27162 For full details on these and other less significant compatibility issues,
27163 see appendix E of the HP publication entitled @cite{HP Ada, Technical
27164 Overview and Comparison on HP Platforms}.
27166 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
27167 attributes are recognized, although only a subset of them can sensibly
27168 be implemented.  The description of pragmas in @ref{Implementation
27169 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
27170 indicates whether or not they are applicable to non-VMS systems.
27173 @c ************************************************
27174 @node Microsoft Windows Topics
27175 @appendix Microsoft Windows Topics
27176 @cindex Windows NT
27177 @cindex Windows 95
27178 @cindex Windows 98
27180 @noindent
27181 This chapter describes topics that are specific to the Microsoft Windows
27182 platforms (NT, 2000, and XP Professional).
27184 @menu
27185 @ifclear FSFEDITION
27186 * Installing from the Command Line::
27187 @end ifclear
27188 * Using GNAT on Windows::
27189 * Using a network installation of GNAT::
27190 * CONSOLE and WINDOWS subsystems::
27191 * Temporary Files::
27192 * Mixed-Language Programming on Windows::
27193 * Windows Calling Conventions::
27194 * Introduction to Dynamic Link Libraries (DLLs)::
27195 * Using DLLs with GNAT::
27196 * Building DLLs with GNAT Project files::
27197 * Building DLLs with GNAT::
27198 * Building DLLs with gnatdll::
27199 * GNAT and Windows Resources::
27200 * Debugging a DLL::
27201 * Setting Stack Size from gnatlink::
27202 * Setting Heap Size from gnatlink::
27203 @end menu
27205 @ifclear FSFEDITION
27206 @node Installing from the Command Line
27207 @section Installing from the Command Line
27208 @cindex Batch installation
27209 @cindex Silent installation
27210 @cindex Unassisted installation
27212 @noindent
27213 By default the @value{EDITION} installers display a GUI that prompts the user
27214 to enter installation path and similar information, and guide him through the
27215 installation process. It is also possible to perform silent installations
27216 using the command-line interface.
27218 In order to install one of the @value{EDITION} installers from the command
27219 line you should pass parameter @code{/S} (and, optionally,
27220 @code{/D=<directory>}) as command-line arguments.
27222 @ifset PROEDITION
27223 For example, for an unattended installation of
27224 @value{EDITION} 7.0.2 into the default directory
27225 @code{C:\GNATPRO\7.0.2} you would run:
27227 @smallexample
27228 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
27229 @end smallexample
27231 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
27233 @smallexample
27234 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
27235 @end smallexample
27236 @end ifset
27238 @ifset GPLEDITION
27239 For example, for an unattended installation of
27240 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
27242 @smallexample
27243 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
27244 @end smallexample
27245 @end ifset
27247 You can use the same syntax for all installers.
27249 Note that unattended installations don't modify system path, nor create file
27250 associations, so such activities need to be done by hand.
27251 @end ifclear
27253 @node Using GNAT on Windows
27254 @section Using GNAT on Windows
27256 @noindent
27257 One of the strengths of the GNAT technology is that its tool set
27258 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27259 @code{gdb} debugger, etc.) is used in the same way regardless of the
27260 platform.
27262 On Windows this tool set is complemented by a number of Microsoft-specific
27263 tools that have been provided to facilitate interoperability with Windows
27264 when this is required. With these tools:
27266 @itemize @bullet
27268 @item
27269 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27270 subsystems.
27272 @item
27273 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27274 relocatable and non-relocatable DLLs are supported).
27276 @item
27277 You can build Ada DLLs for use in other applications. These applications
27278 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27279 relocatable and non-relocatable Ada DLLs are supported.
27281 @item
27282 You can include Windows resources in your Ada application.
27284 @item
27285 You can use or create COM/DCOM objects.
27286 @end itemize
27288 @noindent
27289 Immediately below are listed all known general GNAT-for-Windows restrictions.
27290 Other restrictions about specific features like Windows Resources and DLLs
27291 are listed in separate sections below.
27293 @itemize @bullet
27295 @item
27296 It is not possible to use @code{GetLastError} and @code{SetLastError}
27297 when tasking, protected records, or exceptions are used. In these
27298 cases, in order to implement Ada semantics, the GNAT run-time system
27299 calls certain Win32 routines that set the last error variable to 0 upon
27300 success. It should be possible to use @code{GetLastError} and
27301 @code{SetLastError} when tasking, protected record, and exception
27302 features are not used, but it is not guaranteed to work.
27304 @item
27305 It is not possible to link against Microsoft C++ libraries except for
27306 import libraries. Interfacing must be done by the mean of DLLs.
27308 @item
27309 It is possible to link against Microsoft C libraries. Yet the preferred
27310 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
27311 doesn't require having two different development environments and makes the
27312 inter-language debugging experience smoother.
27314 @item
27315 When the compilation environment is located on FAT32 drives, users may
27316 experience recompilations of the source files that have not changed if
27317 Daylight Saving Time (DST) state has changed since the last time files
27318 were compiled. NTFS drives do not have this problem.
27320 @item
27321 No components of the GNAT toolset use any entries in the Windows
27322 registry. The only entries that can be created are file associations and
27323 PATH settings, provided the user has chosen to create them at installation
27324 time, as well as some minimal book-keeping information needed to correctly
27325 uninstall or integrate different GNAT products.
27326 @end itemize
27328 @node Using a network installation of GNAT
27329 @section Using a network installation of GNAT
27331 @noindent
27332 Make sure the system on which GNAT is installed is accessible from the
27333 current machine, i.e., the install location is shared over the network.
27334 Shared resources are accessed on Windows by means of UNC paths, which
27335 have the format @code{\\server\sharename\path}
27337 In order to use such a network installation, simply add the UNC path of the
27338 @file{bin} directory of your GNAT installation in front of your PATH. For
27339 example, if GNAT is installed in @file{\GNAT} directory of a share location
27340 called @file{c-drive} on a machine @file{LOKI}, the following command will
27341 make it available:
27343 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27345 Be aware that every compilation using the network installation results in the
27346 transfer of large amounts of data across the network and will likely cause
27347 serious performance penalty.
27349 @node CONSOLE and WINDOWS subsystems
27350 @section CONSOLE and WINDOWS subsystems
27351 @cindex CONSOLE Subsystem
27352 @cindex WINDOWS Subsystem
27353 @cindex -mwindows
27355 @noindent
27356 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27357 (which is the default subsystem) will always create a console when
27358 launching the application. This is not something desirable when the
27359 application has a Windows GUI. To get rid of this console the
27360 application must be using the @code{WINDOWS} subsystem. To do so
27361 the @option{-mwindows} linker option must be specified.
27363 @smallexample
27364 $ gnatmake winprog -largs -mwindows
27365 @end smallexample
27367 @node Temporary Files
27368 @section Temporary Files
27369 @cindex Temporary files
27371 @noindent
27372 It is possible to control where temporary files gets created by setting
27373 the @env{TMP} environment variable. The file will be created:
27375 @itemize
27376 @item Under the directory pointed to by the @env{TMP} environment variable if
27377 this directory exists.
27379 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27380 set (or not pointing to a directory) and if this directory exists.
27382 @item Under the current working directory otherwise.
27383 @end itemize
27385 @noindent
27386 This allows you to determine exactly where the temporary
27387 file will be created. This is particularly useful in networked
27388 environments where you may not have write access to some
27389 directories.
27391 @node Mixed-Language Programming on Windows
27392 @section Mixed-Language Programming on Windows
27394 @noindent
27395 Developing pure Ada applications on Windows is no different than on
27396 other GNAT-supported platforms. However, when developing or porting an
27397 application that contains a mix of Ada and C/C++, the choice of your
27398 Windows C/C++ development environment conditions your overall
27399 interoperability strategy.
27401 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
27402 your application, there are no Windows-specific restrictions that
27403 affect the overall interoperability with your Ada code. If you do want
27404 to use the Microsoft tools for your C++ code, you have two choices:
27406 @enumerate
27407 @item
27408 Encapsulate your C++ code in a DLL to be linked with your Ada
27409 application. In this case, use the Microsoft or whatever environment to
27410 build the DLL and use GNAT to build your executable
27411 (@pxref{Using DLLs with GNAT}).
27413 @item
27414 Or you can encapsulate your Ada code in a DLL to be linked with the
27415 other part of your application. In this case, use GNAT to build the DLL
27416 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27417 or whatever environment to build your executable.
27418 @end enumerate
27420 In addition to the description about C main in
27421 @pxref{Mixed Language Programming} section, if the C main uses a
27422 stand-alone library it is required on x86-windows to
27423 setup the SEH context. For this the C main must looks like this:
27425 @smallexample
27426 /* main.c */
27427 extern void adainit (void);
27428 extern void adafinal (void);
27429 extern void __gnat_initialize(void*);
27430 extern void call_to_ada (void);
27432 int main (int argc, char *argv[])
27434   int SEH [2];
27436   /* Initialize the SEH context */
27437   __gnat_initialize (&SEH);
27439   adainit();
27441   /* Then call Ada services in the stand-alone library */
27443   call_to_ada();
27445   adafinal();
27447 @end smallexample
27449 Note that this is not needed on x86_64-windows where the Windows
27450 native SEH support is used.
27452 @node Windows Calling Conventions
27453 @section Windows Calling Conventions
27454 @findex Stdcall
27455 @findex APIENTRY
27457 This section pertain only to Win32. On Win64 there is a single native
27458 calling convention. All convention specifiers are ignored on this
27459 platform.
27461 @menu
27462 * C Calling Convention::
27463 * Stdcall Calling Convention::
27464 * Win32 Calling Convention::
27465 * DLL Calling Convention::
27466 @end menu
27468 @noindent
27469 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27470 (callee), there are several ways to push @code{G}'s parameters on the
27471 stack and there are several possible scenarios to clean up the stack
27472 upon @code{G}'s return. A calling convention is an agreed upon software
27473 protocol whereby the responsibilities between the caller (@code{F}) and
27474 the callee (@code{G}) are clearly defined. Several calling conventions
27475 are available for Windows:
27477 @itemize @bullet
27478 @item
27479 @code{C} (Microsoft defined)
27481 @item
27482 @code{Stdcall} (Microsoft defined)
27484 @item
27485 @code{Win32} (GNAT specific)
27487 @item
27488 @code{DLL} (GNAT specific)
27489 @end itemize
27491 @node C Calling Convention
27492 @subsection @code{C} Calling Convention
27494 @noindent
27495 This is the default calling convention used when interfacing to C/C++
27496 routines compiled with either @command{gcc} or Microsoft Visual C++.
27498 In the @code{C} calling convention subprogram parameters are pushed on the
27499 stack by the caller from right to left. The caller itself is in charge of
27500 cleaning up the stack after the call. In addition, the name of a routine
27501 with @code{C} calling convention is mangled by adding a leading underscore.
27503 The name to use on the Ada side when importing (or exporting) a routine
27504 with @code{C} calling convention is the name of the routine. For
27505 instance the C function:
27507 @smallexample
27508 int get_val (long);
27509 @end smallexample
27511 @noindent
27512 should be imported from Ada as follows:
27514 @smallexample @c ada
27515 @group
27516 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27517 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
27518 @end group
27519 @end smallexample
27521 @noindent
27522 Note that in this particular case the @code{External_Name} parameter could
27523 have been omitted since, when missing, this parameter is taken to be the
27524 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27525 is missing, as in the above example, this parameter is set to be the
27526 @code{External_Name} with a leading underscore.
27528 When importing a variable defined in C, you should always use the @code{C}
27529 calling convention unless the object containing the variable is part of a
27530 DLL (in which case you should use the @code{Stdcall} calling
27531 convention, @pxref{Stdcall Calling Convention}).
27533 @node Stdcall Calling Convention
27534 @subsection @code{Stdcall} Calling Convention
27536 @noindent
27537 This convention, which was the calling convention used for Pascal
27538 programs, is used by Microsoft for all the routines in the Win32 API for
27539 efficiency reasons. It must be used to import any routine for which this
27540 convention was specified.
27542 In the @code{Stdcall} calling convention subprogram parameters are pushed
27543 on the stack by the caller from right to left. The callee (and not the
27544 caller) is in charge of cleaning the stack on routine exit. In addition,
27545 the name of a routine with @code{Stdcall} calling convention is mangled by
27546 adding a leading underscore (as for the @code{C} calling convention) and a
27547 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27548 bytes) of the parameters passed to the routine.
27550 The name to use on the Ada side when importing a C routine with a
27551 @code{Stdcall} calling convention is the name of the C routine. The leading
27552 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27553 the compiler. For instance the Win32 function:
27555 @smallexample
27556 @b{APIENTRY} int get_val (long);
27557 @end smallexample
27559 @noindent
27560 should be imported from Ada as follows:
27562 @smallexample @c ada
27563 @group
27564 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27565 @b{pragma} Import (Stdcall, Get_Val);
27566 --@i{  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"}
27567 @end group
27568 @end smallexample
27570 @noindent
27571 As for the @code{C} calling convention, when the @code{External_Name}
27572 parameter is missing, it is taken to be the name of the Ada entity in lower
27573 case. If instead of writing the above import pragma you write:
27575 @smallexample @c ada
27576 @group
27577 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27578 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27579 @end group
27580 @end smallexample
27582 @noindent
27583 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27584 of specifying the @code{External_Name} parameter you specify the
27585 @code{Link_Name} as in the following example:
27587 @smallexample @c ada
27588 @group
27589 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
27590 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27591 @end group
27592 @end smallexample
27594 @noindent
27595 then the imported routine is @code{retrieve_val}, that is, there is no
27596 decoration at all. No leading underscore and no Stdcall suffix
27597 @code{@@}@code{@var{nn}}.
27599 @noindent
27600 This is especially important as in some special cases a DLL's entry
27601 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27602 name generated for a call has it.
27604 @noindent
27605 It is also possible to import variables defined in a DLL by using an
27606 import pragma for a variable. As an example, if a DLL contains a
27607 variable defined as:
27609 @smallexample
27610 int my_var;
27611 @end smallexample
27613 @noindent
27614 then, to access this variable from Ada you should write:
27616 @smallexample @c ada
27617 @group
27618 My_Var : Interfaces.C.int;
27619 @b{pragma} Import (Stdcall, My_Var);
27620 @end group
27621 @end smallexample
27623 @noindent
27624 Note that to ease building cross-platform bindings this convention
27625 will be handled as a @code{C} calling convention on non-Windows platforms.
27627 @node Win32 Calling Convention
27628 @subsection @code{Win32} Calling Convention
27630 @noindent
27631 This convention, which is GNAT-specific is fully equivalent to the
27632 @code{Stdcall} calling convention described above.
27634 @node DLL Calling Convention
27635 @subsection @code{DLL} Calling Convention
27637 @noindent
27638 This convention, which is GNAT-specific is fully equivalent to the
27639 @code{Stdcall} calling convention described above.
27641 @node Introduction to Dynamic Link Libraries (DLLs)
27642 @section Introduction to Dynamic Link Libraries (DLLs)
27643 @findex DLL
27645 @noindent
27646 A Dynamically Linked Library (DLL) is a library that can be shared by
27647 several applications running under Windows. A DLL can contain any number of
27648 routines and variables.
27650 One advantage of DLLs is that you can change and enhance them without
27651 forcing all the applications that depend on them to be relinked or
27652 recompiled. However, you should be aware than all calls to DLL routines are
27653 slower since, as you will understand below, such calls are indirect.
27655 To illustrate the remainder of this section, suppose that an application
27656 wants to use the services of a DLL @file{API.dll}. To use the services
27657 provided by @file{API.dll} you must statically link against the DLL or
27658 an import library which contains a jump table with an entry for each
27659 routine and variable exported by the DLL. In the Microsoft world this
27660 import library is called @file{API.lib}. When using GNAT this import
27661 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27662 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27664 After you have linked your application with the DLL or the import library
27665 and you run your application, here is what happens:
27667 @enumerate
27668 @item
27669 Your application is loaded into memory.
27671 @item
27672 The DLL @file{API.dll} is mapped into the address space of your
27673 application. This means that:
27675 @itemize @bullet
27676 @item
27677 The DLL will use the stack of the calling thread.
27679 @item
27680 The DLL will use the virtual address space of the calling process.
27682 @item
27683 The DLL will allocate memory from the virtual address space of the calling
27684 process.
27686 @item
27687 Handles (pointers) can be safely exchanged between routines in the DLL
27688 routines and routines in the application using the DLL.
27689 @end itemize
27691 @item
27692 The entries in the jump table (from the import library @file{libAPI.dll.a}
27693 or @file{API.lib} or automatically created when linking against a DLL)
27694 which is part of your application are initialized with the addresses
27695 of the routines and variables in @file{API.dll}.
27697 @item
27698 If present in @file{API.dll}, routines @code{DllMain} or
27699 @code{DllMainCRTStartup} are invoked. These routines typically contain
27700 the initialization code needed for the well-being of the routines and
27701 variables exported by the DLL.
27702 @end enumerate
27704 @noindent
27705 There is an additional point which is worth mentioning. In the Windows
27706 world there are two kind of DLLs: relocatable and non-relocatable
27707 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27708 in the target application address space. If the addresses of two
27709 non-relocatable DLLs overlap and these happen to be used by the same
27710 application, a conflict will occur and the application will run
27711 incorrectly. Hence, when possible, it is always preferable to use and
27712 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27713 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27714 User's Guide) removes the debugging symbols from the DLL but the DLL can
27715 still be relocated.
27717 As a side note, an interesting difference between Microsoft DLLs and
27718 Unix shared libraries, is the fact that on most Unix systems all public
27719 routines are exported by default in a Unix shared library, while under
27720 Windows it is possible (but not required) to list exported routines in
27721 a definition file (@pxref{The Definition File}).
27723 @node Using DLLs with GNAT
27724 @section Using DLLs with GNAT
27726 @menu
27727 * Creating an Ada Spec for the DLL Services::
27728 * Creating an Import Library::
27729 @end menu
27731 @noindent
27732 To use the services of a DLL, say @file{API.dll}, in your Ada application
27733 you must have:
27735 @enumerate
27736 @item
27737 The Ada spec for the routines and/or variables you want to access in
27738 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27739 header files provided with the DLL.
27741 @item
27742 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27743 mentioned an import library is a statically linked library containing the
27744 import table which will be filled at load time to point to the actual
27745 @file{API.dll} routines. Sometimes you don't have an import library for the
27746 DLL you want to use. The following sections will explain how to build
27747 one. Note that this is optional.
27749 @item
27750 The actual DLL, @file{API.dll}.
27751 @end enumerate
27753 @noindent
27754 Once you have all the above, to compile an Ada application that uses the
27755 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27756 you simply issue the command
27758 @smallexample
27759 $ gnatmake my_ada_app -largs -lAPI
27760 @end smallexample
27762 @noindent
27763 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27764 tells the GNAT linker to look for an import library. The linker will
27765 look for a library name in this specific order:
27767 @enumerate
27768 @item @file{libAPI.dll.a}
27769 @item @file{API.dll.a}
27770 @item @file{libAPI.a}
27771 @item @file{API.lib}
27772 @item @file{libAPI.dll}
27773 @item @file{API.dll}
27774 @end enumerate
27776 The first three are the GNU style import libraries. The third is the
27777 Microsoft style import libraries. The last two are the actual DLL names.
27779 Note that if the Ada package spec for @file{API.dll} contains the
27780 following pragma
27782 @smallexample @c ada
27783 @b{pragma} Linker_Options ("-lAPI");
27784 @end smallexample
27786 @noindent
27787 you do not have to add @option{-largs -lAPI} at the end of the
27788 @command{gnatmake} command.
27790 If any one of the items above is missing you will have to create it
27791 yourself. The following sections explain how to do so using as an
27792 example a fictitious DLL called @file{API.dll}.
27794 @node Creating an Ada Spec for the DLL Services
27795 @subsection Creating an Ada Spec for the DLL Services
27797 @noindent
27798 A DLL typically comes with a C/C++ header file which provides the
27799 definitions of the routines and variables exported by the DLL. The Ada
27800 equivalent of this header file is a package spec that contains definitions
27801 for the imported entities. If the DLL you intend to use does not come with
27802 an Ada spec you have to generate one such spec yourself. For example if
27803 the header file of @file{API.dll} is a file @file{api.h} containing the
27804 following two definitions:
27806 @smallexample
27807 @group
27808 @cartouche
27809 int some_var;
27810 int get (char *);
27811 @end cartouche
27812 @end group
27813 @end smallexample
27815 @noindent
27816 then the equivalent Ada spec could be:
27818 @smallexample @c ada
27819 @group
27820 @cartouche
27821 @b{with} Interfaces.C.Strings;
27822 @b{package} API @b{is}
27823    @b{use} Interfaces;
27825    Some_Var : C.int;
27826    @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
27828 @b{private}
27829    @b{pragma} Import (C, Get);
27830    @b{pragma} Import (DLL, Some_Var);
27831 @b{end} API;
27832 @end cartouche
27833 @end group
27834 @end smallexample
27836 @node Creating an Import Library
27837 @subsection Creating an Import Library
27838 @cindex Import library
27840 @menu
27841 * The Definition File::
27842 * GNAT-Style Import Library::
27843 * Microsoft-Style Import Library::
27844 @end menu
27846 @noindent
27847 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27848 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27849 with @file{API.dll} you can skip this section. You can also skip this
27850 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27851 as in this case it is possible to link directly against the
27852 DLL. Otherwise read on.
27854 @node The Definition File
27855 @subsubsection The Definition File
27856 @cindex Definition file
27857 @findex .def
27859 @noindent
27860 As previously mentioned, and unlike Unix systems, the list of symbols
27861 that are exported from a DLL must be provided explicitly in Windows.
27862 The main goal of a definition file is precisely that: list the symbols
27863 exported by a DLL. A definition file (usually a file with a @code{.def}
27864 suffix) has the following structure:
27866 @smallexample
27867 @group
27868 @cartouche
27869 @r{[}LIBRARY @var{name}@r{]}
27870 @r{[}DESCRIPTION @var{string}@r{]}
27871 EXPORTS
27872    @var{symbol1}
27873    @var{symbol2}
27874    @dots{}
27875 @end cartouche
27876 @end group
27877 @end smallexample
27879 @table @code
27880 @item LIBRARY @var{name}
27881 This section, which is optional, gives the name of the DLL.
27883 @item DESCRIPTION @var{string}
27884 This section, which is optional, gives a description string that will be
27885 embedded in the import library.
27887 @item EXPORTS
27888 This section gives the list of exported symbols (procedures, functions or
27889 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27890 section of @file{API.def} looks like:
27892 @smallexample
27893 @group
27894 @cartouche
27895 EXPORTS
27896    some_var
27897    get
27898 @end cartouche
27899 @end group
27900 @end smallexample
27901 @end table
27903 @noindent
27904 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27905 (@pxref{Windows Calling Conventions}) for a Stdcall
27906 calling convention function in the exported symbols list.
27908 @noindent
27909 There can actually be other sections in a definition file, but these
27910 sections are not relevant to the discussion at hand.
27912 @node GNAT-Style Import Library
27913 @subsubsection GNAT-Style Import Library
27915 @noindent
27916 To create a static import library from @file{API.dll} with the GNAT tools
27917 you should proceed as follows:
27919 @enumerate
27920 @item
27921 Create the definition file @file{API.def} (@pxref{The Definition File}).
27922 For that use the @code{dll2def} tool as follows:
27924 @smallexample
27925 $ dll2def API.dll > API.def
27926 @end smallexample
27928 @noindent
27929 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27930 to standard output the list of entry points in the DLL. Note that if
27931 some routines in the DLL have the @code{Stdcall} convention
27932 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27933 suffix then you'll have to edit @file{api.def} to add it, and specify
27934 @option{-k} to @command{gnatdll} when creating the import library.
27936 @noindent
27937 Here are some hints to find the right @code{@@}@var{nn} suffix.
27939 @enumerate
27940 @item
27941 If you have the Microsoft import library (.lib), it is possible to get
27942 the right symbols by using Microsoft @code{dumpbin} tool (see the
27943 corresponding Microsoft documentation for further details).
27945 @smallexample
27946 $ dumpbin /exports api.lib
27947 @end smallexample
27949 @item
27950 If you have a message about a missing symbol at link time the compiler
27951 tells you what symbol is expected. You just have to go back to the
27952 definition file and add the right suffix.
27953 @end enumerate
27955 @item
27956 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27957 (@pxref{Using gnatdll}) as follows:
27959 @smallexample
27960 $ gnatdll -e API.def -d API.dll
27961 @end smallexample
27963 @noindent
27964 @code{gnatdll} takes as input a definition file @file{API.def} and the
27965 name of the DLL containing the services listed in the definition file
27966 @file{API.dll}. The name of the static import library generated is
27967 computed from the name of the definition file as follows: if the
27968 definition file name is @var{xyz}@code{.def}, the import library name will
27969 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27970 @option{-e} could have been removed because the name of the definition
27971 file (before the ``@code{.def}'' suffix) is the same as the name of the
27972 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27973 @end enumerate
27975 @node Microsoft-Style Import Library
27976 @subsubsection Microsoft-Style Import Library
27978 @noindent
27979 With GNAT you can either use a GNAT-style or Microsoft-style import
27980 library. A Microsoft import library is needed only if you plan to make an
27981 Ada DLL available to applications developed with Microsoft
27982 tools (@pxref{Mixed-Language Programming on Windows}).
27984 To create a Microsoft-style import library for @file{API.dll} you
27985 should proceed as follows:
27987 @enumerate
27988 @item
27989 Create the definition file @file{API.def} from the DLL. For this use either
27990 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27991 tool (see the corresponding Microsoft documentation for further details).
27993 @item
27994 Build the actual import library using Microsoft's @code{lib} utility:
27996 @smallexample
27997 $ lib -machine:IX86 -def:API.def -out:API.lib
27998 @end smallexample
28000 @noindent
28001 If you use the above command the definition file @file{API.def} must
28002 contain a line giving the name of the DLL:
28004 @smallexample
28005 LIBRARY      "API"
28006 @end smallexample
28008 @noindent
28009 See the Microsoft documentation for further details about the usage of
28010 @code{lib}.
28011 @end enumerate
28013 @node Building DLLs with GNAT Project files
28014 @section Building DLLs with GNAT Project files
28015 @cindex DLLs, building
28017 @noindent
28018 There is nothing specific to Windows in the build process.
28019 @pxref{Library Projects}.
28021 @noindent
28022 Due to a system limitation, it is not possible under Windows to create threads
28023 when inside the @code{DllMain} routine which is used for auto-initialization
28024 of shared libraries, so it is not possible to have library level tasks in SALs.
28026 @node Building DLLs with GNAT
28027 @section Building DLLs with GNAT
28028 @cindex DLLs, building
28030 @noindent
28031 This section explain how to build DLLs using the GNAT built-in DLL
28032 support. With the following procedure it is straight forward to build
28033 and use DLLs with GNAT.
28035 @enumerate
28037 @item building object files
28039 The first step is to build all objects files that are to be included
28040 into the DLL. This is done by using the standard @command{gnatmake} tool.
28042 @item building the DLL
28044 To build the DLL you must use @command{gcc}'s @option{-shared} and
28045 @option{-shared-libgcc} options. It is quite simple to use this method:
28047 @smallexample
28048 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
28049 @end smallexample
28051 It is important to note that in this case all symbols found in the
28052 object files are automatically exported. It is possible to restrict
28053 the set of symbols to export by passing to @command{gcc} a definition
28054 file, @pxref{The Definition File}. For example:
28056 @smallexample
28057 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
28058 @end smallexample
28060 If you use a definition file you must export the elaboration procedures
28061 for every package that required one. Elaboration procedures are named
28062 using the package name followed by "_E".
28064 @item preparing DLL to be used
28066 For the DLL to be used by client programs the bodies must be hidden
28067 from it and the .ali set with read-only attribute. This is very important
28068 otherwise GNAT will recompile all packages and will not actually use
28069 the code in the DLL. For example:
28071 @smallexample
28072 $ mkdir apilib
28073 $ copy *.ads *.ali api.dll apilib
28074 $ attrib +R apilib\*.ali
28075 @end smallexample
28077 @end enumerate
28079 At this point it is possible to use the DLL by directly linking
28080 against it. Note that you must use the GNAT shared runtime when using
28081 GNAT shared libraries. This is achieved by using @option{-shared} binder's
28082 option.
28084 @smallexample
28085 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28086 @end smallexample
28088 @node Building DLLs with gnatdll
28089 @section Building DLLs with gnatdll
28090 @cindex DLLs, building
28092 @menu
28093 * Limitations When Using Ada DLLs from Ada::
28094 * Exporting Ada Entities::
28095 * Ada DLLs and Elaboration::
28096 * Ada DLLs and Finalization::
28097 * Creating a Spec for Ada DLLs::
28098 * Creating the Definition File::
28099 * Using gnatdll::
28100 @end menu
28102 @noindent
28103 Note that it is preferred to use GNAT Project files
28104 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28105 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28107 This section explains how to build DLLs containing Ada code using
28108 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28109 remainder of this section.
28111 The steps required to build an Ada DLL that is to be used by Ada as well as
28112 non-Ada applications are as follows:
28114 @enumerate
28115 @item
28116 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28117 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28118 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28119 skip this step if you plan to use the Ada DLL only from Ada applications.
28121 @item
28122 Your Ada code must export an initialization routine which calls the routine
28123 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28124 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28125 routine exported by the Ada DLL must be invoked by the clients of the DLL
28126 to initialize the DLL.
28128 @item
28129 When useful, the DLL should also export a finalization routine which calls
28130 routine @code{adafinal} generated by @command{gnatbind} to perform the
28131 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28132 The finalization routine exported by the Ada DLL must be invoked by the
28133 clients of the DLL when the DLL services are no further needed.
28135 @item
28136 You must provide a spec for the services exported by the Ada DLL in each
28137 of the programming languages to which you plan to make the DLL available.
28139 @item
28140 You must provide a definition file listing the exported entities
28141 (@pxref{The Definition File}).
28143 @item
28144 Finally you must use @code{gnatdll} to produce the DLL and the import
28145 library (@pxref{Using gnatdll}).
28146 @end enumerate
28148 @noindent
28149 Note that a relocatable DLL stripped using the @code{strip}
28150 binutils tool will not be relocatable anymore. To build a DLL without
28151 debug information pass @code{-largs -s} to @code{gnatdll}. This
28152 restriction does not apply to a DLL built using a Library Project.
28153 @pxref{Library Projects}.
28155 @node Limitations When Using Ada DLLs from Ada
28156 @subsection Limitations When Using Ada DLLs from Ada
28158 @noindent
28159 When using Ada DLLs from Ada applications there is a limitation users
28160 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28161 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28162 each Ada DLL includes the services of the GNAT run time that are necessary
28163 to the Ada code inside the DLL. As a result, when an Ada program uses an
28164 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28165 one in the main program.
28167 It is therefore not possible to exchange GNAT run-time objects between the
28168 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28169 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
28170 types, etc.
28172 It is completely safe to exchange plain elementary, array or record types,
28173 Windows object handles, etc.
28175 @node Exporting Ada Entities
28176 @subsection Exporting Ada Entities
28177 @cindex Export table
28179 @noindent
28180 Building a DLL is a way to encapsulate a set of services usable from any
28181 application. As a result, the Ada entities exported by a DLL should be
28182 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28183 any Ada name mangling. As an example here is an Ada package
28184 @code{API}, spec and body, exporting two procedures, a function, and a
28185 variable:
28187 @smallexample @c ada
28188 @group
28189 @cartouche
28190 @b{with} Interfaces.C; @b{use} Interfaces;
28191 @b{package} API @b{is}
28192    Count : C.int := 0;
28193    @b{function} Factorial (Val : C.int) @b{return} C.int;
28195    @b{procedure} Initialize_API;
28196    @b{procedure} Finalize_API;
28197    --@i{  Initialization & Finalization routines. More in the next section.}
28198 @b{private}
28199    @b{pragma} Export (C, Initialize_API);
28200    @b{pragma} Export (C, Finalize_API);
28201    @b{pragma} Export (C, Count);
28202    @b{pragma} Export (C, Factorial);
28203 @b{end} API;
28204 @end cartouche
28205 @end group
28206 @end smallexample
28208 @smallexample @c ada
28209 @group
28210 @cartouche
28211 @b{package} @b{body} API @b{is}
28212    @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
28213       Fact : C.int := 1;
28214    @b{begin}
28215       Count := Count + 1;
28216       @b{for} K @b{in} 1 .. Val @b{loop}
28217          Fact := Fact * K;
28218       @b{end} @b{loop};
28219       @b{return} Fact;
28220    @b{end} Factorial;
28222    @b{procedure} Initialize_API @b{is}
28223       @b{procedure} Adainit;
28224       @b{pragma} Import (C, Adainit);
28225    @b{begin}
28226       Adainit;
28227    @b{end} Initialize_API;
28229    @b{procedure} Finalize_API @b{is}
28230       @b{procedure} Adafinal;
28231       @b{pragma} Import (C, Adafinal);
28232    @b{begin}
28233       Adafinal;
28234    @b{end} Finalize_API;
28235 @b{end} API;
28236 @end cartouche
28237 @end group
28238 @end smallexample
28240 @noindent
28241 If the Ada DLL you are building will only be used by Ada applications
28242 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28243 convention. As an example, the previous package could be written as
28244 follows:
28246 @smallexample @c ada
28247 @group
28248 @cartouche
28249 @b{package} API @b{is}
28250    Count : Integer := 0;
28251    @b{function} Factorial (Val : Integer) @b{return} Integer;
28253    @b{procedure} Initialize_API;
28254    @b{procedure} Finalize_API;
28255    --@i{  Initialization and Finalization routines.}
28256 @b{end} API;
28257 @end cartouche
28258 @end group
28259 @end smallexample
28261 @smallexample @c ada
28262 @group
28263 @cartouche
28264 @b{package} @b{body} API @b{is}
28265    @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
28266       Fact : Integer := 1;
28267    @b{begin}
28268       Count := Count + 1;
28269       @b{for} K @b{in} 1 .. Val @b{loop}
28270          Fact := Fact * K;
28271       @b{end} @b{loop};
28272       @b{return} Fact;
28273    @b{end} Factorial;
28275    @dots{}
28276    --@i{  The remainder of this package body is unchanged.}
28277 @b{end} API;
28278 @end cartouche
28279 @end group
28280 @end smallexample
28282 @noindent
28283 Note that if you do not export the Ada entities with a @code{C} or
28284 @code{Stdcall} convention you will have to provide the mangled Ada names
28285 in the definition file of the Ada DLL
28286 (@pxref{Creating the Definition File}).
28288 @node Ada DLLs and Elaboration
28289 @subsection Ada DLLs and Elaboration
28290 @cindex DLLs and elaboration
28292 @noindent
28293 The DLL that you are building contains your Ada code as well as all the
28294 routines in the Ada library that are needed by it. The first thing a
28295 user of your DLL must do is elaborate the Ada code
28296 (@pxref{Elaboration Order Handling in GNAT}).
28298 To achieve this you must export an initialization routine
28299 (@code{Initialize_API} in the previous example), which must be invoked
28300 before using any of the DLL services. This elaboration routine must call
28301 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28302 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28303 @code{Initialize_Api} for an example. Note that the GNAT binder is
28304 automatically invoked during the DLL build process by the @code{gnatdll}
28305 tool (@pxref{Using gnatdll}).
28307 When a DLL is loaded, Windows systematically invokes a routine called
28308 @code{DllMain}. It would therefore be possible to call @code{adainit}
28309 directly from @code{DllMain} without having to provide an explicit
28310 initialization routine. Unfortunately, it is not possible to call
28311 @code{adainit} from the @code{DllMain} if your program has library level
28312 tasks because access to the @code{DllMain} entry point is serialized by
28313 the system (that is, only a single thread can execute ``through'' it at a
28314 time), which means that the GNAT run time will deadlock waiting for the
28315 newly created task to complete its initialization.
28317 @node Ada DLLs and Finalization
28318 @subsection Ada DLLs and Finalization
28319 @cindex DLLs and finalization
28321 @noindent
28322 When the services of an Ada DLL are no longer needed, the client code should
28323 invoke the DLL finalization routine, if available. The DLL finalization
28324 routine is in charge of releasing all resources acquired by the DLL. In the
28325 case of the Ada code contained in the DLL, this is achieved by calling
28326 routine @code{adafinal} generated by the GNAT binder
28327 (@pxref{Binding with Non-Ada Main Programs}).
28328 See the body of @code{Finalize_Api} for an
28329 example. As already pointed out the GNAT binder is automatically invoked
28330 during the DLL build process by the @code{gnatdll} tool
28331 (@pxref{Using gnatdll}).
28333 @node Creating a Spec for Ada DLLs
28334 @subsection Creating a Spec for Ada DLLs
28336 @noindent
28337 To use the services exported by the Ada DLL from another programming
28338 language (e.g.@: C), you have to translate the specs of the exported Ada
28339 entities in that language. For instance in the case of @code{API.dll},
28340 the corresponding C header file could look like:
28342 @smallexample
28343 @group
28344 @cartouche
28345 extern int *_imp__count;
28346 #define count (*_imp__count)
28347 int factorial (int);
28348 @end cartouche
28349 @end group
28350 @end smallexample
28352 @noindent
28353 It is important to understand that when building an Ada DLL to be used by
28354 other Ada applications, you need two different specs for the packages
28355 contained in the DLL: one for building the DLL and the other for using
28356 the DLL. This is because the @code{DLL} calling convention is needed to
28357 use a variable defined in a DLL, but when building the DLL, the variable
28358 must have either the @code{Ada} or @code{C} calling convention. As an
28359 example consider a DLL comprising the following package @code{API}:
28361 @smallexample @c ada
28362 @group
28363 @cartouche
28364 @b{package} API @b{is}
28365    Count : Integer := 0;
28366    @dots{}
28367    --@i{  Remainder of the package omitted.}
28368 @b{end} API;
28369 @end cartouche
28370 @end group
28371 @end smallexample
28373 @noindent
28374 After producing a DLL containing package @code{API}, the spec that
28375 must be used to import @code{API.Count} from Ada code outside of the
28376 DLL is:
28378 @smallexample @c ada
28379 @group
28380 @cartouche
28381 @b{package} API @b{is}
28382    Count : Integer;
28383    @b{pragma} Import (DLL, Count);
28384 @b{end} API;
28385 @end cartouche
28386 @end group
28387 @end smallexample
28389 @node Creating the Definition File
28390 @subsection Creating the Definition File
28392 @noindent
28393 The definition file is the last file needed to build the DLL. It lists
28394 the exported symbols. As an example, the definition file for a DLL
28395 containing only package @code{API} (where all the entities are exported
28396 with a @code{C} calling convention) is:
28398 @smallexample
28399 @group
28400 @cartouche
28401 EXPORTS
28402     count
28403     factorial
28404     finalize_api
28405     initialize_api
28406 @end cartouche
28407 @end group
28408 @end smallexample
28410 @noindent
28411 If the @code{C} calling convention is missing from package @code{API},
28412 then the definition file contains the mangled Ada names of the above
28413 entities, which in this case are:
28415 @smallexample
28416 @group
28417 @cartouche
28418 EXPORTS
28419     api__count
28420     api__factorial
28421     api__finalize_api
28422     api__initialize_api
28423 @end cartouche
28424 @end group
28425 @end smallexample
28427 @node Using gnatdll
28428 @subsection Using @code{gnatdll}
28429 @findex gnatdll
28431 @menu
28432 * gnatdll Example::
28433 * gnatdll behind the Scenes::
28434 * Using dlltool::
28435 @end menu
28437 @noindent
28438 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28439 and non-Ada sources that make up your DLL have been compiled.
28440 @code{gnatdll} is actually in charge of two distinct tasks: build the
28441 static import library for the DLL and the actual DLL. The form of the
28442 @code{gnatdll} command is
28444 @smallexample
28445 @cartouche
28446 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28447 @c Expanding @ovar macro inline (explanation in macro def comments)
28448 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28449 @end cartouche
28450 @end smallexample
28452 @noindent
28453 where @var{list-of-files} is a list of ALI and object files. The object
28454 file list must be the exact list of objects corresponding to the non-Ada
28455 sources whose services are to be included in the DLL. The ALI file list
28456 must be the exact list of ALI files for the corresponding Ada sources
28457 whose services are to be included in the DLL. If @var{list-of-files} is
28458 missing, only the static import library is generated.
28460 @noindent
28461 You may specify any of the following switches to @code{gnatdll}:
28463 @table @code
28464 @c @item -a@ovar{address}
28465 @c Expanding @ovar macro inline (explanation in macro def comments)
28466 @item -a@r{[}@var{address}@r{]}
28467 @cindex @option{-a} (@code{gnatdll})
28468 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28469 specified the default address @var{0x11000000} will be used. By default,
28470 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28471 advise the reader to build relocatable DLL.
28473 @item -b @var{address}
28474 @cindex @option{-b} (@code{gnatdll})
28475 Set the relocatable DLL base address. By default the address is
28476 @code{0x11000000}.
28478 @item -bargs @var{opts}
28479 @cindex @option{-bargs} (@code{gnatdll})
28480 Binder options. Pass @var{opts} to the binder.
28482 @item -d @var{dllfile}
28483 @cindex @option{-d} (@code{gnatdll})
28484 @var{dllfile} is the name of the DLL. This switch must be present for
28485 @code{gnatdll} to do anything. The name of the generated import library is
28486 obtained algorithmically from @var{dllfile} as shown in the following
28487 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28488 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28489 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28490 as shown in the following example:
28491 if @var{dllfile} is @code{xyz.dll}, the definition
28492 file used is @code{xyz.def}.
28494 @item -e @var{deffile}
28495 @cindex @option{-e} (@code{gnatdll})
28496 @var{deffile} is the name of the definition file.
28498 @item -g
28499 @cindex @option{-g} (@code{gnatdll})
28500 Generate debugging information. This information is stored in the object
28501 file and copied from there to the final DLL file by the linker,
28502 where it can be read by the debugger. You must use the
28503 @option{-g} switch if you plan on using the debugger or the symbolic
28504 stack traceback.
28506 @item -h
28507 @cindex @option{-h} (@code{gnatdll})
28508 Help mode. Displays @code{gnatdll} switch usage information.
28510 @item -Idir
28511 @cindex @option{-I} (@code{gnatdll})
28512 Direct @code{gnatdll} to search the @var{dir} directory for source and
28513 object files needed to build the DLL.
28514 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28516 @item -k
28517 @cindex @option{-k} (@code{gnatdll})
28518 Removes the @code{@@}@var{nn} suffix from the import library's exported
28519 names, but keeps them for the link names. You must specify this
28520 option if you want to use a @code{Stdcall} function in a DLL for which
28521 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28522 of the Windows NT DLL for example. This option has no effect when
28523 @option{-n} option is specified.
28525 @item -l @var{file}
28526 @cindex @option{-l} (@code{gnatdll})
28527 The list of ALI and object files used to build the DLL are listed in
28528 @var{file}, instead of being given in the command line. Each line in
28529 @var{file} contains the name of an ALI or object file.
28531 @item -n
28532 @cindex @option{-n} (@code{gnatdll})
28533 No Import. Do not create the import library.
28535 @item -q
28536 @cindex @option{-q} (@code{gnatdll})
28537 Quiet mode. Do not display unnecessary messages.
28539 @item -v
28540 @cindex @option{-v} (@code{gnatdll})
28541 Verbose mode. Display extra information.
28543 @item -largs @var{opts}
28544 @cindex @option{-largs} (@code{gnatdll})
28545 Linker options. Pass @var{opts} to the linker.
28546 @end table
28548 @node gnatdll Example
28549 @subsubsection @code{gnatdll} Example
28551 @noindent
28552 As an example the command to build a relocatable DLL from @file{api.adb}
28553 once @file{api.adb} has been compiled and @file{api.def} created is
28555 @smallexample
28556 $ gnatdll -d api.dll api.ali
28557 @end smallexample
28559 @noindent
28560 The above command creates two files: @file{libapi.dll.a} (the import
28561 library) and @file{api.dll} (the actual DLL). If you want to create
28562 only the DLL, just type:
28564 @smallexample
28565 $ gnatdll -d api.dll -n api.ali
28566 @end smallexample
28568 @noindent
28569 Alternatively if you want to create just the import library, type:
28571 @smallexample
28572 $ gnatdll -d api.dll
28573 @end smallexample
28575 @node gnatdll behind the Scenes
28576 @subsubsection @code{gnatdll} behind the Scenes
28578 @noindent
28579 This section details the steps involved in creating a DLL. @code{gnatdll}
28580 does these steps for you. Unless you are interested in understanding what
28581 goes on behind the scenes, you should skip this section.
28583 We use the previous example of a DLL containing the Ada package @code{API},
28584 to illustrate the steps necessary to build a DLL. The starting point is a
28585 set of objects that will make up the DLL and the corresponding ALI
28586 files. In the case of this example this means that @file{api.o} and
28587 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28588 the following:
28590 @enumerate
28591 @item
28592 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28593 the information necessary to generate relocation information for the
28594 DLL.
28596 @smallexample
28597 @group
28598 $ gnatbind -n api
28599 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28600 @end group
28601 @end smallexample
28603 @noindent
28604 In addition to the base file, the @command{gnatlink} command generates an
28605 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28606 asks @command{gnatlink} to generate the routines @code{DllMain} and
28607 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28608 is loaded into memory.
28610 @item
28611 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28612 export table (@file{api.exp}). The export table contains the relocation
28613 information in a form which can be used during the final link to ensure
28614 that the Windows loader is able to place the DLL anywhere in memory.
28616 @smallexample
28617 @group
28618 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28619           --output-exp api.exp
28620 @end group
28621 @end smallexample
28623 @item
28624 @code{gnatdll} builds the base file using the new export table. Note that
28625 @command{gnatbind} must be called once again since the binder generated file
28626 has been deleted during the previous call to @command{gnatlink}.
28628 @smallexample
28629 @group
28630 $ gnatbind -n api
28631 $ gnatlink api -o api.jnk api.exp -mdll
28632       -Wl,--base-file,api.base
28633 @end group
28634 @end smallexample
28636 @item
28637 @code{gnatdll} builds the new export table using the new base file and
28638 generates the DLL import library @file{libAPI.dll.a}.
28640 @smallexample
28641 @group
28642 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28643           --output-exp api.exp --output-lib libAPI.a
28644 @end group
28645 @end smallexample
28647 @item
28648 Finally @code{gnatdll} builds the relocatable DLL using the final export
28649 table.
28651 @smallexample
28652 @group
28653 $ gnatbind -n api
28654 $ gnatlink api api.exp -o api.dll -mdll
28655 @end group
28656 @end smallexample
28657 @end enumerate
28659 @node Using dlltool
28660 @subsubsection Using @code{dlltool}
28662 @noindent
28663 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28664 DLLs and static import libraries. This section summarizes the most
28665 common @code{dlltool} switches. The form of the @code{dlltool} command
28668 @smallexample
28669 @c $ dlltool @ovar{switches}
28670 @c Expanding @ovar macro inline (explanation in macro def comments)
28671 $ dlltool @r{[}@var{switches}@r{]}
28672 @end smallexample
28674 @noindent
28675 @code{dlltool} switches include:
28677 @table @option
28678 @item --base-file @var{basefile}
28679 @cindex @option{--base-file} (@command{dlltool})
28680 Read the base file @var{basefile} generated by the linker. This switch
28681 is used to create a relocatable DLL.
28683 @item --def @var{deffile}
28684 @cindex @option{--def} (@command{dlltool})
28685 Read the definition file.
28687 @item --dllname @var{name}
28688 @cindex @option{--dllname} (@command{dlltool})
28689 Gives the name of the DLL. This switch is used to embed the name of the
28690 DLL in the static import library generated by @code{dlltool} with switch
28691 @option{--output-lib}.
28693 @item -k
28694 @cindex @option{-k} (@command{dlltool})
28695 Kill @code{@@}@var{nn} from exported names
28696 (@pxref{Windows Calling Conventions}
28697 for a discussion about @code{Stdcall}-style symbols.
28699 @item --help
28700 @cindex @option{--help} (@command{dlltool})
28701 Prints the @code{dlltool} switches with a concise description.
28703 @item --output-exp @var{exportfile}
28704 @cindex @option{--output-exp} (@command{dlltool})
28705 Generate an export file @var{exportfile}. The export file contains the
28706 export table (list of symbols in the DLL) and is used to create the DLL.
28708 @item --output-lib @var{libfile}
28709 @cindex @option{--output-lib} (@command{dlltool})
28710 Generate a static import library @var{libfile}.
28712 @item -v
28713 @cindex @option{-v} (@command{dlltool})
28714 Verbose mode.
28716 @item --as @var{assembler-name}
28717 @cindex @option{--as} (@command{dlltool})
28718 Use @var{assembler-name} as the assembler. The default is @code{as}.
28719 @end table
28721 @node GNAT and Windows Resources
28722 @section GNAT and Windows Resources
28723 @cindex Resources, windows
28725 @menu
28726 * Building Resources::
28727 * Compiling Resources::
28728 * Using Resources::
28729 @end menu
28731 @noindent
28732 Resources are an easy way to add Windows specific objects to your
28733 application. The objects that can be added as resources include:
28735 @itemize @bullet
28736 @item menus
28738 @item accelerators
28740 @item dialog boxes
28742 @item string tables
28744 @item bitmaps
28746 @item cursors
28748 @item icons
28750 @item fonts
28752 @item version information
28753 @end itemize
28755 For example, a version information resource can be defined as follow and
28756 embedded into an executable or DLL:
28758 A version information resource can be used to embed information into an
28759 executable or a DLL. These information can be viewed using the file properties
28760 from the Windows Explorer. Here is an example of a version information
28761 resource:
28763 @smallexample
28764 @group
28765 1 VERSIONINFO
28766 FILEVERSION     1,0,0,0
28767 PRODUCTVERSION  1,0,0,0
28768 BEGIN
28769   BLOCK "StringFileInfo"
28770   BEGIN
28771     BLOCK "080904E4"
28772     BEGIN
28773       VALUE "CompanyName", "My Company Name"
28774       VALUE "FileDescription", "My application"
28775       VALUE "FileVersion", "1.0"
28776       VALUE "InternalName", "my_app"
28777       VALUE "LegalCopyright", "My Name"
28778       VALUE "OriginalFilename", "my_app.exe"
28779       VALUE "ProductName", "My App"
28780       VALUE "ProductVersion", "1.0"
28781     END
28782   END
28784   BLOCK "VarFileInfo"
28785   BEGIN
28786     VALUE "Translation", 0x809, 1252
28787   END
28789 @end group
28790 @end smallexample
28792 The value @code{0809} (langID) is for the U.K English language and
28793 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28794 multilingual.
28796 @noindent
28797 This section explains how to build, compile and use resources. Note that this
28798 section does not cover all resource objects, for a complete description see
28799 the corresponding Microsoft documentation.
28801 @node Building Resources
28802 @subsection Building Resources
28803 @cindex Resources, building
28805 @noindent
28806 A resource file is an ASCII file. By convention resource files have an
28807 @file{.rc} extension.
28808 The easiest way to build a resource file is to use Microsoft tools
28809 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28810 @code{dlgedit.exe} to build dialogs.
28811 It is always possible to build an @file{.rc} file yourself by writing a
28812 resource script.
28814 It is not our objective to explain how to write a resource file. A
28815 complete description of the resource script language can be found in the
28816 Microsoft documentation.
28818 @node Compiling Resources
28819 @subsection Compiling Resources
28820 @findex rc
28821 @findex windres
28822 @cindex Resources, compiling
28824 @noindent
28825 This section describes how to build a GNAT-compatible (COFF) object file
28826 containing the resources. This is done using the Resource Compiler
28827 @code{windres} as follows:
28829 @smallexample
28830 $ windres -i myres.rc -o myres.o
28831 @end smallexample
28833 @noindent
28834 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28835 file. You can specify an alternate preprocessor (usually named
28836 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28837 parameter. A list of all possible options may be obtained by entering
28838 the command @code{windres} @option{--help}.
28840 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28841 to produce a @file{.res} file (binary resource file). See the
28842 corresponding Microsoft documentation for further details. In this case
28843 you need to use @code{windres} to translate the @file{.res} file to a
28844 GNAT-compatible object file as follows:
28846 @smallexample
28847 $ windres -i myres.res -o myres.o
28848 @end smallexample
28850 @node Using Resources
28851 @subsection Using Resources
28852 @cindex Resources, using
28854 @noindent
28855 To include the resource file in your program just add the
28856 GNAT-compatible object file for the resource(s) to the linker
28857 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28858 option:
28860 @smallexample
28861 $ gnatmake myprog -largs myres.o
28862 @end smallexample
28864 @node Debugging a DLL
28865 @section Debugging a DLL
28866 @cindex DLL debugging
28868 @menu
28869 * Program and DLL Both Built with GCC/GNAT::
28870 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28871 @end menu
28873 @noindent
28874 Debugging a DLL is similar to debugging a standard program. But
28875 we have to deal with two different executable parts: the DLL and the
28876 program that uses it. We have the following four possibilities:
28878 @enumerate 1
28879 @item
28880 The program and the DLL are built with @code{GCC/GNAT}.
28881 @item
28882 The program is built with foreign tools and the DLL is built with
28883 @code{GCC/GNAT}.
28884 @item
28885 The program is built with @code{GCC/GNAT} and the DLL is built with
28886 foreign tools.
28887 @end enumerate
28889 @noindent
28890 In this section we address only cases one and two above.
28891 There is no point in trying to debug
28892 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28893 information in it. To do so you must use a debugger compatible with the
28894 tools suite used to build the DLL.
28896 @node Program and DLL Both Built with GCC/GNAT
28897 @subsection Program and DLL Both Built with GCC/GNAT
28899 @noindent
28900 This is the simplest case. Both the DLL and the program have @code{GDB}
28901 compatible debugging information. It is then possible to break anywhere in
28902 the process. Let's suppose here that the main procedure is named
28903 @code{ada_main} and that in the DLL there is an entry point named
28904 @code{ada_dll}.
28906 @noindent
28907 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28908 program must have been built with the debugging information (see GNAT -g
28909 switch). Here are the step-by-step instructions for debugging it:
28911 @enumerate 1
28912 @item Launch @code{GDB} on the main program.
28914 @smallexample
28915 $ gdb -nw ada_main
28916 @end smallexample
28918 @item Start the program and stop at the beginning of the main procedure
28920 @smallexample
28921 (gdb) start
28922 @end smallexample
28924 @noindent
28925 This step is required to be able to set a breakpoint inside the DLL. As long
28926 as the program is not run, the DLL is not loaded. This has the
28927 consequence that the DLL debugging information is also not loaded, so it is not
28928 possible to set a breakpoint in the DLL.
28930 @item Set a breakpoint inside the DLL
28932 @smallexample
28933 (gdb) break ada_dll
28934 (gdb) cont
28935 @end smallexample
28937 @end enumerate
28939 @noindent
28940 At this stage a breakpoint is set inside the DLL. From there on
28941 you can use the standard approach to debug the whole program
28942 (@pxref{Running and Debugging Ada Programs}).
28944 @ignore
28945 @c This used to work, probably because the DLLs were non-relocatable
28946 @c keep this section around until the problem is sorted out.
28948 To break on the @code{DllMain} routine it is not possible to follow
28949 the procedure above. At the time the program stop on @code{ada_main}
28950 the @code{DllMain} routine as already been called. Either you can use
28951 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28953 @enumerate 1
28954 @item Launch @code{GDB} on the main program.
28956 @smallexample
28957 $ gdb ada_main
28958 @end smallexample
28960 @item Load DLL symbols
28962 @smallexample
28963 (gdb) add-sym api.dll
28964 @end smallexample
28966 @item Set a breakpoint inside the DLL
28968 @smallexample
28969 (gdb) break ada_dll.adb:45
28970 @end smallexample
28972 Note that at this point it is not possible to break using the routine symbol
28973 directly as the program is not yet running. The solution is to break
28974 on the proper line (break in @file{ada_dll.adb} line 45).
28976 @item Start the program
28978 @smallexample
28979 (gdb) run
28980 @end smallexample
28982 @end enumerate
28983 @end ignore
28985 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28986 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28988 @menu
28989 * Debugging the DLL Directly::
28990 * Attaching to a Running Process::
28991 @end menu
28993 @noindent
28994 In this case things are slightly more complex because it is not possible to
28995 start the main program and then break at the beginning to load the DLL and the
28996 associated DLL debugging information. It is not possible to break at the
28997 beginning of the program because there is no @code{GDB} debugging information,
28998 and therefore there is no direct way of getting initial control. This
28999 section addresses this issue by describing some methods that can be used
29000 to break somewhere in the DLL to debug it.
29002 @noindent
29003 First suppose that the main procedure is named @code{main} (this is for
29004 example some C code built with Microsoft Visual C) and that there is a
29005 DLL named @code{test.dll} containing an Ada entry point named
29006 @code{ada_dll}.
29008 @noindent
29009 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
29010 been built with debugging information (see GNAT -g option).
29012 @node Debugging the DLL Directly
29013 @subsubsection Debugging the DLL Directly
29015 @enumerate 1
29016 @item
29017 Find out the executable starting address
29019 @smallexample
29020 $ objdump --file-header main.exe
29021 @end smallexample
29023 The starting address is reported on the last line. For example:
29025 @smallexample
29026 main.exe:     file format pei-i386
29027 architecture: i386, flags 0x0000010a:
29028 EXEC_P, HAS_DEBUG, D_PAGED
29029 start address 0x00401010
29030 @end smallexample
29032 @item
29033 Launch the debugger on the executable.
29035 @smallexample
29036 $ gdb main.exe
29037 @end smallexample
29039 @item
29040 Set a breakpoint at the starting address, and launch the program.
29042 @smallexample
29043 $ (gdb) break *0x00401010
29044 $ (gdb) run
29045 @end smallexample
29047 The program will stop at the given address.
29049 @item
29050 Set a breakpoint on a DLL subroutine.
29052 @smallexample
29053 (gdb) break ada_dll.adb:45
29054 @end smallexample
29056 Or if you want to break using a symbol on the DLL, you need first to
29057 select the Ada language (language used by the DLL).
29059 @smallexample
29060 (gdb) set language ada
29061 (gdb) break ada_dll
29062 @end smallexample
29064 @item
29065 Continue the program.
29067 @smallexample
29068 (gdb) cont
29069 @end smallexample
29071 @noindent
29072 This will run the program until it reaches the breakpoint that has been
29073 set. From that point you can use the standard way to debug a program
29074 as described in (@pxref{Running and Debugging Ada Programs}).
29076 @end enumerate
29078 @noindent
29079 It is also possible to debug the DLL by attaching to a running process.
29081 @node Attaching to a Running Process
29082 @subsubsection Attaching to a Running Process
29083 @cindex DLL debugging, attach to process
29085 @noindent
29086 With @code{GDB} it is always possible to debug a running process by
29087 attaching to it. It is possible to debug a DLL this way. The limitation
29088 of this approach is that the DLL must run long enough to perform the
29089 attach operation. It may be useful for instance to insert a time wasting
29090 loop in the code of the DLL to meet this criterion.
29092 @enumerate 1
29094 @item Launch the main program @file{main.exe}.
29096 @smallexample
29097 $ main
29098 @end smallexample
29100 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29101 that the process PID for @file{main.exe} is 208.
29103 @item Launch gdb.
29105 @smallexample
29106 $ gdb
29107 @end smallexample
29109 @item Attach to the running process to be debugged.
29111 @smallexample
29112 (gdb) attach 208
29113 @end smallexample
29115 @item Load the process debugging information.
29117 @smallexample
29118 (gdb) symbol-file main.exe
29119 @end smallexample
29121 @item Break somewhere in the DLL.
29123 @smallexample
29124 (gdb) break ada_dll
29125 @end smallexample
29127 @item Continue process execution.
29129 @smallexample
29130 (gdb) cont
29131 @end smallexample
29133 @end enumerate
29135 @noindent
29136 This last step will resume the process execution, and stop at
29137 the breakpoint we have set. From there you can use the standard
29138 approach to debug a program as described in
29139 (@pxref{Running and Debugging Ada Programs}).
29141 @node Setting Stack Size from gnatlink
29142 @section Setting Stack Size from @command{gnatlink}
29144 @noindent
29145 It is possible to specify the program stack size at link time. On modern
29146 versions of Windows, starting with XP, this is mostly useful to set the size of
29147 the main stack (environment task). The other task stacks are set with pragma
29148 Storage_Size or with the @command{gnatbind -d} command.
29150 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
29151 reserve size of individual tasks, the link-time stack size applies to all
29152 tasks, and pragma Storage_Size has no effect.
29153 In particular, Stack Overflow checks are made against this
29154 link-time specified size.
29156 This setting can be done with
29157 @command{gnatlink} using either:
29159 @itemize @bullet
29161 @item using @option{-Xlinker} linker option
29163 @smallexample
29164 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29165 @end smallexample
29167 This sets the stack reserve size to 0x10000 bytes and the stack commit
29168 size to 0x1000 bytes.
29170 @item using @option{-Wl} linker option
29172 @smallexample
29173 $ gnatlink hello -Wl,--stack=0x1000000
29174 @end smallexample
29176 This sets the stack reserve size to 0x1000000 bytes. Note that with
29177 @option{-Wl} option it is not possible to set the stack commit size
29178 because the coma is a separator for this option.
29180 @end itemize
29182 @node Setting Heap Size from gnatlink
29183 @section Setting Heap Size from @command{gnatlink}
29185 @noindent
29186 Under Windows systems, it is possible to specify the program heap size from
29187 @command{gnatlink} using either:
29189 @itemize @bullet
29191 @item using @option{-Xlinker} linker option
29193 @smallexample
29194 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29195 @end smallexample
29197 This sets the heap reserve size to 0x10000 bytes and the heap commit
29198 size to 0x1000 bytes.
29200 @item using @option{-Wl} linker option
29202 @smallexample
29203 $ gnatlink hello -Wl,--heap=0x1000000
29204 @end smallexample
29206 This sets the heap reserve size to 0x1000000 bytes. Note that with
29207 @option{-Wl} option it is not possible to set the heap commit size
29208 because the coma is a separator for this option.
29210 @end itemize
29212 @node Mac OS Topics
29213 @appendix Mac OS Topics
29214 @cindex OS X
29216 @noindent
29217 This chapter describes topics that are specific to Apple's OS X
29218 platform.
29220 @menu
29221 * Codesigning the Debugger::
29222 @end menu
29224 @node Codesigning the Debugger
29225 @section Codesigning the Debugger
29227 @noindent
29228 The Darwin Kernel requires the debugger to have special permissions
29229 before it is allowed to control other processes. These permissions
29230 are granted by codesigning the GDB executable. Without these
29231 permissions, the debugger will report error messages such as:
29233 @smallexample
29234 Starting program: /x/y/foo
29235 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
29236  (please check gdb is codesigned - see taskgated(8))
29237 @end smallexample
29239 Codesigning requires a certificate.  The following procedure explains
29240 how to create one:
29242 @itemize @bullet
29243 @item Start the Keychain Access application (in
29244 /Applications/Utilities/Keychain Access.app)
29246 @item Select the Keychain Access -> Certificate Assistant ->
29247 Create a Certificate... menu
29249 @item Then:
29251 @itemize @bullet
29252 @item Choose a name for the new certificate (this procedure will use
29253 "gdb-cert" as an example)
29255 @item Set "Identity Type" to "Self Signed Root"
29257 @item Set "Certificate Type" to "Code Signing"
29259 @item Activate the "Let me override defaults" option
29261 @end itemize
29263 @item Click several times on "Continue" until the "Specify a Location
29264 For The Certificate" screen appears, then set "Keychain" to "System"
29266 @item Click on "Continue" until the certificate is created
29268 @item Finally, in the view, double-click on the new certificate,
29269 and set "When using this certificate" to "Always Trust"
29271 @item Exit the Keychain Access application and restart the computer
29272 (this is unfortunately required)
29274 @end itemize
29276 Once a certificate has been created, the debugger can be codesigned
29277 as follow. In a Terminal, run the following command...
29279 @smallexample
29280 codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
29281 @end smallexample
29283 ... where "gdb-cert" should be replaced by the actual certificate
29284 name chosen above, and <gnat_install_prefix> should be replaced by
29285 the location where you installed GNAT.  Also, be sure that users are
29286 in the Unix group @samp{_developer}.
29288 @c **********************************
29289 @c * GNU Free Documentation License *
29290 @c **********************************
29291 @include fdl.texi
29292 @c GNU Free Documentation License
29294 @node Index
29295 @unnumbered Index
29297 @printindex cp
29299 @contents
29300 @c Put table of contents at end, otherwise it precedes the "title page" in
29301 @c the .txt version
29302 @c Edit the pdf file to move the contents to the beginning, after the title
29303 @c page
29305 @bye